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
13,561
utils.lisp
lepisma_pigeon/src/utils.lisp
(in-package #:pigeon) (cl-interpol:enable-interpol-syntax) (defun prepend-pad (lines pad-str) (mapcar (cut format nil "~A~A" pad-str <>) lines)) (defun get-line-pad (line pad-char &optional (at 0)) (if (or (= at (length line)) (char-not-equal (elt line at) pad-char)) at (get-line-pad line pad-char (+ 1 at)))) (defun get-min-pad (lines pad-char) (let ((lines (remove-if (cut string-equal "" <>) lines))) (if (null lines) 0 (apply #'min (mapcar (cut get-line-pad <> pad-char) lines))))) (defun indent-string (text &key indent) (let ((pad (make-string indent :initial-element #\space))) (cl-strings:join (prepend-pad (cl-strings:split text #\linefeed) pad) :separator (string #\linefeed)))) (defun dedent-string (text) "Dedent common whitespace from the text." (let* ((lines (cl-strings:split text #\linefeed)) (n-pad (get-min-pad lines #\ ))) (cl-strings:join (mapcar (cut subseq <> n-pad) lines) :separator #?"\n"))) (defun kebab-to-snake (text) (cl-strings:replace-all text "-" "_"))
1,049
Common Lisp
.lisp
23
41.869565
85
0.65098
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
b42b1676e0a20efce28d7e058776de288bf58132796b4af43338265b1ee98145
13,561
[ -1 ]
13,562
read.lisp
lepisma_pigeon/src/read.lisp
;;; Reading and loading stuff (in-package #:pigeon) (cl-interpol:enable-interpol-syntax) (defun load-pgl (input-path-spec) "Load a pgl file with macro definitions. Argument doesn't contain extension." (let ((file-name (concatenate 'string (string-downcase (symbol-name input-path-spec)) ".pgl"))) (with-open-file (fp file-name) (loop for form = (read fp nil) while form do (match form ((list* 'defmacro name _) (eval form) (setf *macros* (cons name *macros*))) (form (eval form))))))) (defun read-until (stream okay-cond) (map 'string #'identity (loop for c = (peek-char nil stream nil nil t) while (and c (funcall okay-cond c)) do (read-char stream nil nil t) collect c))) (defun read-open-close (stream open-char close-char) "Read a nest string following open and close chars." (let ((nesting 0)) (map 'string #'identity (loop for c = (peek-char nil stream nil nil t) while (and c (or (char-not-equal close-char c) (not (zerop nesting)))) do (progn (read-char stream nil nil t) (cond ((char-equal open-char c) (incf nesting)) ((char-equal close-char c) (decf nesting)))) collect c)))) (defun read-case-sensitive-id (stream subchar arg) (declare (ignore subchar arg)) (let ((name (read-until stream (lambda (c) (or (alphanumericp c) (char-equal #\_ c)))))) `(cons 'id ,name))) (defun read-pigeon-list (stream char) (declare (ignore char)) (let ((list-stuff (read-open-close stream #\[ #\]))) (read-char stream nil nil t) ;; discarding the last #\] (read-from-string #?"(pg-list ${list-stuff})"))) (defun read-pigeon-list-comp (stream subchar arg) (declare (ignore arg)) (ematch (read-pigeon-list stream subchar) ((list 'pg-list thing :for item :in collection) `(pg-list-comp ,thing ,item ,collection)) ((list 'pg-list thing :for item :in collection :if condition) `(pg-list-comp ,thing ,item ,collection ,condition)))) (defun read-python-code (stream subchar arg) (declare (ignore subchar arg)) (let ((code (string-trim #?"\n" (read-open-close stream #\< #\>)))) (read-char stream nil nil t) `(pg-python ,code))) (named-readtables:defreadtable :pigeon-syntax (:merge :standard :interpol-syntax) (:macro-char #\[ #'read-pigeon-list) (:macro-char #\@ :dispatch) (:dispatch-macro-char #\@ #\[ #'read-pigeon-list-comp) (:dispatch-macro-char #\@ #\< #'read-python-code) (:macro-char #\# :dispatch) (:dispatch-macro-char #\# #\i #'read-case-sensitive-id)) (defun read-pg (input-path) "Read pigeon code forms" (let ((*readtable* (named-readtables:find-readtable :pigeon-syntax))) (with-open-file (fp input-path) (loop for form = (read fp nil) while form collect form))))
3,027
Common Lisp
.lisp
69
36.173913
97
0.603799
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
5fa4be02d1bd3c63b05848c6449aea20e0f555feabe674bd69469b25bdb0cb17
13,562
[ -1 ]
13,563
format.lisp
lepisma_pigeon/src/format.lisp
;;; Functions for formatting the primitives that translate directly to python (in-package #:pigeon) (cl-interpol:enable-interpol-syntax) (defparameter *indent* 4 "Indent for the generated python code. We use spaces around here.") (defparameter *infix-ops* '(+ - * / % ** == != > < >= <= >> << or and is in) "Infix operators in python") (defparameter *statements* '(return not) "Statements that have direct call pattern in python.") (defun lambda-parse-args (fn-form) (let ((args (subseq (symbol-name fn-form) 3))) (map 'list #'identity args))) (defun add-return (body) "Add a return statement to the last item of the body" (append (subseq body 0 (- (length body) 1)) (list (cons 'return (last body))))) (defun fmt-lambda (fn-form body) (let ((args (unless (eq fn-form 'fn) (lambda-parse-args fn-form)))) #?"(lambda ${(fmt-lambda-list args)}: ${(fmt body)})")) (defun fmt-string (string) "Need to check for multiline strings too." (if (find #\linefeed string) #?"\"\"\"${string}\"\"\"" #?"\"${string}\"")) (defun fmt-atom (exp) (cond ((characterp exp) (string-downcase (string exp))) ((stringp exp) (fmt-string exp)) ((eq 't exp) "True") ((eq 'f exp) "False") ((eq 'none exp) "None") ((null exp) "[]") ((symbolp exp) (fmt-id exp)) ((numberp exp) (format nil "~A" exp)) ((vectorp exp) (fmt-vector exp)))) (defun fmt-id (exp) (ematch exp ((list 'cons (cons 'quote _) id-string) id-string) ((guard x (member exp *infix-ops*)) (symbol-name x)) (_ (string-downcase (kebab-to-snake (symbol-name exp)))))) (defun fmt-lambda-list (args &optional segments) (if (null args) (cl-strings:join (nreverse segments) :separator ", ") (cond ((kid-p (car args)) (fmt-lambda-list (cddr args) (cons #?"${(fmt (car args))}=${(fmt (cadr args))}" segments))) (t (fmt-lambda-list (cdr args) (cons (fmt (car args)) segments)))))) (defun fmt-block (body &optional no-indent) (indent-string (cl-strings:join (mapcar #'fmt body) :separator (string #\linefeed)) :indent (if no-indent 0 *indent*))) (defun fmt-fn (name lambda-list body) (let ((body (fmt-block (add-return body)))) #?"def ${(fmt-id name)}(${(fmt-lambda-list lambda-list)}):\n${body}")) (defun fmt-call-infix (fn args) (let ((text (cl-strings:join (mapcar #'fmt args) :separator #?" ${(fmt fn)} "))) #?"(${text})")) (defun fmt-cond-clause (clause &optional first) (ematch clause ((cons t body) #?"else:\n${(fmt-block body)}") ((cons condition body) (cond (first #?"if ${(fmt condition)}:\n${(fmt-block body)}") (t #?"elif ${(fmt condition)}:\n${(fmt-block body)}"))))) (defun fmt-cond (clauses) (cl-strings:join (cons (fmt-cond-clause (car clauses) t) (mapcar #'fmt-cond-clause (cdr clauses))) :separator (string #\linefeed))) (defun fmt-call (fn args) (cond ((member fn *infix-ops*) (fmt-call-infix fn args)) ((member fn *macros*) (fmt (macroexpand-1 `(,fn ,@args)))) ((member fn *statements*) #?"${(fmt fn)} ${(fmt-lambda-list args)}") ((eq fn 'cond) (fmt-cond args)) (t #?"${(fmt fn)}(${(fmt-lambda-list args)})"))) (defun fmt-setf (lhs rhs) #?"${(fmt lhs)} = ${(fmt rhs)}") (defun fmt-list-comp (thing item collection &optional condition) (let ((last-bit (if condition #?" if ${(fmt condition)}" ""))) #?"[${(fmt thing)} for ${(fmt item)} in ${(fmt collection)}${last-bit}]")) (defun fmt-list (args) (let ((items (mapcar #'fmt args))) #?"[${(cl-strings:join items :separator ", ")}]")) (defun fmt-tuple (args) (let* ((items (mapcar #'fmt args)) (items (if (= 1 (length items)) (append items '("")) items))) #?"(${(cl-strings:join items :separator ", ")})")) (defun get-dict-items (args &optional earlier) (ematch args ((list* key value rest) (get-dict-items rest (cons (cons key value) earlier))) ((or (list garbage) nil) (reverse earlier)))) (defun fmt-dict-item (item) #?"${(fmt (car item))}: ${(fmt (cdr item))}") (defun fmt-dict (args) (let ((items (get-dict-items args))) #?"{${(cl-strings:join (mapcar #'fmt-dict-item items) :separator ", ")}}")) (defun fmt-vector (vec) (let ((list (map 'list #'identity vec))) #?"np.array(${(fmt-list list)})")) (defun fmt-getf (key obj) #?"${(fmt obj)}[${(fmt key)}]") (defun fmt-import-item (item) (ematch item ((list module :as alias) #?"import ${(fmt-id module)} as ${(fmt-id alias)}") (module #?"import ${(fmt-id module)}"))) (defun fmt-import (args) (let* ((from-p (member :from args)) (item-args (if from-p (subseq args 0 (- (length args) 2)) args)) (lines (mapcar #'fmt-import-item item-args))) (cl-strings:join (if from-p (prepend-pad lines #?"from ${(fmt-id (car (last args)))} ") lines) :separator (string #\linefeed)))) (defun fmt-ext (ext-path) (load-pgl ext-path) #?"# loaded extension from ${ext-path}") (defun fmt-with (exp rest) "`exp' is the only expression and `rest' might include `:as' specifier." (ematch rest ((list* :as name body) #?"with ${(fmt exp)} as ${(fmt name)}:\n${(fmt-block body)}") (_ #?"with ${(fmt exp)}:\n${(fmt-block rest)}"))) (defun fmt-python (code) (dedent-string code)) (defun fmt (exp) (ematch exp ((list* 'defun name lambda-list body) (fmt-fn name lambda-list body)) ((list* 'with exp rest) (fmt-with exp rest)) ((list 'setf lhs rhs) (fmt-setf lhs rhs)) ((cons 'pg-list args) (fmt-list args)) ((cons 'pg-list-comp args) (apply #'fmt-list-comp args)) ((list 'pg-python code) (fmt-python code)) ((cons 'tuple args) (fmt-tuple args)) ((cons 'dict args) (fmt-dict args)) ((list 'getf key obj) (fmt-getf key obj)) ((cons 'progn body) (fmt-block body t)) ((cons 'import args) (fmt-import args)) ((list 'require ext-path) (fmt-ext ext-path)) ((guard x (atom x)) (fmt-atom x)) ((guard x (id-p x)) (fmt-id x)) ((guard x (lambda-p x)) (apply #'fmt-lambda exp)) ((cons fn args) (fmt-call fn args)))) (defmacro pgfmt (&rest body) (cl-strings:join (mapcar #'fmt body) :separator (make-string 2 :initial-element #\linefeed)))
6,367
Common Lisp
.lisp
159
35.081761
104
0.59417
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
0bdd54159988572864044e996fe45cdafc709dfd2c5798a01c25b945a90c9f68
13,563
[ -1 ]
13,564
predicates.lisp
lepisma_pigeon/src/predicates.lisp
;;; A few predicates (in-package #:pigeon) (cl-interpol:enable-interpol-syntax) (defun lambda-p (exp) "Check whether the expression is a lambda" (and (< 1 (length exp)) (symbolp (car exp)) (or (cl-strings:starts-with (symbol-name (car exp)) "FN-") (eq (car exp) 'fn)))) (defun id-p (exp) (or (symbolp exp) (match exp ((list 'cons (cons 'quote _) _) t)))) (defun kid-p (exp) "Tell if the thing is id and starts with `:'" (or (keywordp exp) (match exp ((list 'cond (cons 'quote _) _) t))))
540
Common Lisp
.lisp
16
29.5
65
0.60501
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
60b0ae3cdaafc6185030f4a985d05a4b49c2c0ee44d21da0402eac316479fe2d
13,564
[ -1 ]
13,565
pigeon.asd
lepisma_pigeon/pigeon.asd
(defsystem #:pigeon :description "s-exp based python" :author "Abhinav Tushar <[email protected]>" :license "GPLv3" :version "0.1.7" :depends-on (#:trivia #:cl-cut #:cl-interpol #:named-readtables #:cl-strings) :components ((:file "package") (:module "src" :depends-on ("package") :serial t :components ((:file "vars") (:file "utils") (:file "read") (:file "predicates") (:file "transform") (:file "format") (:file "shell") (:file "pigeon")))))
576
Common Lisp
.asd
24
17.666667
49
0.539855
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
75b01d72f19cfdb7ef713bc7ab99ba99f6cf69e226acd01a4c4362d338be011c
13,565
[ -1 ]
13,568
Lakefile
lepisma_pigeon/Lakefile
;;; -*- mode: lisp -*- (defpackage #:lake.user (:use #:cl #:lake #:cl-syntax) (:shadowing-import-from #:lake :directory)) (in-package #:lake.user) (use-syntax :interpol) (task "build" () (sh "ros build ./bin/pigeon.ros"))
235
Common Lisp
.l
8
26.75
45
0.625
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
a029700e2e47a4abb9b9ecfdaccefd382f576f014712f1621f95c77846883459
13,568
[ -1 ]
13,569
mpm-scrobble.pg
lepisma_pigeon/samples/mpm-scrobble.pg
;; -*- mode: lisp -*- (setf #iDOC "mpm-scrobble Usage: mpm-scrobble [--config=<CFG>] [--log=<LOG>] [--scrobbled-at=<FILE>] [--lfm-creds=<JSON>] mpm-scrobble -h | --help mpm-scrobble -v | --version Options: -h, --help Show this screen. -v, --version Show version. --config=<CFG> Path to config file [default: ~/.mpm.d/config] --log=<LOG> Path to play log file [default: ~/.mpm.d/play-log] --scrobbled-at=<FILE> Path to scrobbled at file [default: ~/.mpm.d/scrobbled-at] --lfm-creds=<JSON> Path to lastfm creds file [default: ~/.mpm.d/last-fm.json]") (import (#iLastFMNetwork :as lnet) :from pylast) (import docopt :from docopt) (import yaml) (import json) (import --version-- :from mpmplay) (import (#iMpm :as mpm) :from mpm.mpm) (import (mpm.db :as db)) (import time :from time) (require macros) (with-fp "~/Desktop" (fp.write "lol")) ;; Okay let's write down the things we need for this to work out ;; - [x] list (only) comprehensions ;; - [x] context managers (general `with'; and then a macro for with-fp with-fpw) ;; - [ ] keyword arguments in function call ;; - [ ] if macro ;; - [ ] Maybe that #p pathname. Might need to dynamically change the #p reader macro for this. ;; (defn read-log (file-name) ;; (emap (fn [line] (emap int (.split line ","))) ;; (with-fp file-name ;; (efilter (fn [line] (> (len line) 0)) (.split (fp.read) "\n"))))) ;; (defn item-present? [log-entry mpm-instance] ;; "Check if the item in entry is present in db" ;; (db.song-present? mpm-instance.database :id (second log-entry))) ;; (defn get-item [log-entry mpm-instance] ;; "Get the item represented in the entry" ;; (let [song (db.get-song mpm-instance.database (second log-entry))] ;; {"artist" (get song "artist") ;; "title" (get song "title") ;; "album" (get song "album") ;; "timestamp" (first log-entry)})) ;; (defn filter-entries [log-entries timestamp mpm-instance] ;; "Remove entries older than the timestamp" ;; (efilter (fn [entry] (> (get (get-item entry mpm-instance) "timestamp") timestamp)) ;; (efilter (fn [it] (item-present? it mpm-instance)) log-entries))) ;; (defn scrobble [log-entries lastfm-network mpm-instance] ;; (let [items (emap (fn [it] (get-item it mpm-instance)) log-entries)] ;; (if (= (len items) 0) ;; (print "Nothing to do") ;; (do (print (+ "Scrobbling " (str (len items)) " items")) ;; (lastfm-network.scrobble-many items))))) ;; (defn update-last-scrobble [file-name] ;; (with [fp (open file-name "w")] ;; (fp.write (str (int (time)))))) ;; (defn cli [] ;; (let [args (docopt *doc* :version --version--) ;; mpm-instance (Mpm (with-fp #p(get args "--config") (yaml.load fp))) ;; lastfm-config (with-fp #p(get args "--lfm-creds") (json.load fp)) ;; log-entries (read-log #p(get args "--log")) ;; scrobbled-at-file #p(get args "--scrobbled-at") ;; last-scrobble (with-fp (ensure-file scrobbled-at-file "0") (int (fp.read))) ;; lastfm-network (apply LastFMNetwork [] lastfm-config)] ;; (scrobble (filter-entries log-entries last-scrobble mpm-instance) lastfm-network mpm-instance) ;; (update-last-scrobble scrobbled-at-file) ;; (exit 0)))
3,332
Common Lisp
.l
68
47.5
104
0.619077
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
b39ce7aad4ae621c107bcc11a1317ac6c3d247d8f3e85a36ec38adf14b690f8d
13,569
[ -1 ]
13,570
macros.pgl
lepisma_pigeon/samples/macros.pgl
;;; -*- mode: lisp -*- (defmacro incv (a &optional (val 1)) "Test macro" `(setf ,a (+ ,a ,val))) (defmacro with-fp (file-name &rest body) `(pg::with (open ,file-name) :as fp ,@body)) (defmacro with-fpw (file-name &rest body) `(pg::with (open ,file-name "w") :as fp ,@body))
311
Common Lisp
.l
10
26.4
41
0.553691
lepisma/pigeon
7
1
4
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
8914131dc2e32165c0e32caed8ed9a1a043d713d8d26166354a08342038d3f9e
13,570
[ -1 ]
13,590
bliky.lisp
fons_cl-bliky/src/bliky.lisp
;; -*- Mode : LISP; Syntax: COMMON-LISP; ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; (in-package :cl-bliky) (defvar MONTHS '("xx" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")) (defvar DAYS '("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")) (defvar TIMEZONE '("1" "2" "3" "4" "5" "Est" "6") ) (defconstant DEFAULT-PORT 8050) (defvar DEFAULT-REMOTE-REPO-HOST "github.com") (defvar IMPORT-FAILED-MSG "I was unable to convert this post back to html during the import") (defvar USRMODE (logior sb-posix:s-irusr sb-posix:s-ixusr sb-posix:s-iwusr)) (defvar *bliky-server* (not t)) (defvar *BLIKY-HOME* "location of the cl-bliky repository") ;;format classes ;;controlled by the fmt-bit on the blog post object ;; (defmacro html() `'html) (defmacro md() `'md) ;;blog classes ;;controlled by the type-bit on the blog post object ;; (defmacro post() `'post) (defmacro about() `'about) (defmacro sidebar() `'sidebar) ;; macro's used when reading in an uploaded file. (defmacro <title>() `"<title>") (defmacro <split>() `"<split>") (defmacro main-repo-qs() `"main-repo") (defmacro sandbox-repo-qs() `"sandbox-repo") ;;This macro is used in 'clean to identify lines which ;; are end-of-line markers. ;; So two with (clean-ws-guard - 1) spaces and a clf ;; will result in an empty line. ;; This is the same as the markdown package expects; ;; (defmacro clean-ws-guard() `3) ;(setf (hunchentoot:log-file) "/tmp/error.file") (setf hunchentoot:*message-log-pathname* "/tmp/error.file") (defun filter(fun lst) (let ((l)) (dolist (obj lst) (when (funcall fun obj) (push obj l))) (nreverse l))) (defun after (Funs args) (labels ((after* (Funs args) (if (null Funs) args (after (cdr Funs) (funcall (car Funs) args))))) (after* (nreverse Funs) args))) (defun str-strip(str) (string-trim '(#\Return #\Space #\Newline #\Tab #\Nul ) str)) (defun rm-cr(x) (if (equal x #\Return) #\Space x)) (defun clean-str(str) (map 'string #'rm-cr str)) (defun slurp-stream(stream) ;;from ;;www.emmett.ca/~sabetts/slurp.html ;; (let ((seq (make-string (file-length stream)))) (read-sequence seq stream) seq)) (defun fmt-timestamp(st) ;; format rfc-822 style (multiple-value-bind (second minute hour day month year dow dst-p tz) (decode-universal-time st) (declare (ignore dst-p)) (format nil "~&~A, ~2,'0D ~A ~4D ~2,'0D:~2,'0D:~2,'0D ~A" (nth dow DAYS) day (nth month MONTHS) year hour minute second (string-upcase (nth tz TIMEZONE))))) (defun str2type(str) (labels ((strip(str) (string-trim '(#\Return #\Space #\Newline #\Tab #\Nul #\" ) str))) (let ((s (strip str))) (cond ((eq (not t) s) (post)) ((equalp "post" s) (post)) ((equalp "about" s) (about)) ((equalp "sidebar" s) (sidebar)) ( t (post)))))) (defun string-split(s sep) (let ((l ()) (str (string-trim '(#\Space) s))) (do ((pos (position sep str :test #'string=) (position sep str :test #'string=))) ((or (null pos) (eql 0 pos))) (push (string-left-trim '(#\Space) (subseq str 0 pos)) l) (setf str (string-left-trim '(#\Space) (subseq str (+ pos 1) )))) (nreverse (cons str l)))) (defun string-replace*(sep new str) (let ((l ())) (do ((pos (search sep str :test #'string=) (search sep str :test #'string=))) ((or (null pos) (eql 0 pos))) (push (subseq str 0 pos) l) (push new l) (setf str (subseq str (+ pos (length sep) )))) (nreverse (cons str l)))) (defun string-replace(sep new str) (let ((L (string-replace* sep new str))) (reduce (lambda (s1 s2) (concatenate 'string s1 s2)) L :initial-value ""))) (defun read-lines(file) (let ((rlines ())) (with-open-file (stream file :direction :input) (do ((line (read-line stream nil 'eof) (read-line stream nil 'eof))) ((eql line 'eof)) (push line rlines))) rlines)) ;;--------------basic config file--------------- (defun read-db-config(fn) (labels ((!comment?(str) (if ( < 0 (length str) ) (not (char= (char str 0) #\#)) (not t)))) (mapcar (lambda (s) (string-split s ":") ) (filter #'!comment? (mapcar #'str-strip (read-lines fn)))))) (defun find-db-config(key config) (cadr (find-if (lambda (s) (string= (car s) key) ) config))) ;;----string cleaning-------------------------------------- ;; TODO : add eol char to wsb ;; this needs to be filtered out in the regular case before appending to the accumulator. ;; If an eol is encountered with an eol in the wsb then insert a break (defun clean(s) (labels ((clean-helper(s accum wsb eolf) (labels ((str-car(s) (elt s 0)) ;; (str-cdr(s);; (subseq s 1)) ;; (cr-p(c) (char= #\Return c)) ;; (nl-p(c) (char= #\Newline c)) ;; (chr-p(c) (and (not (cr-p c)) (not (nl-p c)))) ;; (rln-st(str) (chr-p (str-car str))) ;; (eol-st(str) (cr-p (str-car str))) ;; (neolf-st (wsb eolf) (cond ( (and (> (length wsb) (clean-ws-guard)) (eq (count #\Space wsb) (length wsb))) t) ((not eolf) t) (t (not t)))) ;; (p-acc(s accum) (cons (str-car s) accum)) ;; (p-acc-br(accum) (append (nreverse (coerce (string #\Newline) 'list)) accum)) ;; (p-acc-br-alt(accum) (append (nreverse (coerce "<br /><br />" 'list)) accum)) ;; (merge-wsb(wsb accum) (append (filter (lambda (c) (not (cr-p c))) wsb) accum)) ;;( (< (count #\Return ws) 1) (p-acc-br accum)) (p-acc-br-ws(accum ws) (cond ;; just an empty line -> insert <br /> ( (< (length ws) 1) (p-acc-br accum)) ( (eq (count #\Space ws) (length ws)) (p-acc-br-alt accum)) ( t (merge-wsb ws accum))))) (cond ((eq (length s) 0) (p-acc-br-ws accum wsb )) ((neolf-st wsb eolf) (clean-helper (str-cdr s) accum (p-acc s wsb) nil )) ((rln-st s) (clean-helper (str-cdr s) accum (p-acc s wsb) t )) ((eol-st s) (clean-helper (str-cdr s) (p-acc-br-ws accum wsb) nil t )) (t (clean-helper (str-cdr s) accum wsb t )))))) (coerce (nreverse (clean-helper s nil nil t)) 'string))) ;;--> this is problamtic as <special char> is escaped to &<something>; ;;--> so you get into some infinite recursion ! ;;((char= c #\&) "&amp;") ;;((char= c #\&) t) (defun escape-html-chars(str &optional (start 0)) ;; find the first char to be escaped, escape it, and return a list of the ;; position in the string plus the new string. ;; Repeat, until done, when the car of the list is nil (labels ((escape-html-chars-helper(str start) (labels ((escape-string(str) (labels ((escape-chars(c) ;; add additional chars to be escaped here... (cond ((char= c #\<) "&lt;") ((char= c #\>) "&gt;") ( t (string c))))) (concatenate 'string (escape-chars (char str 0)) (subseq str 1)))) ;; (escape-chars-pred(c) ;; add additional chars to be escaped here... (cond ((char= c #\<) t) ((char= c #\>) t) ( t (not t))))) ;; if no chars to be escaped are found, return nil (let* ((npos (position-if #'escape-chars-pred (subseq str start))) (epos (if npos (+ start npos) (not t) )) (nstr (if epos (concatenate 'string (subseq str 0 epos) (escape-string (subseq str epos))) str))) (list epos nstr))))) (let ((res (escape-html-chars-helper str start))) ;; recursion (cond ((null (car res)) (cadr res)) ( t (escape-html-chars (cadr res) (car res))))))) (defun to-list(parts) (if (listp parts) parts (list parts))) ;;-------------------------------------------------------------------------- (defpclass blog-post () ((title :initarg :title :accessor title) (intro :initarg :intro :accessor intro) (body :initarg :body :accessor body) (timestamp :initarg :timestamp :accessor timestamp :initform (get-universal-time) :index t) (gc-bit :accessor gc-bit :index t :initform (not t)) (pub-bit :accessor pub-bit :index t :initform (not t)) (fmt-bit :initarg :fmt-bit :accessor fmt-bit :index t) (type-bit :initarg :type-bit :accessor type-bit :index t) (url-part :initarg :url-part :accessor url-part :initform nil :index t))) (defmethod print-object ((u blog-post) stream) "specialize print object blog post" (format stream "~&blog-post : [title = ~A] [url-part = ~A][time=~A][gc=~A][pub=~A]~%[type=~A][fmt=~A]~%[~A]~%[~A]~% " (if (slot-boundp u 'title) (title u) "(blog-post not set)") (if (slot-boundp u 'url-part) (url-part u) "(url-part not specified") (if (slot-boundp u 'timestamp) (timestamp u) "(timestamp not set)") (if (slot-boundp u 'gc-bit) (gc-bit u) "(gc not set)") (if (slot-boundp u 'pub-bit) (pub-bit u) "(publish bit not set)") (if (slot-boundp u 'type-bit) (type-bit u) "(type bit not set)") (if (slot-boundp u 'fmt-bit) (fmt-bit u) "(format bit not set)") (if (slot-boundp u 'intro) (intro u) "(intro not set)") (if (slot-boundp u 'body) (body u) "(body not set)"))) ;; ;; blog post is md unless specified otherwise ;; (defun p-blogpost-html(blog-post) (cond ((equalp (fmt-bit blog-post) (html) ) t) ( t (not t)))) (defun p-blogpost-md(blog-post) (cond ((not (p-blogpost-html blog-post)) t) ( t (not t)))) (defun render-post (part post) (cond ((p-blogpost-html post) (after (to-list part) post)) ((p-blogpost-md post) (after (cons 'render-md (to-list part)) post)) (t (funcall part post)))) (defun render-identity (part post) (identity (funcall part post))) (defun render-md(s) (with-output-to-string (stream) (markdown:markdown (clean s) :stream stream :format :html))) ;; ;; ;;--------------settings----------------- ;; ;; (defun get-settings() (let ((eb (get-from-root 'blog-settings))) (if eb eb (progn (add-to-root 'blog-settings (make-btree)) (get-from-root 'blog-settings))))) (defun set-bliky-setting(k v) (setf (get-value k (get-settings)) v)) (defun get-bliky-setting(k) (get-value k (get-settings))) (defun set-bliky-port(port) (labels ((conv-i(port) (if (integerp port) port (parse-integer port)))) (set-bliky-setting 'bliky-port (conv-i port)))) (defun get-bliky-port() (let ((val (get-bliky-setting 'bliky-port))) (if val val (set-bliky-port DEFAULT-PORT)))) (defun set-blog-title(title) (set-bliky-setting 'blog-title title)) (defun get-blog-title() (let ((val (get-bliky-setting 'blog-title))) (if val val (set-blog-title "blog title not set")))) (defun set-google-meta-tag(tag) (set-bliky-setting 'google-meta-tag tag)) (defun get-google-meta-tag() (let ((val (get-bliky-setting 'google-meta-tag))) (if val val (set-google-meta-tag "")))) (defun set-technorati-claim(tag) (set-bliky-setting 'technorati-claim tag)) (defun get-technorati-claim() (let ((val (get-bliky-setting 'technorati-claim))) (if val val (set-technorati-claim "")))) (defun set-follow-on-twitter(tag) (set-bliky-setting 'follow-on-twitter tag)) (defun get-follow-on-twitter() (let ((val (get-bliky-setting 'follow-on-twitter))) (if val val (set-follow-on-twitter "")))) (defun set-email-subscription(tag) (set-bliky-setting 'email-subscription tag)) (defun get-email-subscription() (let ((val (get-bliky-setting 'email-subscription))) (if val val (set-email-subscription "")))) (defun set-background-uri(uri) (set-bliky-setting 'background-uri uri)) (defun get-background-uri() (let ((val (get-bliky-setting 'background-uri))) (if val val (set-background-uri nil)))) (defun set-contact-info(co) (set-bliky-setting 'contact-info co)) (defun get-contact-info() (let ((val (get-bliky-setting 'contact-info))) (if val val (set-contact-info "contact info not set")))) (defun set-google-analytics(co) (set-bliky-setting 'google-analytics co)) (defun get-google-analytics() (let ((val (get-bliky-setting 'google-analytics))) (if val val (set-google-analytics nil)))) (defun set-rss-link(co) (set-bliky-setting 'rss-link co)) (defun get-rss-link() (let ((val (get-bliky-setting 'rss-link))) (if val val (set-rss-link "<h2>rss</h2>")))) (defun set-remote-repo(repo) (set-bliky-setting 'remote-repo repo)) (defun get-remote-repo() (let ((val (get-bliky-setting 'remote-repo))) (if val val (set-remote-repo DEFAULT-REMOTE-REPO-HOST)))) (defun set-rss-validator(co) (set-bliky-setting 'rss-validator co)) (defun get-rss-validator() (let ((val (get-bliky-setting 'rss-validator))) (if val val (set-rss-validator "")))) ;;---------------path name code----------------------------------------- (defun create-if-missing(path) (unless (probe-file path) (sb-posix:mkdir path USRMODE)) path) (defun set-bliky-pathname(path name) ;; nil is used to signal 'not set (if path (set-bliky-setting name (make-pathname :directory path)) (set-bliky-setting name path))) (defun get-bliky-pathname(name default-path) ;; side effects : ;; 1. set path if not found to whatever default-path generates. ;; 2. create directory if missing (let ((val (get-bliky-setting name))) (if val val (let ((path (funcall default-path))) (create-if-missing path) (set-bliky-pathname path name))))) ;---------------------------------- (defun blog-store-location*() (let* ((home (sb-posix:getenv "HOME")) (path (format nil "~A/.blog-store.db" home))) path)) (defun get-blog-store-location(name) (find-db-config name (read-db-config (blog-store-location*)))) (defun set-template-pathname(p) (set-bliky-pathname p 'template-pathname)) (defun get-template-pathname() (labels ((df-path() (let ((home *BLIKY-HOME*)) (format nil "~A/templates/" home)))) (get-bliky-pathname 'template-pathname #'df-path))) (defun set-styles-pathname(p) (set-bliky-pathname p 'styles-pathname)) (defun get-styles-pathname() (labels ((df-path() (let ((home *BLIKY-HOME*)) (format nil "~A/styles/" home)))) (get-bliky-pathname 'styles-pathname #'df-path))) ;;--- (defun set-script-pathname(p) (set-bliky-pathname p 'script-pathname)) (defun get-script-pathname() (labels ((df-path() (let ((home (sb-posix:getenv "HOME"))) (format nil "~A/cl-bliky/js" home)))) (get-bliky-pathname 'script-pathname #'df-path))) ;;-- (defun set-idiot-location(p) (set-bliky-pathname p 'idiot-location)) (defun get-idiot-location() (get-bliky-pathname 'idiot-location (lambda()"/tmp/idiot"))) ;;-- (defun set-repo-pathname(p) (set-bliky-pathname p 'repo-pathname)) (defun get-repo-pathname() (labels ((df-path() (let ((home (sb-posix:getenv "HOME")) (user (sb-posix:getenv "USER"))) (format nil "~A/~A.github.com" home user)))) (get-bliky-pathname 'repo-pathname #'df-path))) ;;-- (defun set-sandbox-pathname(p) (set-bliky-pathname p 'sandbox-pathname)) (defun get-sandbox-pathname() (labels ((df-path() (let ((user (sb-posix:getenv "USER"))) (format nil "/tmp/~A.sandbox.github.com" user)))) (get-bliky-pathname 'sandbox-pathname #'df-path))) (defun set-mainstore?(v) (set-bliky-setting 'is_main_store v)) (defun get-mainstore?() (if (get-bliky-setting 'is_main_store) t (not t))) (defun set-offline?(v) (set-bliky-setting 'is_off_line v)) (defun get-offline?() (if (get-bliky-setting 'is_off_line) t (not t))) (defun show-settings() (map-btree (lambda(k v) (format t "~A->~A~%" k v)) (get-settings))) ;;---------------end of settings --------------------------------------- ;;----------------------------------------------------------------------- ;;(defun blog-title() ;; (get-blog-title)) ;;(defun contact-info() ;; (get-contact-info)) (defun infer-repo-name () (let* ((pn (namestring (get-repo-pathname))) (index (search "/" pn :from-end t :end2 (- (length pn) 1)))) (subseq pn (+ index 1) (- (length pn) 1)))) ;;---------------------------- (defun load-script(fn path) (handler-case (with-open-file (stream path :direction :input) (funcall fn (slurp-stream stream))) (error(c) (declare (ignore c))))) (defun tracking-js-path() (concatenate 'string (namestring (get-script-pathname)) "/google-analytics.js")) (defun load-tracking-js() (load-script #'set-google-analytics (tracking-js-path))) ;---------------------------- (defun google-meta-tag-path() (concatenate 'string (namestring (get-script-pathname)) "/google-meta-tag.js")) (defun load-google-meta-tag() (load-script #'set-google-meta-tag (google-meta-tag-path))) ;;---------------------------- (defun follow-on-twitter-path() (concatenate 'string (namestring (get-script-pathname)) "/follow-on-twitter.js")) (defun load-follow-on-twitter() (load-script #'set-follow-on-twitter (follow-on-twitter-path))) ;;---------------------------- (defun email-subscription-path() (concatenate 'string (namestring (get-script-pathname)) "/email-subscription.js")) (defun load-email-subscription() (load-script #'set-email-subscription (email-subscription-path))) ;;---------------------------- (defun contact-js-path() (concatenate 'string (namestring (get-script-pathname)) "/contact-info.js")) (defun load-contact-js() (load-script #'set-contact-info (contact-js-path))) ;;---------------------------- (defun rss-js-path() (concatenate 'string (namestring (get-script-pathname)) "/rss-tag.js")) (defun load-rss-js() (load-script #'set-rss-link (rss-js-path))) ;;----------------------------------------------------------------------------------- ;;-----------git-repo-managment code------------------------------------------------- ;;---------------------------------------------------------------------------------- (defun switch-to-repo(repo-path) (sb-posix:chdir repo-path)) (defun switch-to-default-path() (sb-posix:chdir *default-pathname-defaults*)) (defun string-to-list2(s sep) (let ((l ()) (str (string-trim '(#\Space) s))) (do ((pos (position sep str) (position sep str))) ((or (null pos) (eql 0 pos))) (push (string-left-trim '(#\Space) (subseq str 0 pos)) l) (setf str (string-left-trim '(#\Space) (subseq str (+ pos 1) )))) (nreverse l))) (defun string-to-list(s) (let ((l ()) (str (string-trim '(#\Space) s))) (do ((pos (position #\Space str) (position #\Space str))) ((or (null pos) (eql 0 pos))) (push (string-left-trim '(#\Space) (subseq str 0 pos)) l) (setf str (string-left-trim '(#\Space) (subseq str pos )))) (push str l) (nreverse l))) (defun run-cmd(cmd &optional args ) (let ((str (make-string 0))) (labels ((set-args (args) (cond ((null args) nil) ((listp args) args) ((stringp args) (string-to-list args)) (t nil)))) (let* ((data (process-output (sb-ext:run-program cmd (set-args args) :input :stream :output :stream :search t)))) (do ((line (read-line data nil 'eof) (read-line data nil 'eof))) ((eql line 'eof)) (setf str (concatenate 'string str line "|")) ))) str)) (defun run-git(&optional args ) (run-cmd "git" args)) (defun find-deleted-files() (let* ((status (run-git "status")) (lst ())) (do* ((pos (search "deleted:" status) (search "deleted:" status))) ((null pos)) (let ((peek (search "|" (subseq status pos)))) (push (string-trim '(#\Space) (subseq status (+ pos (length "deleted:")) (+ peek pos))) lst) (setf status (subseq status (+ peek pos))))) (nreverse lst))) (defun git-rm-discarded-posts() (dolist (f (find-deleted-files) ) (run-git (list "rm" f)))) (defun git-commit() (let* ((ts (substitute #\_ #\Space (fmt-timestamp (get-universal-time)))) (msg (concatenate 'string "commit -m message_ok_" ts))) (run-git msg))) (defun git-add-all-posts() (run-git "add *.html") (run-git "add *.css") (run-git "add *.xml")) (defun git-publish-branch() (run-git "checkout -b publish")) (defun git-master-branch() (run-git "checkout master")) (defun git-merge() (run-git "merge publish")) (defun remove-files() (dolist (fn (filter (lambda(x) (not (equalp "CNAME" x))) (string-to-list2 (run-cmd "ls") #\|))) (run-cmd "cp" (format nil "~A ~A" fn (get-idiot-location))) (run-cmd "rm" (format nil "~A" fn )))) (defun git-publish() ;; ;; run ssh-add to add the pasword to the ssh agent. ;; this way you won't get challenged for a keyword.. ;; (let* ((cmd "git") (str (make-string 0)) (args (list "push" "origin" "master")) (proc (sb-ext:run-program cmd args :wait nil :input :stream :output :stream :search t)) (data (process-output proc))) (if (not (eql (process-status proc) :RUNNING)) (progn (process-kill proc -9) (setf str (format nil "killed stopped process ~A ~A; add pwd to ssh agent; or run push manually" cmd args))) (do ((line (read-line data nil 'eof) (read-line data nil 'eof))) ((eql line 'eof)) ;;(format t "~A ~%" line) (setf str (concatenate 'string str line "|")))) str)) (defun p-blogpost-active(blog-post) (cond ((not (gc-bit blog-post)) t) ( t (not t)))) (defun get-blog-post-by-timestamp(ts) (let ((objs (get-instances-by-value 'blog-post 'timestamp ts))) (if objs (dolist (obj objs) (if (p-blogpost-active obj) (return obj))) nil))) (defun create-blog-post(title intro body type &optional (fmt-bid (md))) (make-instance 'blog-post :title title :intro intro :body body :type-bit type :fmt-bit fmt-bid)) (defun create-html-blog-post(title intro body type) (create-blog-post title intro body type (html))) ; (make-instance 'blog-post :title title :intro intro :body body :type-bit type :fmt-bit (html))) (defun create-blog-post-template(type &optional (fmt-bid (md))) (let* ((title (format nil "new blog post dd ~A" (fmt-timestamp (get-universal-time)))) (intro "") (body "")) (create-blog-post title intro body type fmt-bid))) (defun create-about-post() (let* ((title "About") (intro "") (body "")) (create-blog-post title intro body (about)))) (defun make-url-part(title) (string-downcase (delete-if #'(lambda(x) (not (or (alphanumericp x) (char= #\- x)))) (substitute #\- #\Space title)))) ;;---------Importing a Repo------------------------------------------ (defun disassem-html-page(page) (let ((links nil)) (labels ((get-page(path) (with-open-file (stream path :direction :input) (slurp-stream stream))) (link-cb (element) (labels ((is-div(lst) (cond ((consp lst) (and (equal :DIV (car lst)) (eq :ID (cadr lst)))) ( t (not t)))) (get-div-tag(lst) (if (is-div lst) (car (cdr (cdr lst))) nil)) (describe-tag(tag) ;;(format t "in describe-tag ~A~%" tag) (cond ((equal tag "post-timestamp-id") tag) ((equal tag "post-body") tag) ((equal tag "post-intro") tag) ((equal tag "post-header") tag) ((equal tag "post-type") tag) ((equal tag "post-timestamp") tag) ( t (not t)))) (unpack(el) el)) (let ((tag (describe-tag (get-div-tag (car element))))) (if tag (push (list tag (unpack (cdr element))) links)))))) (let ((cb (cons (cons :DIV #'link-cb ) nil))) (html-parse:parse-html (get-page page) :callbacks cb) links)))) (defun unpack (str up) (labels ((find-piece(str lst &optional (accum nil)) (cond ((equal str (car (car lst))) (push (cadr (car lst)) accum)) ((eq lst nil) accum) (t (find-piece str (cdr lst) accum))))) (let ((piece (find-piece str up))) (labels ((up-ts(lst) (str-strip (cadr (caar lst)))) ;;; (rm-wrapper-tags(seq) (let ((slen (length "<BODY>" )) (nlen (length "</BODY>" ))) (subseq seq slen (- (length seq) nlen )))) ;;; (to-wrapped-html(lst) (let ((s (cons :body (car lst)))) (with-output-to-string (stream) (net.html.generator:html-print s stream)))) ;;TODO : move handler case HERE... (to-html(lst) (handler-case (str-strip (rm-wrapper-tags (to-wrapped-html lst))) (error(c) (declare (ignore c)) (cons IMPORT-FAILED-MSG lst))))) (cond ((equal "post-timestamp-id" str ) (up-ts piece)) ((equal "post-timestamp" str ) (up-ts piece)) ((equal "post-header" str ) (up-ts piece)) ((equal "post-type" str ) (up-ts piece)) ((equal "post-intro" str ) (to-html piece)) ((equal "post-body" str ) (to-html piece)) (t nil)))))) (defun unpack-post(p) (let ((ts-id (parse-integer (unpack "post-timestamp-id" p))) (ts (unpack "post-timestamp" p)) (header (unpack "post-header" p)) (intro (unpack "post-intro" p)) (body (unpack "post-body" p)) (type (str2type (unpack "post-type" p)))) (values ts-id ts type header intro body))) (defun mv-about() (let ((lst (get-instances-by-value 'blog-post 'type-bit (about))) (seed (random (floor (/ (get-universal-time) 100000000))))) (dolist (obj lst) (setf (type-bit obj) (sidebar)) (setf (title obj) (format nil "About-~A-~A" (get-universal-time) seed)) (setf (url-part obj) (make-url-part (title obj))) (setf (gc-bit obj) t)))) (defun recreate-post(ts-id type header intro body) ;; the about post is always generated when it's not found ;; move the on found to the sidebar, so no info is lost.. (when (equal type (about) ) (mv-about)) (let ((post (create-html-blog-post header intro body type))) (setf (timestamp post) ts-id) post)) (defun import-blog-post(html-page) (multiple-value-bind (ts-id ts type header intro body) (unpack-post (disassem-html-page html-page)) (declare (ignore ts)) (let ((pst (get-blog-post-by-timestamp ts-id))) (unless pst (recreate-post ts-id type header intro body))))) (defun import-repo(repo-path) (let ((lst (directory (make-pathname :name :wild :type :wild :defaults repo-path)))) (dolist (f lst) (let* ((fn (namestring f)) (not-index? (not (search "/index.html" fn :from-end t))) (html? (search ".html" fn :from-end t))) (handler-case (when (and html? not-index?) (import-blog-post fn)) (error(c) (format t "an error [~A] occured when importing post ~A at ~A" c fn repo-path))))))) ;;------------------- (defun blog-posts() (or (get-from-root "blog-posts") (let ((blog-posts (make-pset))) (add-to-root "blog-posts" blog-posts) (blog-posts)))) (defun open-blog-store(name) (let ((blog-store (list :BDB (get-blog-store-location name) ))) (if (null *store-controller*) (open-store blog-store :recover t) (print "store already opened")))) (defun p-blogpost-post(blog-post) (cond ((not (slot-boundp blog-post 'type-bit)) t) ((eq (type-bit blog-post) (post)) t) ((eq (type-bit blog-post) (not t)) t) ( t (not t)))) (defun p-blogpost-sidebar(blog-post) (cond ((eq (type-bit blog-post) (sidebar)) t) ( t (not t)))) (defun p-blogpost(blog-post) (and (p-blogpost-active blog-post) (p-blogpost-post blog-post))) (defun p-sidebar(blog-post) (and (p-blogpost-active blog-post) (p-blogpost-sidebar blog-post))) (defun show-blogs() (map-class #'print 'blog-post)) (defmethod initialize-url-part ((obj blog-post)) (cond ((eq nil (url-part obj)) (setf (url-part obj) (make-url-part (title obj)))))) (defmethod initialize-instance :after ((obj blog-post) &key) (cond ((eq nil (url-part obj)) (setf (url-part obj) (make-url-part (title obj)))))) (defun style-css-path() (concatenate 'string (namestring (get-styles-pathname)) "/style.css")) (defun background-css(uri) (format nil "background-image:url('~A')" uri)) (defun add-background(str) (let ( (background (get-background-uri))) (if background (string-replace "#:background-image" (background-css background) str) str))) (defun cat-style-sheet() (with-open-file (stream (style-css-path) :direction :input) (add-background (slurp-stream stream)))) (defun inject-style-sheet() (let ((sheet (cat-style-sheet))) ( format nil "<style type=\"text/css\"> ~A </style>" sheet))) (defun online-style-sheet() (format nil "<link rel=\"stylesheet\" href=\"/style.css\" type=\"text/css\"/>")) ;;needs to get all instances (defun discard-post-by-type(type) (let ((post (get-instance-by-value 'blog-post 'type-bit type))) (if post (setf (gc-bit post) t) nil))) (defun get-live-blog-post(url-part) (let ((objs (get-instances-by-value 'blog-post 'url-part url-part))) (if objs (dolist (obj objs) (if (p-blogpost-active obj) (return obj))) nil))) (defun get-blog-post(url-part &optional (fmt-bid (md))) (let ((obj (get-live-blog-post url-part))) (if obj obj (create-blog-post-template (post) fmt-bid )))) (defun get-about-post() (let ((about-post (get-instance-by-value 'blog-post 'type-bit (about)))) (if (null about-post) (create-about-post) about-post))) (defun about-page() (let ((obj (get-about-post))) (url-part obj))) (defun template-path(tmpl) (make-pathname :directory (namestring (get-template-pathname) ) :name tmpl)) (defun generate-error-page(trace msg) (handler-case (with-output-to-string (stream) (let ((html-template:*string-modifier* #'identity)) (html-template:fill-and-print-template (template-path "error.tmpl") (list :error-condition trace :error-message msg) :stream stream))) (error(c) (format nil "an error when generating the error page: ~A" c)))) (defun protect(f) (lambda() (handler-case (funcall f) (error(c) (generate-error-page c "an error occured when generating static pages"))))) (defun rss-feed-format_alt(blog-post) (handler-case (list :timestamp (fmt-timestamp (timestamp blog-post)) :title (title blog-post) :url-part (url-part blog-post) :intro (concatenate 'string (escape-html-chars (render-post 'intro blog-post)) (escape-html-chars (render-post 'body blog-post))) :cdata (concatenate 'string (render-md (str-strip (intro blog-post))) (render-md (str-strip (body blog-post))))) (error(c) (format t "an error ~A occurred when generating the rss for post ~A ~%" c (title blog-post))))) (defun rss-feed-format(blog-post) (handler-case (list :timestamp (fmt-timestamp (timestamp blog-post)) :title (title blog-post) :url-part (url-part blog-post) :intro (escape-html-chars (render-post 'intro blog-post)) :cdata (concatenate 'string (render-post 'intro blog-post) (render-post 'body blog-post))) (error(c) (format t "an error ~A occurred when generating the rss for post ~A ~%" c (title blog-post))))) ;;(intro blog-post) (defun use-static-template(blog-post) (list :timestamp (fmt-timestamp (timestamp blog-post)) :timestamp-id (timestamp blog-post) :type (string-downcase (type-bit blog-post)) :title (title blog-post) :url-part (url-part blog-post) :intro (render-post 'intro blog-post))) (defun use-edit-template(blog-post) (cons :edit_part (cons t (use-static-template blog-post)))) (defun collect-posts(tlf) (loop for blog-post in (nreverse (get-instances-by-range 'blog-post 'timestamp nil nil)) if (p-blogpost blog-post ) collect (funcall tlf blog-post))) (defun collect-sidebars(tlf) ;; note that this is oldest-firts order (loop for blog-post in (get-instances-by-range 'blog-post 'timestamp nil nil) if (p-sidebar blog-post ) collect (cons :body (cons (body blog-post) (funcall tlf blog-post))))) (defun blog-url() (format nil "http://~A/" (infer-repo-name))) (defun blog-description() (let ((post (car (get-instances-by-value 'blog-post 'type-bit (about))))) (escape-html-chars (str-strip (intro post))))) (defun generate-rss-page() (with-output-to-string (stream) (let ((html-template:*string-modifier* #'identity)) (html-template:fill-and-print-template (template-path "rss.tmpl") (list :blog-title (get-blog-title) :blog-url (blog-url) :blog-description (blog-description) :rss-generation-date (fmt-timestamp (get-universal-time)) :blog-posts (collect-posts #'rss-feed-format) ) :stream stream)))) (defun generate-index-page(tlf &key create (style-sheet 'inject-style-sheet)) (with-output-to-string (stream) (let ((html-template:*string-modifier* #'identity)) (html-template:fill-and-print-template (template-path "index.tmpl") (list :style-sheet (funcall style-sheet) (unless (get-offline?) :google-analytics) (unless (get-offline?) (get-google-analytics)) :rss-link (if (get-offline?) "<h2>rss</h2>" (get-rss-link)) (if create :edit_part) (if create t) :blog-title (get-blog-title) :google-meta-tag (get-google-meta-tag) :main-repo-qs (main-repo-qs) :sandbox-repo-qs (sandbox-repo-qs) (unless (get-offline?) :contact-info) (unless (get-offline?) (get-contact-info)) (unless (get-offline?) :rss-validator) (unless (get-offline?) (get-rss-validator)) (unless (get-offline?) :follow-on-twitter) (unless (get-offline?) (get-follow-on-twitter)) (unless (get-offline?) :email-subscription) (unless (get-offline?) (get-email-subscription)) :about (about-page) :sidebars (collect-sidebars tlf) :blog-posts (collect-posts tlf)) :stream stream)))) (defun generate-editable-index-page() (generate-index-page #'use-edit-template :create t)) (defun generate-blog-post-page(tmpl url-part &key (render 'render-identity) (style-sheet 'inject-style-sheet)) (with-output-to-string (stream) (let ((blog-post (get-live-blog-post url-part)) (html-template:*string-modifier* #'identity)) (if blog-post (html-template:fill-and-print-template tmpl (list :style-sheet (funcall style-sheet) :blog-title (get-blog-title) :title (title blog-post) :url_part url-part :timestamp (fmt-timestamp (timestamp blog-post)) :timestamp-id (timestamp blog-post) :type (string-downcase (type-bit blog-post)) :intro (funcall render 'intro blog-post) :body (funcall render 'body blog-post)) :stream stream))))) (defun view-blog-post-page() (generate-blog-post-page (template-path "post.tmpl") (hunchentoot:query-string*) :render 'render-post)) ;; ;; Somehow we end up with a extra space at the start of the intro and body ;; This could trigger some mark-down formatting; ;; Hence the string is stripped of spaces etc.. ;; (defun save-blog-post() (let ((blog-post (get-live-blog-post (hunchentoot:query-string*)))) (setf (title blog-post) (hunchentoot:post-parameter "title")) (setf (intro blog-post) (str-strip (hunchentoot:post-parameter "intro"))) (setf (body blog-post) (str-strip (hunchentoot:post-parameter "body"))) (setf (url-part blog-post) (make-url-part (title blog-post))) (hunchentoot:redirect "/" ))) (defun split-sequence(seq tkw kw) (handler-case (let* ((ltkw (length tkw)) (lkw (length kw)) (tkwpos (search tkw seq)) (kwpos (search kw seq)) (title (subseq seq 0 tkwpos)) (intro (subseq seq (+ tkwpos ltkw 1) kwpos)) (body (subseq seq (+ kwpos lkw 1)))) (values title intro body)) (error(c) (declare (ignore c)) (values "new blog post created from upload" "" seq)))) (defun redirect-to-edit-page(blog-post) (hunchentoot:redirect (concatenate 'string "/edit/?"(url-part blog-post)))) (defun save-file() (labels ((read-file(params) (let ((fn (namestring(car params)))) (with-open-file (stream fn :direction :input) (split-sequence (slurp-stream stream) (<title>) (<split>)))))) (let ((blog-post (get-blog-post (hunchentoot:query-string*)))) (multiple-value-bind (title intro body) (read-file (hunchentoot:post-parameter "file")) (setf (title blog-post) title) (setf (intro blog-post) intro) (setf (body blog-post) body) (setf (url-part blog-post) (make-url-part (title blog-post)))) (redirect-to-edit-page blog-post)))) (defun save-html-file(url-part fn) (labels ((read-file(fn) (with-open-file (stream fn :direction :input) (split-sequence (slurp-stream stream) (<title>) (<split>))))) (let ((blog-post (get-blog-post url-part (html)))) (multiple-value-bind (title intro body) (read-file fn) (setf (title blog-post) title) (setf (intro blog-post) intro) (setf (body blog-post) body) (setf (url-part blog-post) (make-url-part (title blog-post)))) blog-post))) #| (let ((blog-post (get-blog-post (hunchentoot:query-string*)))) (multiple-value-bind (title intro body) (read-file (hunchentoot:post-parameter "file")) (setf (title blog-post) title) (setf (intro blog-post) intro) (setf (body blog-post) body) (setf (url-part blog-post) (make-url-part (title blog-post)))) (redirect-to-edit-page blog-post)))) |# (defun discard-blog-post() (let ((blog-posts (get-instances-by-value 'blog-post 'url-part (hunchentoot:query-string*)))) (dolist (blog-post blog-posts) (setf (gc-bit blog-post) t)) (hunchentoot:redirect "/" ))) (defun discard-all-blog-posts() (let ((blog-posts (get-instances-by-class 'blog-post))) (dolist (blog-post blog-posts) (setf (gc-bit blog-post) t)))) (defun undo-all-discards() (let ((blog-posts (get-instances-by-value 'blog-post 'gc-bit t))) (dolist (blog-post blog-posts) (setf (gc-bit blog-post) (not t))))) (defun drop-all-discards() (let ((blog-posts (get-instances-by-value 'blog-post 'gc-bit t))) (drop-instances blog-posts))) (defun create-empty-blog-post(tmpl type-str) (let* ((bp (create-blog-post-template (str2type type-str))) (up (url-part bp))) (generate-blog-post-page tmpl up))) (defun create-blog-post-page() (cond ((eq (hunchentoot:request-method*) :GET) (create-empty-blog-post (template-path "post-edit.tmpl") (hunchentoot:query-string*))) ((eq (hunchentoot:request-method*) :POST) (save-blog-post)))) (defun edit-blog-post-page() (cond ((eq (hunchentoot:request-method*) :GET) (generate-blog-post-page (template-path "post-edit.tmpl") (hunchentoot:query-string*))) ((eq (hunchentoot:request-method*) :POST) (save-blog-post)))) (defun simple-template(p) (with-open-file (stream p :direction :input) (slurp-stream stream))) (defun generate-import-page() (with-output-to-string (stream) (let ((html-template:*string-modifier* #'identity)) (html-template:fill-and-print-template (template-path "import.tmpl") (list :style-sheet (inject-style-sheet) :blog-title (get-blog-title) :repo-name (infer-repo-name) :remote-repo (get-remote-repo) :repo-pathname (get-repo-pathname)) :stream stream)))) (defun do-import (file-path) (import-repo (directory-namestring file-path)) (hunchentoot:redirect "/" )) (defun import-remote () (format nil "this is a test : ~A" (hunchentoot:post-parameters*) ) ) (defun import-local() ( do-import (hunchentoot:post-parameter "repo-path"))) (defun import-repo-page() (cond ((eq (hunchentoot:request-method*) :GET) (generate-import-page)) ((eq (hunchentoot:request-method*) :POST) ( do-import (hunchentoot:post-parameter "file"))))) (defun generate-options-page() (labels ((checked?(fn) (when (funcall fn) "checked"))) (with-output-to-string (stream) (let ((html-template:*string-modifier* #'identity)) (html-template:fill-and-print-template (template-path "options.tmpl") (list :style-sheet (inject-style-sheet) :blog-title (get-blog-title) :background-uri (get-background-uri) :bliky-port (get-bliky-port) :idiot-location (get-idiot-location) :remote-repo (get-remote-repo) :repo-pathname (get-repo-pathname) :is-mainstore (checked? #'get-mainstore? ) :is-offline (checked? #'get-offline?) :template-pathname (get-template-pathname) :styles-pathname (get-styles-pathname) :script-pathname (get-script-pathname) :google-meta-tag (clean-str (str-strip (get-google-meta-tag))) :contact-info (clean-str (str-strip (get-contact-info))) :rss-image-link (clean-str (str-strip (get-rss-link))) :rss-validator (clean-str (str-strip (get-rss-validator))) :follow-on-twitter (clean-str (str-strip (get-follow-on-twitter))) :email-subscription (clean-str (str-strip (get-email-subscription))) :web-analytics (clean-str (str-strip (get-google-analytics))) :sandbox-pathname (get-sandbox-pathname)) :stream stream))))) (defun save-option(fn p) (funcall fn (hunchentoot:post-parameter p))) (defun save-checked(fn p) (funcall fn (string-equal (hunchentoot:post-parameter p) "on"))) (defun save-options-main() (save-checked #'set-mainstore? "is-mainstore?") (save-checked #'set-offline? "is-offline?") (save-option #'set-bliky-port "bliky-port") (save-option #'set-repo-pathname "repo-pathname") (save-option #'set-sandbox-pathname "sandbox-pathname") (save-option #'set-template-pathname "template-pathname") (save-option #'set-styles-pathname "styles-pathname") (save-option #'set-script-pathname "script-pathname") (save-option #'set-blog-title "blog-title") (save-option #'set-background-uri "background-uri") (save-option #'set-remote-repo "remote-repo") (save-option #'set-google-meta-tag "google-meta-tag") (save-option #'set-google-analytics "web-analytics") (save-option #'set-contact-info "contact-info") (save-option #'set-rss-link "rss-image-link") (save-option #'set-rss-validator "rss-validator") (save-option #'set-follow-on-twitter "follow-on-twitter") (save-option #'set-email-subscription "email-subscription") (save-option #'set-idiot-location "idiot-location")) (defun save-resource(action params) (labels ((make-lookup() (let ((lst)) (setf lst (acons "web-analytics" #'set-google-analytics lst)) (setf lst (acons "google-meta-tag" #'set-google-meta-tag lst)) (setf lst (acons "contact-info" #'set-contact-info lst)) (setf lst (acons "rss-validator" #'set-rss-validator lst)) (setf lst (acons "follow-on-twitter" #'set-follow-on-twitter lst)) (setf lst (acons "email-subscription" #'set-email-subscription lst)) (setf lst (acons "rss-image-link" #'set-rss-link lst)) lst)) ;; (lookup-action (action lst) (cdr (assoc action lst :test #'equal)))) (let ((fn (namestring(car params)))) (load-script (lookup-action action (make-lookup)) fn)))) (defun redirect-to-options-page() (hunchentoot:redirect (concatenate 'string "/options/?"))) (defun save-options() (let ((which (hunchentoot:post-parameter "which")) (file (hunchentoot:post-parameter "file"))) (labels ((empty-qs() (eq 0 (length (hunchentoot:query-string*))))) (cond ( (empty-qs)(progn (save-options-main) (hunchentoot:redirect "/" ))) ( t (progn (save-resource which file) (redirect-to-options-page))))))) (defun options-page() (cond ((eq (hunchentoot:request-method*) :GET) (generate-options-page)) ((eq (hunchentoot:request-method*) :POST) (save-options)))) (defun discard-blog-post-page() (cond ((eq (hunchentoot:request-method*) :GET) (discard-blog-post)) ((eq (hunchentoot:request-method*) :POST) (discard-blog-post)))) (defun undo-discards() (undo-all-discards) (hunchentoot:redirect "/" )) (defun drop-discards() (drop-all-discards) (hunchentoot:redirect "/" )) (defun push-pages-to-repo(repo-path) (labels ((publish-index-page() (let ((fn (concatenate 'string repo-path "/index.html"))) (with-open-file (stream fn :direction :output :if-exists :supersede) (format stream "~A" (generate-index-page #'use-static-template :style-sheet 'online-style-sheet)) ;;(generate-index-page #'use-static-template) ))) (publish-style-sheet() (let ((fn (concatenate 'string repo-path "/style.css"))) (with-open-file (stream fn :direction :output :if-exists :supersede) (format stream "~A" (cat-style-sheet))))) (publish-rss-page() (let ((fn (concatenate 'string repo-path "/feed.xml"))) (with-open-file (stream fn :direction :output :if-exists :supersede) (format stream "~A" (generate-rss-page))))) (url-parts() (let ((lst)) (labels ((up(u) (if (slot-boundp u 'url-part) (push (url-part u) lst)))) (map-class #'up 'blog-post)) (nreverse lst))) (publish-other-pages() (dolist (up (url-parts)) (let ((fn (concatenate 'string repo-path "/" up ".html"))) (with-open-file (stream fn :direction :output :if-exists :supersede) (format stream "~A" (generate-blog-post-page (template-path "post.tmpl") up :render 'render-post :style-sheet 'online-style-sheet))))))) (publish-index-page) (publish-rss-page) (publish-style-sheet) (publish-other-pages))) (defun publish-pages*() (let ((repo-pathname (get-repo-pathname))) (switch-to-repo repo-pathname) (git-publish-branch) (when (get-mainstore?) (remove-files)) (push-pages-to-repo (namestring repo-pathname) ) (git-add-all-posts) (when (get-mainstore?) (git-rm-discarded-posts)) (git-commit) (git-master-branch) (git-merge) (git-publish) (switch-to-default-path))) (defun publish-pages() (publish-pages*) (hunchentoot:redirect "/")) ; (defun index-unless(d) (if (> (length d) 1) d "index.html")) (defun static-page-path(p) (let ((name (index-unless p))) (concatenate 'string (namestring (get-sandbox-pathname)) name))) (defun get-static-page(p) (with-open-file (stream (static-page-path p ) :direction :input) (slurp-stream stream))) (defun static-pages() (get-static-page (hunchentoot:request-uri*))) (defun generate-static-pages() (let ((repo-path (create-if-missing (get-sandbox-pathname)))) (push-pages-to-repo (namestring repo-path)) (get-static-page "index.html"))) (setq hunchentoot:*dispatch-table* (list (hunchentoot:create-regex-dispatcher "[.]html" (protect 'static-pages)) (hunchentoot:create-regex-dispatcher "[.]xml" (protect 'static-pages)) (hunchentoot:create-regex-dispatcher "^/$" (protect 'generate-editable-index-page)) (hunchentoot:create-regex-dispatcher "^/view/$" (protect 'view-blog-post-page)) (hunchentoot:create-regex-dispatcher "^/edit/$" (protect 'edit-blog-post-page)) (hunchentoot:create-regex-dispatcher "^/create/save-file" (protect 'save-file)) (hunchentoot:create-regex-dispatcher "^/edit/save-file" (protect 'save-file)) (hunchentoot:create-regex-dispatcher "^/discard/$" (protect 'discard-blog-post-page)) (hunchentoot:create-regex-dispatcher "^/import-repo/$" (protect 'import-repo-page)) (hunchentoot:create-regex-dispatcher "^/import-local/$" (protect 'import-local)) (hunchentoot:create-regex-dispatcher "^/import-remote/$" (protect 'import-remote)) (hunchentoot:create-regex-dispatcher "^/publish/$" (protect 'publish-pages)) (hunchentoot:create-regex-dispatcher "^/options/$" (protect 'options-page)) (hunchentoot:create-regex-dispatcher "^/rss-feed/$" (protect 'generate-rss-page)) (hunchentoot:create-regex-dispatcher "^/static-pages/$" (protect 'generate-static-pages)) (hunchentoot:create-regex-dispatcher "^/undo-discards/$" (protect 'undo-discards)) (hunchentoot:create-regex-dispatcher "^/drop-discards/$" (protect 'drop-discards)) (hunchentoot:create-regex-dispatcher "^/create/$" (protect 'create-blog-post-page)))) (defun start-server*() (setf *bliky-server* (make-instance 'hunchentoot:acceptor :port (get-bliky-port))) (hunchentoot:start *bliky-server*)) (defun start-server(name) (open-blog-store name) (unless *bliky-server* (start-server*))) ;;(defun stop-server() ;; (hunchentoot:stop-server *bliky-server*) ;; (setf *bliky-server* nil) ;; (close-store)) (defun stop-server() (close-store) ;;(hunchentoot:stop *bliky-server*) (setf *bliky-server* nil))
50,788
Common Lisp
.lisp
1,275
35.391373
119
0.616392
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
9bf85c3ee55a0dce0a354914de2af0e16d898e69e0ce644f71cb63cd5877d384
13,590
[ -1 ]
13,591
packages.lisp
fons_cl-bliky/src/packages.lisp
(in-package #:cl-user) (defpackage #:cl-bliky (:use #:common-lisp #:sb-ext #:net.html.parser #:net.html.generator #:cl-markdown #:hunchentoot #:html-template #:elephant) (:shadow :html) (:export :blog-post :stop-server :start-server :save-html-file :*BLIKY-HOME* ))
304
Common Lisp
.lisp
18
13.777778
22
0.652632
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
1634dca1d55c85a103faed7f5e55615cb468ed82d91872ca2efe3a63ded69e09
13,591
[ -1 ]
13,592
cl-bliky.asd
fons_cl-bliky/cl-bliky.asd
(in-package #:cl-user) (defpackage #:cl-bliky-system (:use #:cl #:asdf)) (in-package #:cl-bliky-system) (asdf:defsystem cl-bliky :name "cl-bliky" :author "Fons Haffmans; [email protected]" :version "0.0.1" :licence "See COPYING" :description "yet another lisp blog engine" :depends-on (:hunchentoot :elephant :cl-html-parse :htmlgen :cl-markdown :html-template) :serial t :components ((:module "src" :serial t :components ((:file "packages") (:file "bliky"))) (:static-file "README.md") (:static-file "COPYING")))
610
Common Lisp
.asd
23
21.695652
50
0.638261
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
9b5b50600bc64c96be9a6dd809f4719a18c563e11848a2133be6ed950e024917
13,592
[ -1 ]
13,595
sample-upload.txt
fons_cl-bliky/sample-upload.txt
Sample Upload Header <title> This is the introduction <split> This is the main part
87
Common Lisp
.l
5
15.8
24
0.835443
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
76786deb45189942f72e5c4f1e4314ccba856b6e73a278002d2d31c42fc61a7c
13,595
[ -1 ]
13,596
style.css
fons_cl-bliky/styles/style.css
/*------------------------------------------------------------------- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; --------------------------------------------------------------------------*/ /*----------------------------------------------------------------------------- Sheet : All sheets Purpose : General Formatting Comment : Default formatting, no tied to any template or div This is probably NOT the right way, since I created specific formatting under the 'general' settings, esp H1... -------------------------------------------------------------------------------*/ body{ margin:0px; padding:0x; #background:#ffffff; background:#eee9e9; #background:#fffacd; #color:#000011; font-size : 12px; font:normal 100% Sans-Serif; #:background-image; } p { margin:0px; padding:0x; ####background:#ffffff; ##background:#eee9e9; #color:#000011; font-size : 12px; font:normal 100% Sans-Serif; } a{ #padding:2px; margin:0px 0px 0px 0px; width:100%; border:none; color:#0000cc; text-decoration:none; } a:hover{ text-decoration:none; } a:visited{ color:#0000cc; } h1,h2,h3,h4,h5,h6{ color:#595959; color:black; #color:darkblue; font:bold 100% Sans-Serif; #padding:0px 0px 0px 0px; margin:5px 0px 5px 0px; #margin:0px 0px 5px 0px; width:100%; text-align:left; } h1 { font-size:180%; } h2 { font-size:160%; color:black; } h3 { font-size:110%; color:black; } pre { } code{ #border: 0.30em solid #D6D6D6; border-left: 0.3em solid #D6D6D6; display: block; padding: 1em 1em 1em 1em; color:#330066; background:#EDEDED; } /*--------------------------------------------------------------- Sheet : Index page Purpose : Formats the main column Comment : Basically sets up a two column format ----------------------------------------------------------------*/ #mainClm{ float:left; padding:13px 50px 10px 5%; width:68%; } /*--------------------------------------------------------------- Sheet : All pages Purpose : Formats the blog title Comment : Seperate format for the blog title ----------------------------------------------------------------*/ #blog-title { width:100%; padding: 10px 0px 0px 100px; #float:left; } #blog-title h1 { color: #0000cc; font:bold 580% Sans-Serif; #width:100%; #padding: 0px 0px 0px 0px; #border: 0.15em solid #D6D6D6; } /*--------------------------------------------------------------- Sheet : Import Page Purpose : formats the import page Comment : ----------------------------------------------------------------*/ #import-header h1 { color: #0000cc; font:bold Sans-Serif; width:100%; padding:15px 0px 0px 0px; font-size: 240%; #border-bottom:solid 4px #0000cc; } #import-edit h1, h2, h3 h4, h5 { padding:0px 0px 0px 0px; #color: #0000cc; color:black; font:bold Verdana,Sans-Serif; width:100%; #border-bottom:solid 2px #0000cc; } #import-edit h2 { font-size: 160%; } /*--------------------------------------------------------------- Sheet : Index Page / index.tmpl Purpose : Formats the side bar Comment : This is the sidebar to the left of the page ----------------------------------------------------------------*/ #sideBar{ padding:220px 0px 0px 0px; text-align:left; #background:#eee9e9; #background:black; #color:#111111; font-size : 12px; #font:normal 100% Sans-Serif; font:bold 150% Sans-Serif; } #sideBar p { margin:15px 15px 15px 15px; text-align:left; #background:#eee9e9; #font-size : 12px; font:Sans-Serif; font-size : 14px; #font:normal 100% Sans-Serif; } #sideBar h2 { #color:#0000cc; #font-size:120%; #font-size : 20px; } #sideBar ul{ margin:0px 0px 33px 0px; list-style-type:none; #font-size:100%; } #sideBar li { list-style-type:none; color:#111111; } #sideBar a { #color:#555555 color:red; } #sideBar a:hover { border-bottom: solid 2px red; } #sideBar ul a{ #color:#555555; color:black;##FF8000; list-style-type:underline; } #contact a { #color:#555555 } #rss-feed p { #color:#555555 } #contact a:hover { text-decoration:none; } #contact a:visited{ color:#0000cc; } /*------------------------------------------------------------------------- Sheet : Index and post sheets Purpose : Format the postings Comment : each post has a post and post-intro division This is probably NOT the right way, since I created specific formatting under the 'general' settings. --------------------------------------------------------------------------*/ /* h2 is also used for the blog post title... h6 is special; it's used to format the 'continue reading ..' link */ #post { margin: 1em 1em 1em 1em; padding: 1em 1em 1em 1em; border: 0.1em solid #FF8000; background:#F5F5F5; } #post p { background:#F5F5F5; } /* h2 is also used for the blog post title...*/ #post h2 { border-bottom:solid 1px #000000; #color: #0000cc; color:black; font:bold 160% Sans-Serif; } /*this is a special format to bring h2 in line with the other formats..*/ #post-intro h2 { #color:#595959; color:black; border-bottom:dotted 0px #cccccc; font-size:140%; } #post-body h2 { #color:#595959; color:black; border-bottom:dotted 0px #cccccc; font-size:140%; } /* h6 is special; it's used to format the 'continue reading ..' link */ #post h6 { margin:4px 0px 0px 0px; color:#0000cc; #font-family : 'Sans Serif'; font-size : 14px; font-weight : bold; } /*--------------------------------------------------------------- Sheet : Index and post sheets Purpose : Format the visible time stamp Comment : Each blog post has a time stamp in a specific div. ----------------------------------------------------------------*/ #post-timestamp p { margin:0px 0px 18px 0px; border-bottom-width : 4px; color : #cc0000; #font-family : , 'Sans Serif',; font-size : 12px; height : 4px; } /*--------------------------------------------------------------- Sheet : Index sheet Purpose : Format the footer Comment : Basically sets up a footer pointing to the bliky location on github, with a barely visible link ref. ----------------------------------------------------------------*/ #footer p { #font-family : , 'Sans Serif',; font-size:.75em; margin-top: 3em; text-align: center; text-indent: 0; } #footer a { color:#222222; } #footer a:hover { border-bottom: solid 2px red; } /* --------------------------------------------------------------------- Sheet : post-edit.tmpl Purpose : edit a blog post Comment : These are the styles used when editing a blog post -----------------------------------------------------------------------*/ #edit-page{ float:left; padding:13px 50px 10px 5%; width:80%; } #edit-header { margin:0px 0px 0px 0px; font-size:240%; } #edit-header h1 { margin:0px 0px 0px 0px; color:salmon; text-align: center; } #intro-buttons { margin:8px 0px 8px 0px; #background:#caff70; background:#f5deb3; border:solid 1px #cd0000; } #intro-buttons input { margin:2px 0px 2px 0px; text-align:left; #width:48%; font-family : 'Sans Serif'; font-size : 20px; #background:#F5F5F5; #background:#caff70; background:#d3d3d3; } #intro-edit input { margin:20px 0px 20px 0px; text-align:left; width:100%; font-family : 'Sans Serif'; font-size : 18px; #background:#F5F5F5; background:#f5deb3; } #intro-edit textarea { margin:0px 0px 0px 0px; text-align:left; width:100%; font-family : 'Sans Serif'; font-size : 18px; #background:#F5F5F5; background:#f5deb3; } #intro-edit h2 { border-bottom:solid 1px #000000; color: #0000cc; font:bold 110% Verdana,Sans-Serif; } /*--------------end of post-edit.tmpl style -------------------------*/ /* --------------------------------------------------------------------- Sheet : import.tmpl Purpose : import a repo Comment : These are the styles used when importing a repo -----------------------------------------------------------------------*/ #import-page{ float:left; padding:13px 50px 10px 5%; width:80%; } #import-header { margin:0px 0px 0px 0px; font-size:240%; } #import-header h1 { margin:0px 0px 0px 0px; color:salmon; text-align: center; } /*--------------end of import.tmpl style -------------------------*/ /* --------------------------------------------------------------------- Sheet : import.tmpl Purpose : import a repo Comment : These are the styles used when importing a repo -----------------------------------------------------------------------*/ #options-header { margin:0px 0px 0px 0px; font-size:240%; } #options-header h1 { margin:0px 0px 0px 0px; color:salmon; text-align: center; } #options-page{ float:left; padding:10px 0px 0px 50px; width:80%; font-size: 100%; } /*----------------- end of options style ----------------------------*/
12,874
Common Lisp
.l
384
22.848958
81
0.42124
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
540731c4ebd67e3d62d742ccbbfa2b683c8c9f2565d148ef722f5819007446fc
13,596
[ -1 ]
13,599
error.tmpl
fons_cl-bliky/templates/error.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title> BLIKY Error Message </title> <style type="text/css"> body{ padding:50px 50px 50px 50px; background:#ffffff; color:#000011; font:0.9em Sans-Serif; font:italic 100% Sans-Serif; float:left; } h1,h2,h3,h4,h5,h6{ padding:0px;margin:0px; } h1{ #margin:0px 0px 0px 0px; padding:50px 50px 50px 50px; color: #df0101; font:bold 200% Verdana,Sans-Serif; float:left; width:100%; } h2 { padding:50px 50px 50px 50px; #border-bottom:solid 1px #000000; color: #0000cc; font:bold 110% Verdana,Sans-Serif; } h3 { padding:50px 50px 50px 50px; #border-bottom:solid 1px #000000; color: #0000cc; font:italic 100% Sans-Serif; } </style> </head> <body> <h1> An error condition was detected</h1> <br> <br> <br> <br> <br> <br> <h2> <!--tmpl_var error-condition --> </h2> <br> <!--tmpl_var error-message --> </h2> <br> Please consult the documentation or the code for additional information. <a href="/"><h3> return to the main page</h3></a> </body> </html>
2,065
Common Lisp
.l
75
23.333333
90
0.636272
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
e355db221fa1cb3c37f2efe44cb6b83b879279e5f7ea428670a4aa236f4b0880
13,599
[ -1 ]
13,600
import.tmpl
fons_cl-bliky/templates/import.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title> Importing a git repository </title> <!-- tmpl_var style-sheet --> </head> <body> <div id="mainClm"> <div id="import-header"> <a href="/"> <h1> Import a git repository </h1> </a> <br> <br> <br> <br> </div> <div id="import-edit"> <h2> Instructions </h2> <br> </div> Import the local repo located in <!-- tmpl_var repo-pathname --> <div id="intro-buttons"> <form method="post" action="/import-local/?"> repo <input size="40" name="repo-path" value="<!-- tmpl_var repo-pathname -->" > <input type="submit" > </form> </div> Import a remote repo located at <!-- tmpl_var remote-repo --> <div id="intro-buttons"> <form method="post" action="/import-remote/?"> remote repo <input size="40" name="repo-path" value="<!-- tmpl_var repo-name -->" > <input type="submit"> </form> </div> </div> </body> </html>
1,818
Common Lisp
.l
57
28.736842
90
0.636364
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
3afc30bbbca0c4b8eaa098d97cc8d0ec24293785aa5918e52dfb95a175cf5b3f
13,600
[ -1 ]
13,601
index.tmpl
fons_cl-bliky/templates/index.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset =UTF-8"> <!-- tmpl_var google-meta-tag --> <title> <!-- tmpl_var blog-title --> </title> <!-- tmpl_var style-sheet --> </head> <body> <div id="blog-title"> <a href="/"> <h1> <!-- tmpl_var blog-title --> </h1> </a> </div> <div id="mainClm"> <!-- tmpl_if edit_part --> <hr> <a href="/options/?"> [options] </a> <a href="/create/?post"> [create new post] </a> <a href="/create/?sidebar"> [create new side bar] </a> <a href="/undo-discards/?"> [restore discarded posts] </a> <a href="/drop-discards/?"> [remove discarded posts] </a> <a href="/import-repo/?"> [import repo] </a> <a href="/static-pages/?<!-- tmpl_var sandbox-repo-qs -->" > [preview] </a> <a href="/publish/?<!-- tmpl_var main-repo-qs -->" > [publish] </a> <hr> <!-- /tmpl_if --> <!-- tmpl_loop blog-posts --> <div id="<!-- tmpl_var type -->"> <div id="post-timestamp" > <p><!-- tmpl_var timestamp --> </p> </div> <h2> <!-- tmpl_if edit_part --> <a href="/view/?<!--tmpl_var url-part -->"> <!-- tmpl_var title --> </a> <!-- tmpl_else --> <a href="/<!--tmpl_var url-part -->.html"> <!-- tmpl_var title --> </a> <!-- /tmpl_if --> </h2> <div id="post-intro"> <!-- tmpl_var intro --> </div> <!-- tmpl_if edit_part --> <a href="/view/?<!--tmpl_var url-part -->"> <h6> Continue reading "<!-- tmpl_var title -->" </h6></a> <!-- tmpl_else --> <a href="/<!--tmpl_var url-part -->.html"> <h6> Continue reading "<!-- tmpl_var title -->" </h6> </a> <!-- /tmpl_if --> <!-- tmpl_if edit_part --> <div id="editButton"> <a href="/edit/?<!--tmpl_var url-part -->"> [edit] </a> <a href="/discard/?<!--tmpl_var url-part -->"> [discard] </a> </div> <!-- /tmpl_if --> </div> <!-- /tmpl_loop --> <div id="footer"> <p> Powered by <a href="http://www.github.com/fons/cl-bliky"> cl-bliky </a> <!-- tmpl_var google-analytics --> </p> </div> </div> <!-- end of main area --> <!-- start of the sidebar --> <div id="sideBar"> <div id="about"> <!-- tmpl_if edit_part --> <a href="/view/?<!--tmpl_var about -->"> <h2> About </h2></a> <!-- tmpl_else --> <a href="/<!--tmpl_var about -->.html"> <h2> About </h2> </a> <!-- /tmpl_if --> <!-- tmpl_if edit_part --> <a href="/edit/?<!--tmpl_var about -->"> [edit] </a> <!-- /tmpl_if --> </div> <div id="contact"> <!-- tmpl_var contact-info --> </div> <div id="rss-feed"> <!-- tmpl_if edit_part --> <a href="/rss-feed/?"> <!-- tmpl_else --> <a href="/feed.xml"> <!-- /tmpl_if --> <!-- tmpl_var rss-link --> </a> </div> <div id="rss-validator"> <!-- tmpl_var rss-validator --> </div> <div id="follow-on-twitter"> <!-- tmpl_var follow-on-twitter --> </div> <div id="email-subscription"> <!-- tmpl_var email-subscription --> </div> <div id="side-bars"> <!-- tmpl_loop sidebars --> <h2> <!-- tmpl_var title --> </h2> <div> <!-- tmpl_var intro --> </div> <div> <!-- tmpl_var body --> </div> <!-- tmpl_if edit_part --> <div id="editButton"> <a href="/edit/?<!--tmpl_var url-part -->"> [edit] </a> <a href="/discard/?<!--tmpl_var url-part -->"> [discard] </a> </div> <!-- /tmpl_if --> <!-- /tmpl_loop --> </div> <!--end of sidebar--> </body> </html>
4,473
Common Lisp
.l
135
28.355556
107
0.528328
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
3310fc6865b395e39887f289e2bbeda016eeaa1f26fb7b74c9575198323b37ee
13,601
[ -1 ]
13,602
options.tmpl
fons_cl-bliky/templates/options.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/> ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset =UTF-8"> <title> Blog Engine Settings </title> <!-- tmpl_var style-sheet --> </head> <body> <div id="options-header"> <a href="/"> <h1> Options </h1> </a> </div> <div id="options-page"> Below are the current settings for the various options. <hr> <form method="post" action="?"> <input type="checkbox" name="is-mainstore?" <!-- tmpl_var is-mainstore --> > When this box is checked the current store is the main store. The repo will be synched with the pages in the current store. <hr> <input type="checkbox" name="is-offline?" <!-- tmpl_var is-offline --> > When this box is checked you are working off line. Publishing to the remote repo is disabled. <hr> <input type="text" name="bliky-port" size="60" value="<!-- tmpl_var bliky-port -->" > the port used by the web server <hr> <input type="text" name="repo-pathname" size="60" value="<!-- tmpl_var repo-pathname -->" > the path to the main repo <hr> <input type="text" name="sandbox-pathname" size="60" value="<!-- tmpl_var sandbox-pathname -->" > path where the previews are stored <hr> <input type="text" name="template-pathname" size="60" value="<!-- tmpl_var template-pathname -->" > path where the html templates are stored <hr> <input type="text" name="styles-pathname" size="60" value="<!-- tmpl_var styles-pathname -->" > path where the html styles are stored <hr> <input type="text" name="script-pathname" size="60" value="<!-- tmpl_var script-pathname -->" > path where the scripts are stored; Used in loader scripts run from the repl <hr> <input type="text" name="idiot-location" size="60" value="<!-- tmpl_var idiot-location -->" > the old files are copied here before the repo is synched with the store. <hr> <input type="text" name="remote-repo" size="60" value="<!-- tmpl_var remote-repo -->" > name of the host where the remote git repository is located. <hr> <input type="text" name="blog-title" size="60" value="<!-- tmpl_var blog-title -->" > title of the blog (used in the rss feed as well). <hr> <input type="text" name="background-uri" size="90" value="<!-- tmpl_var background-uri -->" > location of background image <hr> This is the google meta tag used for <a href="https://www.google.com/webmasters/verification/home?hl=en" > google site verification. </a> <textarea rows="5" cols="150" type="text" name="google-meta-tag"> <!-- tmpl_var google-meta-tag --> </textarea> <hr> Follow me on Twitter <textarea rows="5" cols="150" type="text" name="follow-on-twitter"> <!-- tmpl_var follow-on-twitter --> </textarea> <hr> Email subscription <textarea rows="5" cols="150" type="text" name="email-subscription"> <!-- tmpl_var email-subscription --> </textarea> This is the html which enables the contact form generated by <a href=\"http://kontactr.com/user/prognotes\"> kontactr.com </a> <textarea rows="5" cols="150" type="text" name="contact-info"> <!-- tmpl_var contact-info --> </textarea> This is web the analytics javascript from <a href="http://www.google.com"> google analytics </a> <textarea rows="10" cols="150" type="text" name="web-analytics"> <!-- tmpl_var web-analytics --> </textarea> This is the image used for the rss link. <textarea rows="5" cols="150" type="text" name="rss-image-link"> <!-- tmpl_var rss-image-link --> </textarea> This is the image used for the rss link validator. <textarea rows="5" cols="150" type="text" name="rss-validator"> <!-- tmpl_var rss-validator --> </textarea> <input type="submit" value="save options" /> </form> <br> <hr> Java script or other files used to generate contact forms or web analytics cen be uploaded below. Code is injected into the web pages as part of the publishing process. <form enctype="multipart/form-data" method="post" action="?save-option-file"> <select name="which" size=1> <option value="contact-info" selected > contact info <option value="web-analytics" > web analytics <option value="rss-image-link" > rss image link <option value="rss-validator" > rss validator <option value="google-meta-tag" > google-meta-tag <option value="follow-on-twitter" > follow-on-twitter <option value="email-subscription" > email-subscription </select> <input type="file" size="40" name="file" value="select file" > <input type="submit" size="20" name="file" value="upload"> </form> <hr> <br> </div> </body> </html>
5,821
Common Lisp
.l
129
39.674419
108
0.638742
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
3451572f1b72bc6bd577ac6800e188ee778b52d5cf786ff2c019043eda91cb0f
13,602
[ -1 ]
13,603
post-edit.tmpl
fons_cl-bliky/templates/post-edit.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title> Create or edit a blog post </title> <!-- tmpl_var style-sheet --> </head> <body> <div id="edit-header"> <a href="/"> <h1> Edit blog post </h1> </a> </div> <div id="edit-page"> <div id="intro-buttons"> <form enctype="multipart/form-data" method="post" action="save-file?<!-- tmpl_var url_part -->"> <input type="file" size="40" name="file" value="select file" > <input type="submit" size="20" name="file" value="upload"> </form> <!-- The main form closes all the way down --> <form action="?<!-- tmpl_var url_part -->" method="post"> <input type="submit" value="save post" /> </div> <div id="intro-edit"> <h2> Title </h2> <input type="text" name="title" value="<!-- tmpl_var title -->" /> <h2> Intro </h2> <textarea rows="10" type="text" name="intro"> <!-- tmpl_var intro --> </textarea> <h2> Body </h2> <textarea rows="30" type="text" name="body" > <!-- tmpl_var body --> </textarea> </div> <div id="intro-buttons"> <input type="submit" value="save post" /> </div> </form> <!-- end of the main form --> </div> </body> </html>
2,050
Common Lisp
.l
57
32.824561
97
0.624622
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
9af3afe095a64b6c0b3a0029e82ff1f174792e7ffc0b925058d063a55bf53916
13,603
[ -1 ]
13,604
rss.tmpl
fons_cl-bliky/templates/rss.tmpl
<?xml version="1.0" encoding="UTF-8"?> <!-- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; --> <?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?> <?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?> <rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" version="2.0"> <!-- rss version='2.0' xmlns:atom="http://www.w3.org/2005/Atom" --> <channel> <title> <!-- tmpl_var blog-title --> </title> <link> <!-- tmpl_var blog-url --> </link> <description> <!-- tmpl_var blog-description --> </description> <pubDate> <!-- tmpl_var rss-generation-date --> </pubDate> <!-- tmpl_loop blog-posts --> <item> <title> <!-- tmpl_var title --> </title> <link> <!--tmpl_var blog-url --><!--tmpl_var url-part -->.html </link> <description> <!-- tmpl_var intro --> </description> <content:encoded><![CDATA[<!-- tmpl_var cdata --> ]]></content:encoded> <guid> <!-- tmpl_var blog-url --><!-- tmpl_var url-part -->.html </guid> <pubDate> <!-- tmpl_var timestamp --> </pubDate> </item> <!-- /tmpl_loop --> </channel> </rss>
1,947
Common Lisp
.l
43
42.348837
120
0.639137
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
dff7b8276b5708408466516d043da95f7563d6f2893475a8ee0e96de9dffd2fa
13,604
[ -1 ]
13,605
post.tmpl
fons_cl-bliky/templates/post.tmpl
<!--- ;; ;; This softeware is Copyright (c) 2009 A.F. Haffmans ;; ;; This file is part of cl-bliky. ;; ;; cl-bliky is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bliky is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bliky. If not, see <http://www.gnu.org/licenses/>. ;; ;; ---> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title> <!-- tmpl_var blog-title --> </title> <!-- tmpl_var style-sheet --> </head> <body> <div id="blog-title"> <a href="/"> <h1> <!-- tmpl_var blog-title --> </h1> </a> </div> <div id="mainClm"> <div id="<!-- tmpl_var type -->"> <div id="post-type" style="visibility:hidden"> <p>"<!-- tmpl_var type -->"</p> </div> <div id="post-timestamp" > <p><!-- tmpl_var timestamp --> </p> </div> <div id="post-header"> <h2> <!-- tmpl_var title --> </h2> </div> <div id="post-intro"> <!-- tmpl_var intro --> </div> <div id="post-body"> <!-- tmpl_var body --> </div> <div id="post-timestamp-id" style="visibility:hidden"> <p><!-- tmpl_var timestamp-id --> </p> </div> </div> <div id="footer"> <p> Powered by <a href="http://www.github.com/fons/cl-bliky"> cl-bliky </a> </p> </div> </div><!-- end of main area --> </body> </html>
1,827
Common Lisp
.l
60
27.45
90
0.606632
fons/cl-bliky
7
1
7
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
c74c400ed61dd82803b3c1ab422e296a6b5ff4bd6239a8cbc1ba0abe8672e03e
13,605
[ -1 ]
13,620
eqv-hash-test.lisp
amb007_cl-automaton/eqv-hash-test.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package :eqv-hash-user) (defclass foo () ((slot1 :initform 0 :initarg :slot1 :type fixnum :accessor slot1) (slot2 :initform 0 :initarg :slot2 :type fixnum :accessor slot2))) (defclass foo-intention (equalp-key-situation) ()) (defparameter +foo-intention+ (make-instance 'foo-intention)) (defmethod eqv ((foo1 foo) (foo2 foo) (s (eql +foo-intention+))) (eql (slot1 foo1) (slot1 foo2))) (defmethod hash ((foo1 foo) (s (eql +foo-intention+))) (floor (slot1 foo1) 2)) (deftest htref.test-1 ; (eqv i1 i2), (= (hash i1) (hash i2)) (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 1 :slot2 2)) (i2 (make-instance 'foo :slot1 1 :slot2 3))) (setf (htref ght i1) i1) (setf (htref ght i2) i2) (and (= (cnt ght) 1) (eq (htref ght i1) i2) (eq (htref ght i2) i2))) t) (deftest htref.test-2 ; (not (eqv i1 i2)), (= (hash i1) (hash i2)) (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3))) (setf (htref ght i1) i1) (setf (htref ght i2) i2) (and (= (cnt ght) 2) (eq (htref ght i1) i1) (eq (htref ght i2) i2))) t) (deftest htref.test-3 ; (not (eqv i1 i2)), (/= (hash i1) (hash i2)) (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 4))) (setf (htref ght i1) i1) (setf (htref ght i2) i2) (and (= (cnt ght) 2) (eq (htref ght i1) i1) (eq (htref ght i2) i2))) t) (deftest htref.test-4 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 1 :slot2 2)) (i2 (make-instance 'foo :slot1 1 :slot2 3))) (setf (htref ght i1) i1) (and (= (cnt ght) 1) (eq (htref ght i2) i1))) t) (deftest htref.test-5 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 1 :slot2 2)) (i2 (make-instance 'foo :slot1 1 :slot2 3))) (setf (htref ght i1) i1) (multiple-value-bind (v vp) (htref ght i2) (declare (ignore v)) (values (cnt ght) vp))) 1 t) (deftest htref.test-6 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3))) (setf (htref ght i1) i1) (htref ght i2)) nil nil) (deftest htref.test-7 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3))) (and (eq (setf (htref ght i1) i2) i2) (= (cnt ght) 1))) t) (deftest htadd.test-1 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (htadd ght i1) (htref ght i1)) t t) (deftest htadd.test-2 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (htref ght i1)) nil nil) (deftest htadd.test-3 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3))) (htadd ght i1) (htref ght i2)) nil nil) (deftest htpresent.test-1 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (htadd ght i1) (and (= (cnt ght) 1) (htpresent ght i1))) t) (deftest htpresent.test-2 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (and (= (cnt ght) 0) (htpresent ght i1))) nil) (deftest htremove.test-1 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (values (htremove ght i1) (= (cnt ght) 0) (htref ght i1))) nil t nil) (deftest htremove.test-2 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2))) (htadd ght i1) (values (htremove ght i1) (= (cnt ght) 0) (htref ght i1))) t t nil) (deftest with-ht.test-1 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3)) l) (htadd ght i1) (htadd ght i2) (with-ht (k v) ght (push (cons k v) l)) (and (= (length l) 2) (equal (assoc i1 l) (cons i1 t)) (equal (assoc i2 l) (cons i2 t)))) t) (deftest with-ht.test-2 (let ((ght (make-generalized-hash-table +foo-intention+)) l) (with-ht (k v) ght (push (cons k v) l)) l) nil) (deftest with-ht-collect.test-1 (let ((ght (make-generalized-hash-table +foo-intention+)) (i1 (make-instance 'foo :slot1 2)) (i2 (make-instance 'foo :slot1 3)) l) (htadd ght i1) (htadd ght i2) (let ((l (with-ht-collect (k v) ght (cons k v)))) (and (= (length l) 2) (equal (assoc i1 l) (cons i1 t)) (equal (assoc i2 l) (cons i2 t))))) t) (deftest with-ht-collect.test-2 (let ((ght (make-generalized-hash-table +foo-intention+))) (with-ht-collect (k v) ght (cons k v))) nil)
4,981
Common Lisp
.lisp
156
28.589744
69
0.631842
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
cf9480c2145bd0c34dcd642d4ef64d04ba63c954a30cc30933f7ce3b3c2f2620
13,620
[ -1 ]
13,621
regexp.lisp
amb007_cl-automaton/regexp.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; ;;; Derived from dk.brics.automaton v1.8.1, (c) 2001-2005 by Anders Møller ;;; - Some comments have been copied verbatim from the original code. ;;; Regular expressions are built from the following abstract syntax: ;;; regexp ::= unionexp ;;; unionexp ::= interexp | unionexp (union) ;;; | interexp ;;; interexp ::= concatexp & interexp (intersection) [OPTIONAL] ;;; | concatexp ;;; concatexp ::= repeatexp concatexp (concatenation) ;;; | repeatexp ;;; repeatexp ::= repeatexp ? (zero or one occurrence) ;;; | repeatexp * (zero or more occurrences) ;;; | repeatexp + (one or more occurrences) ;;; | repeatexp {n} (n occurrences) ;;; | repeatexp {n,} (n or more occurrences) ;;; | repeatexp {n,m} (n to m occurrences, including both) ;;; | complexp ;;; complexp ::= ~ complexp (complement) [OPTIONAL] ;;; | charclassexp ;;; charclassexp ::= [ charclasses ] (character class) ;;; | [^ charclasses ] (negated character class) ;;; | simpleexp ;;; charclasses ::= charclass charclasses ;;; | charclass ;;; charclass ::= charexp - charexp (character range, including end-points) ;;; | charexp ;;; simpleexp ::= charexp ;;; | . (any single character) ;;; | # (the empty language) [OPTIONAL] ;;; | @ (any string) [OPTIONAL] ;;; | " <Unicode string without double-quotes> " (a string) ;;; | ( ) (the empty string) ;;; | ( unionexp ) (precedence override) ;;; | < <identifier> > (named automaton) [OPTIONAL] ;;; | <n-m> (numerical interval) [OPTIONAL] ;;; charexp ::= <Unicode character> (a single non-reserved character) ;;; | \ <Unicode character> (a single character) ;;; The productions marked [OPTIONAL] are only allowed if specified by ;;; the syntax flags passed to the string-regexp constructor. The ;;; reserved characters used in the (enabled) syntax must be escaped ;;; with backslash (\) or double-quotes ("..."). (In contrast to other ;;; regexp syntaxes, this is required also in character classes.) Be ;;; aware that dash (-) has a special meaning in charclass ;;; expressions. An identifier is a string not containing right angle ;;; bracket (>) or dash (-). Numerical intervals are specified by ;;; non-negative decimal integers and include both end points, and if ;;; n and m have the same number of digits, then the conforming ;;; strings must have that length (i.e. prefixed by 0's). (in-package :automaton) (deftype kind () '(member nil :union :concatenation :intersection :optional :repeat :repeat-min :repeat-minmax :complement :char :char-range :anychar :empty :string :anystring :automaton :interval)) (defconstant +intersection+ #x0001) ; enables intersection (&) (defconstant +complement+ #x0002) ; enables complement (~) (defconstant +empty+ #x0004) ; enables empty language (#) (defconstant +anystring+ #x0008) ; enables anystring (@) (defconstant +automaton+ #x0010) ; enables named automaton (<id>) (defconstant +interval+ #x0020) ; enables numerical intervals (n-m) (defconstant +all+ #xffff) ; enables all optional syntax (defconstant +none+ #x0000) ; enables no optional syntax (deftype flags-type () `(integer ,+none+ ,+all+)) (defclass regexp () ((kind :initform nil :initarg :kind :reader kind :type kind) (exp1 :initform nil :initarg :exp1 :reader exp1 :type (or null regexp)) (exp2 :initform nil :initarg :exp2 :reader exp2 :type (or null regexp)) (text :initform nil :initarg :text :reader text :type (or null string)) (s :initform nil :initarg :s :reader s :type (or null string)) (c :initform nil :initarg :c :reader c :type (or null character)) (minr :initform nil :initarg :minr :reader minr :type (or null fixnum)) (maxr :initform nil :initarg :maxr :reader maxr :type (or null fixnum)) (digits :initform nil :initarg :digits :reader digits :type (or null fixnum)) (from :initform nil :initarg :from :reader from :type (or null character)) (to :initform nil :initarg :to :reader to :type (or null character)) (flags :initform +all+ :initarg :flags :reader flags :type flags-type) (pos :initform 0 :initarg :pos :accessor pos :type integer))) (defun regexp-equal (r1 r2) ; for testing (or (eq r1 r2) (and (eq (kind r1) (kind r2)) (regexp-equal (exp1 r1) (exp1 r2)) (regexp-equal (exp2 r1) (exp2 r2)) (equal (s r1) (s r2)) (eql (c r1) (c r2)) (eql (minr r1) (minr r2)) (eql (maxr r1) (maxr r2)) (eql (digits r1) (digits r2)) (eql (from r1) (from r2)) (eql (to r1) (to r2)) (eql (flags r1) (flags r2))))) (defun string-regexp (s &optional fs) "Returns a new regexp object corresponding to regular expression string S. FS is a logior or optional syntax flags." (let* ((r (make-instance 'regexp :text s :flags (or fs +all+))) (e (parse-union-exp r))) (when (more r) (error "end of string expected at position ~A" (pos r))) e)) (defun regexp-automaton (r &optional as) "Returns a new automaton object corresponding to regexp R. AS is a hash table mapping from identifiers to auxiliary named automata. (An error is signaled if R uses an identifier not in AS.) The constructed automaton is deterministic and minimal, and has no transitions to dead states." (let ((a (ecase (kind r) (:union (aunion (regexp-automaton (exp1 r) as) (regexp-automaton (exp2 r) as))) (:concatenation (aconcatenate (regexp-automaton (exp1 r) as) (regexp-automaton (exp2 r) as))) (:intersection (aintersection (regexp-automaton (exp1 r) as) (regexp-automaton (exp2 r) as))) (:optional (optional (regexp-automaton (exp1 r) as))) (:repeat (repeat (regexp-automaton (exp1 r) as))) (:repeat-min (repeat-min (regexp-automaton (exp1 r) as) (minr r))) (:repeat-minmax (repeat-minmax (regexp-automaton (exp1 r) as) (minr r) (maxr r))) (:complement (acomplement (regexp-automaton (exp1 r) as))) (:char (char-automaton (char-code (c r)))) (:char-range (char-range-automaton (char-code (from r)) (char-code (to r)))) (:anychar (any-char-automaton)) (:empty (empty-automaton)) (:string (string-automaton (s r))) (:anystring (any-string-automaton)) (:automaton (let ((aa (gethash (s r) as))) (if aa (clone aa) (error "~A not found" (s r))))) (:interval (interval-automaton (minr r) (maxr r) (digits r)))))) (minimize a))) (defmethod print-object ((r regexp) s) (ecase (kind r) (:union (princ "(" s) (print-object (exp1 r) s) (princ "\|" s) (print-object (exp2 r) s) (princ ")" s)) (:concatenation (print-object (exp1 r) s) (print-object (exp2 r) s)) (:intersection (princ "(" s) (print-object (exp1 r) s) (princ "&" s) (print-object (exp2 r) s) (princ ")" s)) (:optional (princ "(" s) (print-object (exp1 r) s) (princ ")?" s)) (:repeat (princ "(" s) (print-object (exp1 r) s) (princ ")*" s)) (:repeat-min (princ "(" s) (print-object (exp1 r) s) (princ "){" s) (princ (minr r) s) (princ ",}" s)) (:repeat-minmax (princ "(" s) (print-object (exp1 r) s) (princ "){" s) (princ (minr r) s) (princ "," s) (princ (maxr r) s) (princ "}" s)) (:complement (princ "~(" s) (print-object (exp1 r) s) (princ ")" s)) (:char (princ "\\" s) (princ (c r) s)) (:char-range (princ "[\\" s) (princ (from r) s) (princ "-\\" s) (princ (to r) s) (princ "]" s)) (:anychar (princ "." s)) (:empty (princ "#" s)) (:string (princ "\"" s) (princ (s r) s) (princ "\"" s)) (:anystring (princ "@" s)) (:automaton (princ "<" s) (princ (s r) s) (princ ">" s)) (:interval (princ "<" s) (format s "~V,'0D" (digits r) (minr r)) (princ "-" s) (format s "~V,'0D" (digits r) (maxr r)) (princ ">" s)))) (defun more (r) (< (pos r) (length (text r)))) (defun peek (r s) (and (more r) (position (aref (text r) (pos r)) s))) (defun match (r c) (and (more r) (char= (aref (text r) (pos r)) c) (incf (pos r)))) (defun next (r) (if (more r) (prog1 (aref (text r) (pos r)) (incf (pos r))) (error "unexpected end of string"))) (defun check (r flag) (not (= (logand (flags r) flag) 0))) (defun make-regexp (kind &optional e1 e2) (make-instance 'regexp :kind kind :exp1 e1 :exp2 e2)) (defun parse-union-exp (r) (let ((e (parse-intersection-exp r))) (if (match r #\|) (make-regexp :union e (parse-union-exp r)) e))) (defun parse-intersection-exp (r) (let ((e (parse-concatenation-exp r))) (if (and (check r +intersection+) (match r #\&)) (make-regexp :intersection e (parse-intersection-exp r)) e))) (defun parse-concatenation-exp (r) (let ((e (parse-repeat-exp r))) (if (and (more r) (not (peek r ")&\|"))) (let* ((ee (parse-concatenation-exp r)) (ee1 (exp1 ee))) (cond ; optimizations? ((and (member (kind e) '(:string :char)) (eq (kind ee) :concatenation) (member (kind ee1) '(:string :char))) (let ((ss (format nil "~A~A" (if (eq (kind e) :string) (s e) (c e)) (if (eq (kind ee1) :string) (s ee1) (c ee1))))) (if (position #\" ss) (make-regexp :concatenation (make-instance 'regexp :kind :string :s ss) (exp2 ee)) (make-regexp :concatenation e ee)))) ((and (member (kind e) '(:string :char)) (member (kind ee) '(:string :char))) (let ((ss (format nil "~A~A" (if (eq (kind e) :string) (s e) (c e)) (if (eq (kind ee) :string) (s ee) (c ee))))) (if (position #\" ss) (make-regexp :concatenation e ee) (make-instance 'regexp :kind :string :s ss)))) (t (make-regexp :concatenation e ee)))) e))) (defun parse-repeat-exp (r) (let ((e (parse-complement-exp r))) (loop while (peek r "?*+{") do (cond ((match r #\?) (setq e (make-regexp :optional e))) ((match r #\*) (setq e (make-regexp :repeat e))) ((match r #\+) (setq e (make-instance 'regexp :kind :repeat-min :exp1 e :minr 1))) ((match r #\{) (let ((start (pos r))) (loop while (peek r "0123456789") do (next r)) (when (= start (pos r)) (error "integer expected at position ~A" (pos r))) (let ((n (parse-integer (text r) :start start :end (pos r))) (m nil)) (if (match r #\,) (let ((start (pos r))) (loop while (peek r "0123456789") do (next r)) (when (/= start (pos r)) (setq m (parse-integer (text r) :start start :end (pos r))))) (setq m n)) (unless (match r #\}) (error "expected '}' at positiion ~A" (pos r))) (return-from parse-repeat-exp (if m (make-instance 'regexp :kind :repeat-minmax :exp1 e :minr n :maxr m) (make-instance 'regexp :kind :repeat-min :exp1 e :minr n))))))) finally (return e)))) (defun parse-complement-exp (r) (if (and (check r +complement+) (match r #\~)) (make-regexp :complement (parse-complement-exp r)) (parse-char-class-exp r))) (defun parse-char-class-exp (r) (if (match r #\[) (let ((negate (match r #\^)) (e (parse-char-classes r))) (unless (match r #\]) (error "expected ']' at position ~A" (pos r))) (if negate (make-regexp :intersection (make-regexp :anychar) (make-regexp :complement e)) e)) (parse-simple-exp r))) (defun parse-char-classes (r) (let ((e (parse-char-class r))) (loop while (and (more r) (not (peek r "]"))) do (setq e (make-regexp :union e (parse-char-class r))) finally (return e)))) (defun parse-char-class (r) (let ((c (parse-char-exp r))) (if (match r #\-) (make-instance 'regexp :kind :char-range :from c :to (parse-char-exp r)) (make-instance 'regexp :kind :char :c c)))) (defun parse-simple-exp (r) (cond ((match r #\.) (make-regexp :anychar)) ((and (check r +empty+) (match r #\#)) (make-regexp :empty)) ((and (check r +anystring+) (match r #\@)) (make-regexp :anystring)) ((match r #\") (let ((start (pos r))) (loop while (and (more r) (not (peek r "\""))) do (next r)) (unless (match r #\") (error "expected '\"' at position ~A" (pos r))) (make-instance 'regexp :kind :string :s (subseq (text r) start (1- (pos r)))))) ((match r #\() (if (match r #\)) (make-instance 'regexp :kind :string :s "") (let ((e (parse-union-exp r))) (unless (match r #\)) (error "expected ')' at position ~A" (pos r))) e))) ((and (or (check r +automaton+) (check r +interval+)) (match r #\<)) (let ((start (pos r))) (loop while (and (more r) (not (peek r ">"))) do (next r)) (unless (match r #\>) (error "expected '>' at position ~A" (pos r))) (let* ((s (subseq (text r) start (1- (pos r)))) (i (position #\- s))) (if i (progn (unless (check r +interval+) (error "illegal identifier at position ~A" (1- (pos r)))) (handler-bind ((error #'(lambda (c) (error "interval syntax error at position ~A (~A)" (1- (pos r)) c)))) (when (or (= i 0) (= i (length s)) (/= i (position #\- s :from-end t))) (error "number format exception")) (let* ((smin (subseq s 0 i)) (smax (subseq s (1+ i))) (imin (parse-integer smin)) (imax (parse-integer smax)) (digs (if (= (length smin) (length smax)) (length smin) 0))) (when (> imin imax) (rotatef imin imax)) (make-instance 'regexp :kind :interval :minr imin :maxr imax :digits digs)))) (if (check r +automaton+) (make-instance 'regexp :kind :automaton :s s) (error "interval syntax error at position ~A" (1- (pos r)))))))) (t (make-instance 'regexp :kind :char :c (parse-char-exp r))))) (defun parse-char-exp (r) (match r #\\) (next r))
14,494
Common Lisp
.lisp
394
32.106599
77
0.579022
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
028c2f27eccc21eafdfcabbe3543f7eb691c664cb6a33b69809bf74903e1202b
13,621
[ -1 ]
13,622
automaton-package.lisp
amb007_cl-automaton/automaton-package.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (defpackage #:eqv-hash (:use :cl) (:export #:hash #:eqv #:key-situation #:builtin-key-situation #:eq-key-situation #:+eq-key-situation+ #:eql-key-situation #:+eql-key-situation+ #:equal-key-situation #:+equal-key-situation+ #:equalp-key-situation #:+equalp-key-situation+ #:case-sensitive-key-situation #:+case-sensitive-key-situation+ #:case-insensitive-key-situation #:+case-insensitive-key-situation+ #:make-generalized-hash-table #:generalized-hash-table #:ht #:cnt #:situation #:htref #:htadd #:htremove #:htpresent #:with-ht #:with-ht-collect)) (defpackage #:automaton (:nicknames #:cl-automaton) (:use :cl #:eqv-hash) (:export #:string-regexp #:regexp-automaton #:run #:run-to-first-match #:run-to-first-unmatch #:state-equal #:automaton-equal #:regexp-equal))
964
Common Lisp
.lisp
41
20.02439
62
0.659805
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
b9585d2c2d26fd3d94113b3d93b0bbe90a3a46925d4c6f0078a0fa2ae06be71d
13,622
[ -1 ]
13,623
automaton-test.lisp
amb007_cl-automaton/automaton-test.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package :automaton-user) (defmacro defmultitest (name form &rest results) (let ((name-string (symbol-name name))) (flet ((%dts (prefixes) (loop for v1 in prefixes nconc (loop for v2 in '(t nil) collect `(deftest ,(intern (concatenate 'string (symbol-name v1) (if v2 "" "-LIGHT") "." name-string)) (let ((automaton::*minimization* ',(intern (symbol-name v1) :automaton)) (automaton::*minimize-always* ,v2)) ,form) ,@results))))) `(progn ,@(%dts '(hopcroft huffman brzozowski)))))) (defmultitest regexp-automaton.test-1 (automaton-equal (let ((a (regexp-automaton (string-regexp "#")))) (and (not (run a "")) (not (run a "#")) a)) (automaton::minimize (automaton::empty-automaton))) t) (defmultitest regexp-automaton.test-2 (automaton-equal (let ((a (regexp-automaton (string-regexp "foo")))) (and (run a "foo") a)) (automaton::minimize (automaton::string-automaton "foo"))) t) (defmultitest regexp-automaton.test-2a (automaton-equal (let ((a (regexp-automaton (string-regexp "()")))) (and (run a "") (not (run a " ")) a)) (automaton::minimize (automaton::string-automaton ""))) t) (defmultitest regexp-automaton.test-2b (automaton-equal (regexp-automaton (string-regexp "()")) (automaton::minimize (automaton::empty-automaton))) nil) (defmultitest regexp-automaton.test-3 (automaton-equal (let ((a (regexp-automaton (string-regexp "c")))) (and (run a "c") (not (run a "C")) a)) (automaton::minimize (automaton::char-automaton (char-code #\c)))) t) (defmultitest regexp-automaton.test-4 (automaton-equal (let ((a (regexp-automaton (string-regexp ".")))) (and (run a "x") (not (run a "xx")) a)) (automaton::minimize (automaton::any-char-automaton))) t) (defmultitest regexp-automaton.test-5 (automaton-equal (let ((a (regexp-automaton (string-regexp "@")))) (and (run a "foo") a)) (automaton::minimize (automaton::any-string-automaton))) t) (defmultitest regexp-automaton.test-6 (automaton-equal (let ((a (regexp-automaton (string-regexp "<11-15>")))) (and (run a "13") (not (run a "10")) (not (run a "16")) (not (run a "20")) (not (run a "011")) a)) (automaton::minimize (automaton::interval-automaton 11 15 2))) t) (defmultitest regexp-automaton.test-6a (automaton-equal (let ((a (regexp-automaton (string-regexp "<11-115>")))) (and (run a "13") (run a "113") (not (run a "116")) (run a "00114") (run a "20") (not (run a "200")) (run a "011") a)) (automaton::minimize (automaton::interval-automaton 11 115 0))) t) (defmultitest regexp-automaton.test-6b (automaton-equal (let ((a (regexp-automaton (string-regexp "<115-11>")))) (and (run a "13") (run a "113") (not (run a "116")) (run a "00114") (run a "20") (not (run a "200")) (run a "011") a)) (automaton::minimize (automaton::interval-automaton 11 115 0))) t) (defmultitest regexp-automaton.test-7 (let ((ht (make-hash-table :test #'equal))) (setf (gethash "sub" ht) (automaton::empty-automaton)) (automaton-equal (let ((a (regexp-automaton (string-regexp "<sub>") ht))) (and (not (run a "foo")) a)) (automaton::minimize (automaton::empty-automaton)))) t) (defmultitest regexp-automaton.test-8 (automaton-equal (let ((a (regexp-automaton (string-regexp "[a-z]")))) (and (run a "a") (run a "z") (not (run a "A")) a)) (automaton::minimize (automaton::char-range-automaton (char-code #\a) (char-code #\z)))) t) (defmultitest regexp-automaton.test-8a (automaton-equal (let ((a (regexp-automaton (string-regexp "[a]")))) (and (run a "a") (not (run a "A")) a)) (automaton::minimize (automaton::char-automaton (char-code #\a)))) t) (defmultitest regexp-automaton.test-9 (automaton-equal (let ((a (regexp-automaton (string-regexp "[a][b][c]")))) (and (run a "abc") (not (run a "ab")) (not (run a "a")) (not (run a "A")) a)) (automaton::minimize (automaton::string-automaton "abc"))) t) (defmultitest regexp-automaton.test-10 (automaton-equal (let ((a (regexp-automaton (string-regexp "[ab]")))) (and (run a "a") (run a "b") (not (run a "ab")) (not (run a "aa")) (not (run a "A")) a)) (automaton::minimize (automaton::aunion (automaton::char-automaton (char-code #\a)) (automaton::char-automaton (char-code #\b))))) t) (defmultitest regexp-automaton.test-11 (automaton-equal (let ((a (regexp-automaton (string-regexp "[^a-c0-3]")))) (and (run a "d") (not (run a "a")) (not (run a "0")) (run a "4") (not (run a "dd")) (not (run a "00")) a)) (automaton::minimize (automaton::aintersection (automaton::any-char-automaton) (automaton::acomplement (automaton::aunion (automaton::char-range-automaton (char-code #\a) (char-code #\c)) (automaton::char-range-automaton (char-code #\0) (char-code #\3))))))) t) (defmultitest regexp-automaton.test-11a (automaton-equal (let ((a (regexp-automaton (string-regexp "[a^b-c]")))) (and (run a "a") (run a "^") (run a "b") (run a "c") (not (run a "d")) (not (run a "ad")) a)) (automaton::minimize (automaton::aunion (automaton::aunion (automaton::char-automaton (char-code #\a)) (automaton::char-automaton (char-code #\^))) (automaton::char-range-automaton (char-code #\b) (char-code #\c))))) t) (defmultitest regexp-automaton.test-12 (automaton-equal (let ((a (regexp-automaton (string-regexp "~[a-c]")))) (and (run a "d") (not (run a "a")) (not (run a "b")) (not (run a "c")) (run a "dd") (run a "cc") (run a "A") a)) (automaton::minimize (automaton::acomplement (automaton::char-range-automaton (char-code #\a) (char-code #\c))))) t) (defmultitest regexp-automaton.test-13 (automaton-equal (let ((a (regexp-automaton (string-regexp "f?")))) (and (run a "") (run a "f") (not (run a "ff")) (not (run a "F")) a)) (automaton::minimize (automaton::optional (automaton::char-automaton (char-code #\f))))) t) (defmultitest regexp-automaton.test-14 (automaton-equal (let ((a (regexp-automaton (string-regexp "(\"foo\")?")))) (and (run a "") (run a "foo") (not (run a "foofoo")) (not (run a "FOO")) a)) (automaton::minimize (automaton::optional (automaton::string-automaton "foo")))) t) (defmultitest regexp-automaton.test-15 (automaton-equal (let ((a (regexp-automaton (string-regexp "[a-c]*")))) (and (run a "a") (run a "bb") (run a "ccc") (run a "abcabc") (not (run a "d")) (run a "") a)) (automaton::minimize (automaton::repeat (automaton::char-range-automaton (char-code #\a) (char-code #\c))))) t) (defmultitest regexp-automaton.test-16 (automaton-equal (let ((a (regexp-automaton (string-regexp "(\"foo\")+")))) (and (not (run a "")) (run a "foo") (run a "foofoo") (not (run a "FOO")) a)) (automaton::minimize (automaton::repeat-min (automaton::string-automaton "foo") 1))) t) (defmultitest regexp-automaton.test-17 (automaton-equal (let ((a (regexp-automaton (string-regexp "[a-c]{3}")))) (and (run a "abc") (run a "aaa") (not (run a "a")) (not (run a "aaaa")) (not (run a "AAA")) a)) (automaton::minimize (automaton::repeat-minmax (automaton::char-range-automaton (char-code #\a) (char-code #\c)) 3 3))) t) (defmultitest regexp-automaton.test-18 (automaton-equal (let ((a (regexp-automaton (string-regexp "(~c){1,2}")))) (and (run a "aa") (run a "AA") (run a "foofoo") (run a "foo") (not (run a "c")) (run a "cc") (run a "ccc") a)) (automaton::minimize (automaton::repeat-minmax (automaton::acomplement (automaton::char-automaton (char-code #\c))) 1 2))) t) (defmultitest regexp-automaton.test-18a (automaton-equal (let ((a (regexp-automaton (string-regexp "~(c{1,2})")))) (and (run a "aa") (run a "AA") (run a "foofoo") (run a "foo") (not (run a "c")) (not (run a "cc")) (run a "ccc") a)) (automaton::minimize (automaton::acomplement (automaton::repeat-minmax (automaton::char-automaton (char-code #\c)) 1 2)))) t) (defmultitest regexp-automaton.test-19 (automaton-equal (let ((a (regexp-automaton (string-regexp "[a-z]~[0-9]")))) (and (run a "aa") (run a "a") (not (run a "a0")) (not (run a "")) (run a "abc") a)) (automaton::minimize (automaton::aconcatenate (automaton::char-range-automaton (char-code #\a) (char-code #\z)) (automaton::acomplement (automaton::char-range-automaton (char-code #\0) (char-code #\9)))))) t) (defmultitest regexp-automaton.test-20 (automaton-equal (let ((a (regexp-automaton (string-regexp "(ab+)&(a+b)|c")))) (and (run a "ab") (run a "c") (not (run a "abb")) (not (run a "aab")) a)) (automaton::minimize (automaton::aunion (automaton::aintersection (automaton::aconcatenate (automaton::char-automaton (char-code #\a)) (automaton::repeat-min (automaton::char-automaton (char-code #\b)) 1)) (automaton::aconcatenate (automaton::repeat-min (automaton::char-automaton (char-code #\a)) 1) (automaton::char-automaton (char-code #\b)))) (automaton::char-automaton (char-code #\c))))) t) (defmultitest regexp-automaton.test-21 (automaton-equal (let ((a (regexp-automaton (string-regexp "a\"b\"+c")))) (and (run a "abc") (run a "abbc") (not (run a "ab")) (not (run a "ac")) a)) (automaton::minimize (automaton::aconcatenate (automaton::char-automaton (char-code #\a)) (automaton::aconcatenate (automaton::repeat-min (automaton::string-automaton "b") 1) (automaton::char-automaton (char-code #\c)))))) t) (defmultitest run.test-1 (let ((a (regexp-automaton (string-regexp "[Cc]limacs")))) (and (run a "climacs") (run a "Climacs") (not (run a "Klimaks")) (not (run a "climac")) (not (run a "climax")))) t) (defmultitest run-to-first-match.test-1 (let ((a (regexp-automaton (string-regexp "[a-z]+")))) (and (= (run-to-first-match a "abc") 1) (eq (run-to-first-match a "ABC") nil) (eq (run-to-first-match a "000abc") nil) (= (run-to-first-match a "a") 1) (eq (run-to-first-match a "") nil))) t) (defmultitest run-to-first-match.test-2 (let ((a (regexp-automaton (string-regexp "(ab)+")))) (and (= (run-to-first-match a "abab") 2) (= (run-to-first-match a "ababac") 2))) t) (defmultitest run-to-first-unmatch.test-1 (let ((a (regexp-automaton (string-regexp "[a-z]+")))) (and (= (run-to-first-unmatch a "abc") 3) (eq (run-to-first-unmatch a "ABC") nil) (eq (run-to-first-unmatch a "000abc") nil) (= (run-to-first-unmatch a "a") 1) (eq (run-to-first-unmatch a "") nil) (= (run-to-first-unmatch a "abc9d") 3))) t) (defmultitest run-to-first-unmatch.test-2 (let ((a (regexp-automaton (string-regexp "(ab)+")))) (and (= (run-to-first-unmatch a "abab") 2) (= (run-to-first-unmatch a "ababac") 2))) t)
11,136
Common Lisp
.lisp
292
33.907534
80
0.620259
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
5925ad1dc301082ad8d0a02a79814f3215a8f99f24c015fe9c9b8183bfdde02e
13,623
[ -1 ]
13,624
eqv-hash.lisp
amb007_cl-automaton/eqv-hash.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; ;;; A naive attempt at implementing the protocol proposed by Robert ;;; Strandh (see eqv-hash.txt). (in-package :eqv-hash) (defgeneric eqv (object1 object2 situation)) (defgeneric hash (object situation)) (defclass key-situation () ()) (defclass builtin-key-situation (key-situation) ()) (defclass eq-key-situation (builtin-key-situation) ()) (defparameter +eq-key-situation+ (make-instance 'eq-key-situation)) (defclass eql-key-situation (builtin-key-situation) ()) (defparameter +eql-key-situation+ (make-instance 'eql-key-situation)) (defclass equal-key-situation (builtin-key-situation) ()) (defparameter +equal-key-situation+ (make-instance 'equal-key-situation)) (defclass equalp-key-situation (builtin-key-situation) ()) (defparameter +equalp-key-situation+ (make-instance 'equalp-key-situation)) (defclass case-sensitive-key-situation (builtin-key-situation) ()) (defparameter +case-sensitive-key-situation+ (make-instance 'case-sensitive-key-situation)) (defclass case-insensitive-key-situation (builtin-key-situation) ()) (defparameter +case-insensitive-key-situation+ (make-instance 'case-insensitive-key-situation)) (defclass generalized-hash-table () ((ht :initform (make-hash-table) :reader ht) (cnt :initform 0 :accessor cnt) (situation :initarg :situation :reader situation))) (defun make-generalized-hash-table (situation) (make-instance 'generalized-hash-table :situation situation)) (defun htref (table key) (let* ((s (situation table)) (pair (assoc key (gethash (hash key s) (ht table)) :test #'(lambda (o1 o2) (eqv o1 o2 s))))) (if pair (values (cdr pair) t) (values nil nil)))) (defun (setf htref) (object table key) (let* ((ht (ht table)) (s (situation table)) (h (hash key s)) (p (assoc key (gethash h ht) :test #'(lambda (o1 o2) (eqv o1 o2 s))))) (if p (progn (rplaca p key) (rplacd p object)) (progn (push (cons key object) (gethash h ht)) (incf (cnt table))))) object) (defun htadd (table key) (setf (htref table key) t)) (defun htremove (table key) (let* ((ht (ht table)) (s (situation table)) (h (hash key s)) (b (remove key (gethash h ht) :key #'car :test #'(lambda (o1 o2) (eqv o1 o2 s))))) (if (eq b (gethash h ht)) nil (progn (decf (cnt table)) (if b (setf (gethash h ht) b) (remhash h ht)))))) (defun htpresent (table key) (multiple-value-bind (v v-p) (htref table key) (declare (ignore v)) v-p)) (defmacro with-ht ((key value) table &body body) (let ((bucket (gensym "BUCKET"))) `(loop for ,bucket being the hash-value of (ht ,table) do (loop for (,key . ,value) in ,bucket do ,@body)))) (defmacro with-ht-collect ((key value) table &body body) (let ((bucket (gensym "BUCKET"))) `(loop for ,bucket being the hash-value of (ht ,table) nconc (loop for (,key . ,value) in ,bucket collect ,@body)))) ;; By Bruno Haible: ;; (let ((hashcode-table ;; (make-hash-table :test #'eq ;; :key-type 't :value-type 'fixnum ;; :weak :key))) ;; (defmethod hash (obj (situation (eql +eq-key-situation))) ;; (or (gethash obj hashcode-table) ;; (setf (gethash obj hashcode-table) (random (+ most-positive-fixnum ;; 1))))))
3,349
Common Lisp
.lisp
89
34.550562
75
0.674296
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
cbee10102d0942869b0c3563521a149294b0faf76929f738080351e090f7716b
13,624
[ -1 ]
13,625
automaton-test-package.lisp
amb007_cl-automaton/automaton-test-package.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (defpackage #:eqv-hash-user (:use :cl :rtest #:eqv-hash)) (defpackage #:automaton-user (:use :cl :rtest #:automaton #:eqv-hash))
229
Common Lisp
.lisp
8
26.875
62
0.633484
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
c862a63c7f25c3b10e865de5895912c0d4d72ece52b471ca32edfc64f7baa929
13,625
[ -1 ]
13,626
state-and-transition.lisp
amb007_cl-automaton/state-and-transition.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; ;;; Derived from dk.brics.automaton v1.8.1, (c) 2001-2005 by Anders Møller (in-package :automaton) (defconstant +min-char-code+ 0) (defconstant +max-char-code+ (1- char-code-limit)) (deftype char-code-type () `(integer ,+min-char-code+ ,+max-char-code+)) (defclass state () ((accept :initform nil :accessor accept :type boolean) (transitions :accessor transitions :type generalized-hash-table) (num :initform 0 :accessor num :type fixnum) (id :accessor id :type fixnum) (next-id :allocation :class :initform -1 :accessor next-id :type fixnum))) (declaim (special *state-ht*)) (defun state-equal (s1 s2) ; for testing, assuming minimization (multiple-value-bind (se se-p) (gethash (cons s1 s2) *state-ht*) ; TODO: consider (cons s2 s1), too (if se-p se (setf (gethash (cons s1 s2) *state-ht*) t ; bound recursion temporarily (gethash (cons s1 s2) *state-ht*) (and (eq (accept s1) (accept s2)) (transitions-equal (transitions s1) (transitions s2))))))) (declaim (special *to-first*)) (defun transitions-equal (ts1 ts2) ; for testing, assuming minimization (let* ((*to-first* nil) (tss1 (sort (with-ht-collect (t1 nil) ts1 t1) #'transition<)) (tss2 (sort (with-ht-collect (t2 nil) ts2 t2) #'transition<))) (flet ((%transition-equal (t1 t2) (with-slots ((minc1 minc) (maxc1 maxc) (to1 to)) t1 (with-slots ((minc2 minc) (maxc2 maxc) (to2 to)) t2 (and (= minc1 minc2) (= maxc1 maxc2) (state-equal to1 to2)))))) (and (= (length tss1) (length tss2)) (loop for t1 in tss1 and t2 in tss2 always (%transition-equal t1 t2)))))) (defclass state-pair () ((s :initarg :s :accessor s :type (or null state)) (s1 :initarg :s1 :accessor s1 :type state) (s2 :initarg :s2 :accessor s2 :type state))) (defclass transition () ((minc :initarg :minc :accessor minc :type char-code-type) (maxc :initarg :maxc :accessor maxc :type char-code-type) (to :initarg :to :accessor to :type state))) (defclass state-set () ((ht :initform (make-hash-table) :initarg :ht :accessor ht :type hash-table))) (defmethod initialize-instance :after ((s state) &rest initargs) (declare (ignorable initargs)) (with-slots (transitions id next-id) s (setf transitions (make-generalized-hash-table +equalp-key-situation+) id (incf next-id)))) (defmethod initialize-instance :after ((tr transition) &rest initargs) (declare (ignorable initargs)) (with-slots (minc maxc to) tr (cond ((not minc) (assert maxc nil "MINC or MAXC required") (setf minc maxc)) ((not maxc) (assert minc nil "MINC or MAXC required") (setf maxc minc)) ((> minc maxc) (rotatef minc maxc))) (assert to nil "TO required"))) (defmethod eqv ((sp1 state-pair) (sp2 state-pair) (s (eql +equalp-key-situation+))) (and (eq (s1 sp1) (s1 sp2)) (eq (s2 sp1) (s2 sp2)))) (defmethod hash ((sp state-pair) (s (eql +equalp-key-situation+))) "Returns the hash code for state-pair SP." (the fixnum (mod (+ (sxhash (s1 sp)) (sxhash (s2 sp))) most-positive-fixnum))) (defmethod eqv ((tr1 transition) (tr2 transition) (s (eql +equalp-key-situation+))) "Returns true if transitions TR1 and TR2 have equal interval and same (eq) destination state." (with-slots ((minc1 minc) (maxc1 maxc) (to1 to)) tr1 (with-slots ((minc2 minc) (maxc2 maxc) (to2 to)) tr2 (and (= minc1 minc2) (= maxc1 maxc2) (eq to1 to2))))) (defmethod hash ((tr transition) (s (eql +equalp-key-situation+))) "Returns the hash code for transition TR." (with-slots (minc maxc) tr (the fixnum (mod (+ (* 2 minc) (* 3 maxc)) most-positive-fixnum)))) (defmethod clone ((tr transition)) "Returns a clone of TR." (with-slots (minc maxc to) tr (make-instance 'transition :minc minc :maxc maxc :to to))) (defmethod eqv ((ss1 state-set) (ss2 state-set) (s (eql +equalp-key-situation+))) "Returns true if state-set objects SS1 and SS2 contain the same (eql) state objects." (and (= (hash-table-count (ht ss1)) (hash-table-count (ht ss2))) (loop for st being the hash-key of (ht ss1) always (gethash st (ht ss2))))) (defmethod hash ((ss state-set) (s (eql +equalp-key-situation+))) "Returns the hash code for state-set SS." (the fixnum (mod (loop for st being the hash-key of (ht ss) sum (sxhash st)) most-positive-fixnum))) (defvar *do-not-escape* t) ; nil may be useful in Slime (defun escaped-char (c) (if (or *do-not-escape* (and (<= #x21 c #x7e) (/= c (char-code #\\)))) (code-char c) (format nil "\\u~4,'0O" c))) (defmethod print-object ((st state) s) (with-slots (accept transitions num) st (format s "~@<state ~A [~A]: ~2I~_~@<~{~W~^ ~_~}~:>~:>" num (if accept "accept" "reject") (with-ht-collect (tr nil) transitions tr))) st) (defmethod print-object ((tr transition) s) (with-slots (minc maxc to) tr (format s "~@<~A~:[~*~;-~A~] -> ~A~:>" (escaped-char minc) (/= minc maxc) (escaped-char maxc) (num to)) tr)) (defun transition< (tr1 tr2) "Returns true if TR1 is strictly less than TR2. If *TO-FIRST* special variable is bound to true, the values of the destination states' NUM slots are compared first, followed by the intervals comparison. The intervals comparison is done as follows: the lower interval bounds are compared first, followed by reversed upper interval bounds comparisons. If *TO-FIRST* is bound to nil, the interval comparison is done first, followed by the NUM comparisons." (with-slots ((minc1 minc) (maxc1 maxc) (to1 to)) tr1 (with-slots ((minc2 minc) (maxc2 maxc) (to2 to)) tr2 (let ((to< (< (num to1) (num to2))) (to= (= (num to1) (num to2))) (min-rmax< (or (< minc1 minc2) (and (= minc1 minc2) (> maxc1 maxc2)))) (min-rmax= (and (= minc1 minc2) (= maxc1 maxc2)))) (if *to-first* (or to< (and to= min-rmax<)) (or min-rmax< (and min-rmax= to<))))))) (defun reset-transitions (s) (setf (transitions s) (make-generalized-hash-table +equalp-key-situation+))) (defun sstep (s c) "Returns a state reachable from S, given the input character code C." (with-ht (tr nil) (transitions s) (when (<= (minc tr) (char-code c) (maxc tr)) (return-from sstep (to tr))))) (defun add-epsilon (s to) "Adds transitions of state TO to state S. Also, if TO accepts, so does S." (when (accept to) (setf (accept s) t)) (let ((s-table (transitions s))) (with-ht (tr nil) (transitions to) (htadd s-table tr)))) (defun sorted-transition-vector (s *to-first*) "Returns a vector of all transitions of S, sorted using TRANSITION< and *TO-FIRST*." (let ((v (make-array `(,(cnt (transitions s))) :element-type '(or null transition))) (i -1)) (sort (progn (with-ht (tr nil) (transitions s) (setf (aref v (incf i)) tr)) v) #'transition<))) (defun sorted-transition-list (s *to-first*) "Returns a list of all transitions of S, sorted using TRANSITION< and *TO-FIRST*." (sort (with-ht-collect (tr nil) (transitions s) tr) #'transition<))
7,180
Common Lisp
.lisp
173
37.635838
80
0.65616
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
dfb13d5f56d7690fad90027e22b10ca840776871e24d0453cdf13eab99284167
13,626
[ -1 ]
13,627
regexp-test.lisp
amb007_cl-automaton/regexp-test.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package :automaton-user) (deftest string-regexp.test-1 (regexp-equal (string-regexp "#") (automaton::make-regexp :empty)) t) (deftest string-regexp.test-2 (regexp-equal (string-regexp "foo") (make-instance 'automaton::regexp :kind :string :s "foo")) t) (deftest string-regexp.test-2a (regexp-equal (string-regexp "\"foo\"") (make-instance 'automaton::regexp :kind :string :s "foo")) t) (deftest string-regexp.test-2b (regexp-equal (string-regexp "()") (make-instance 'automaton::regexp :kind :string :s "")) t) (deftest string-regexp.test-3 (regexp-equal (string-regexp "c") (make-instance 'automaton::regexp :kind :char :c #\c)) t) (deftest string-regexp.test-3a (regexp-equal (string-regexp "\c") (make-instance 'automaton::regexp :kind :char :c #\c)) t) (deftest string-regexp.test-3b (regexp-equal (string-regexp "\\c") (make-instance 'automaton::regexp :kind :char :c #\c)) t) (deftest string-regexp.test-4 (regexp-equal (string-regexp ".") (automaton::make-regexp :anychar)) t) (deftest string-regexp.test-5 (regexp-equal (string-regexp "@") (automaton::make-regexp :anystring)) t) (deftest string-regexp.test-6 (regexp-equal (string-regexp "<11-15>") (make-instance 'automaton::regexp :kind :interval :minr 11 :maxr 15 :digits 2)) t) (deftest string-regexp.test-6a (regexp-equal (string-regexp "<11-115>") (make-instance 'automaton::regexp :kind :interval :minr 11 :maxr 115 :digits 0)) t) (deftest string-regexp.test-6b (regexp-equal (string-regexp "<115-11>") (make-instance 'automaton::regexp :kind :interval :minr 11 :maxr 115 :digits 0)) t) (deftest string-regexp.test-7 (regexp-equal (string-regexp "<sub>") (make-instance 'automaton::regexp :kind :automaton :s "sub")) t) (deftest string-regexp.test-8 (regexp-equal (string-regexp "[a-z]") (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\z)) t) (deftest string-regexp.test-8a (regexp-equal (string-regexp "[a]") (make-instance 'automaton::regexp :kind :char :c #\a)) t) (deftest string-regexp.test-9 (regexp-equal (string-regexp "[a][b][c]") (make-instance 'automaton::regexp :kind :string :s "abc")) t) (deftest string-regexp.test-10 (regexp-equal (string-regexp "[ab]") (automaton::make-regexp :union (make-instance 'automaton::regexp :kind :char :c #\a) (make-instance 'automaton::regexp :kind :char :c #\b))) t) (deftest string-regexp.test-11 (regexp-equal (string-regexp "[^a-c0-3]") (automaton::make-regexp :intersection (automaton::make-regexp :anychar) (automaton::make-regexp :complement (automaton::make-regexp :union (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\c) (make-instance 'automaton::regexp :kind :char-range :from #\0 :to #\3))))) t) (deftest string-regexp.test-11a (regexp-equal (string-regexp "[a^b-c]") (automaton::make-regexp :union (automaton::make-regexp :union (make-instance 'automaton::regexp :kind :char :c #\a) (make-instance 'automaton::regexp :kind :char :c #\^)) (make-instance 'automaton::regexp :kind :char-range :from #\b :to #\c))) t) (deftest string-regexp.test-12 (regexp-equal (string-regexp "~[a-c]") (automaton::make-regexp :complement (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\c))) t) (deftest string-regexp.test-13 (regexp-equal (string-regexp "f?") (automaton::make-regexp :optional (make-instance 'automaton::regexp :kind :char :c #\f))) t) (deftest string-regexp.test-14 (regexp-equal (string-regexp "(\"foo\")?") (automaton::make-regexp :optional (make-instance 'automaton::regexp :kind :string :s "foo"))) t) (deftest string-regexp.test-15 (regexp-equal (string-regexp "[a-c]*") (automaton::make-regexp :repeat (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\c))) t) (deftest string-regexp.test-16 (regexp-equal (string-regexp "(\"foo\")+") (make-instance 'automaton::regexp :kind :repeat-min :exp1 (make-instance 'automaton::regexp :kind :string :s "foo") :minr 1)) t) (deftest string-regexp.test-17 (regexp-equal (string-regexp "[a-c]{3}") (make-instance 'automaton::regexp :kind :repeat-minmax :exp1 (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\c) :minr 3 :maxr 3)) t) (deftest string-regexp.test-18 (regexp-equal (string-regexp "(~c){1,2}") (make-instance 'automaton::regexp :kind :repeat-minmax :exp1 (automaton::make-regexp :complement (make-instance 'automaton::regexp :kind :char :c #\c)) :minr 1 :maxr 2)) t) (deftest string-regexp.test-19 (regexp-equal (string-regexp "[a-z]~[0-9]") (automaton::make-regexp :concatenation (make-instance 'automaton::regexp :kind :char-range :from #\a :to #\z) (automaton::make-regexp :complement (make-instance 'automaton::regexp :kind :char-range :from #\0 :to #\9)))) t) (deftest string-regexp.test-20 (regexp-equal (string-regexp "(ab+)&(a+b)|c") (automaton::make-regexp :union (automaton::make-regexp :intersection (automaton::make-regexp :concatenation (make-instance 'automaton::regexp :kind :char :c #\a) (make-instance 'automaton::regexp :kind :repeat-min :exp1 (make-instance 'automaton::regexp :kind :char :c #\b) :minr 1)) (automaton::make-regexp :concatenation (make-instance 'automaton::regexp :kind :repeat-min :exp1 (make-instance 'automaton::regexp :kind :char :c #\a) :minr 1) (make-instance 'automaton::regexp :kind :char :c #\b))) (make-instance 'automaton::regexp :kind :char :c #\c))) t) (deftest string-regexp.test-21 (regexp-equal (string-regexp "a\"b\"+c") (automaton::make-regexp :concatenation (make-instance 'automaton::regexp :kind :char :c #\a) (automaton::make-regexp :concatenation (make-instance 'automaton::regexp :kind :repeat-min :exp1 (make-instance 'automaton::regexp :kind :string :s "b") :minr 1) (make-instance 'automaton::regexp :kind :char :c #\c)))) t)
6,432
Common Lisp
.lisp
220
25.195455
74
0.658418
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
4e66040d3e8ca4c9ddf9fd5e9df8c471073963a109723afb8a838b17032f565d
13,627
[ -1 ]
13,628
automaton.lisp
amb007_cl-automaton/automaton.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; ;;; Derived from dk.brics.automaton v1.8.1, (c) 2001-2005 by Anders Møller ;;; - Functionality not used by the regular expression engine and not tested ;;; has been omitted from this initial release. ;;; - Some comments have been copied verbatim from the original code. (in-package :automaton) (deftype minimization () '(member huffman brzozowski hopcroft)) (defvar *minimization* 'hopcroft) (defvar *minimize-always* t) ;;; Class invariants: ;;; - An automaton is either represented explicitly (with state and ;;; transition objects) or with a singleton string in case the ;;; automaton accepts exactly one string. ;;; - Automata are always reduced (see areduce) and have no transitions ;;; to dead states (see remove-dead-transitions). ;;; - If an automaton is nondeterministic, then deterministic returns nil ;;; (but the converse is not required). ;;; Implicitly, all states and transitions of an automaton are reachable ;;; from its initial state. ;;; If the states or transitions are manipulated manually, the ;;; restore-invariant and (setf deterministic) methods should be used ;;; afterwards to restore certain representation invariants that are ;;; assumed by the built-in automata operations. ;;; If minimize-always is true, minimize will automatically be invoked ;;; after every operation that otherwise may produce a non-minimal automaton ;;; (usually, an intermediate result). (defclass automaton () ((minimization :initform *minimization* :accessor minimization :type minimization) (initial :initform (make-instance 'state) :accessor initial :type state) (deterministic :initform t :accessor deterministic :type boolean) (info :initform nil :accessor info) (hash-code :initform 0 :accessor hash-code :type fixnum) (singleton :initform nil :accessor singleton :type (or null string)) (minimize-always :initform *minimize-always* :accessor minimize-always :type boolean))) (defun restore-invariant (a) (remove-dead-transitions a) (setf (hash-code a) 0)) (declaim (special *state-ht*)) (defun automaton-equal (a1 a2) ; for testing, assumes minimization (and (eq (minimization a1) (minimization a2)) (let ((*state-ht* (make-hash-table :test #'equal))) (state-equal (initial a1) (initial a2))) (eq (deterministic a1) (deterministic a2)) (eqv a1 a2 +equalp-key-situation+) (eq (minimize-always a1) (minimize-always a2)))) (defclass int-pair () ; TODO: replace with a simple cons ((n1 :initarg :n1 :reader n1 :type fixnum) (n2 :initarg :n2 :reader n2 :type fixnum))) (defclass state-list-node () ((q :initform nil :initarg :q :accessor q :type (or null state)) (succ :initform nil :accessor succ :type (or null state-list-node)) (pred :initform nil :accessor pred :type (or null state-list-node)) (sl :initform nil :initarg :sl :accessor sl :type (or null state-list)))) (defclass state-list () ((size :initform 0 :accessor size :type fixnum) (fst :initform nil :accessor fst :type (or null state-list-node)) (lst :initform nil :accessor lst :type (or null state-list-node)))) (defun check-minimize-always (a) (if (minimize-always a) (minimize a) a)) (defun states (a) "Returns a hash table containing the set of states reachable from the initial state of A." (expand-singleton a) (let ((visited (make-hash-table)) (worklist nil)) (setf (gethash (initial a) visited) t) (push (initial a) worklist) (loop while worklist for s = (pop worklist) do (with-ht (tr nil) (transitions s) (let ((s2 (to tr))) (unless (gethash s2 visited) (setf (gethash s2 visited) t) (push s2 worklist))))) visited)) (defun accepting-states (a) "Returns a hash table containing the set of accepting states reachable from the initial state of A." (let ((accepting (make-hash-table))) (loop for s being the hash-key of (states a) when (accept s) do (setf (gethash s accepting) t)) accepting)) (defun set-state-nums (states) "Renumerates, by assigning consecutive numbers to the NUM slot of states being the keys of STATES hash table, and finally returns STATES." (let ((i -1)) (loop for s being the hash-key of states do (setf (num s) (incf i)))) states) (defun totalize (a) "Adds transitions to an explicit crash state, added to A, to ensure that the transition function is total. Finally, returns A." (let* ((s (make-instance 'state)) (tr (make-instance 'transition :minc +min-char-code+ :maxc +max-char-code+ :to s))) (htadd (transitions s) tr) (loop for p being the hash-key of (states a) and maxi = +min-char-code+ do (loop for tr in (sorted-transition-list p nil) do (with-slots (minc maxc) tr (when (> minc maxi) (htadd (transitions p) (make-instance 'transition :minc maxi :maxc (1- minc) :to s))) (when (> (1+ maxc) maxi) (setq maxi (1+ maxc))))) (when (<= maxi +max-char-code+) (htadd (transitions p) (make-instance 'transition :minc maxi :maxc +max-char-code+ :to s)))) a)) (defun areduce (a) "Reduces automaton A by combining overlapping and adjacent edge intervals with the same destination. Finally, returns A." (if (singleton a) a (let ((states (states a))) (set-state-nums states) (loop for s being the hash-key of states do (let ((st (sorted-transition-list s t))) (reset-transitions s) (let ((p nil) (min -1) (max -1)) (loop for tr in st if (eq p (to tr)) do (with-slots (minc maxc) tr (if (<= minc (1+ max)) (when (> maxc max) (setq max maxc)) (progn (when p (htadd (transitions s) (make-instance 'transition :minc min :maxc max :to p))) (setq min minc max maxc)))) else do (with-slots (minc maxc to) tr (when p (htadd (transitions s) (make-instance 'transition :minc min :maxc max :to p))) (setq p to min minc max maxc))) (when p (htadd (transitions s) (make-instance 'transition :minc min :maxc max :to p)))))) a))) (defun start-points (a) "Returns a sorted vector of all interval start points (character codes)." (let ((pset (make-hash-table))) (loop for s being the hash-key of (states a) do (setf (gethash +min-char-code+ pset) t) (with-ht (tr nil) (transitions s) (with-slots (minc maxc) tr (setf (gethash minc pset) t) (when (< maxc +max-char-code+) (setf (gethash (1+ maxc) pset) t))))) (let ((pa (make-array (hash-table-count pset) :element-type 'char-code-type))) (loop for p being the hash-key of pset and n from 0 do (setf (aref pa n) p) finally (return (sort pa #'<)))))) (defun live-states2 (a states) "Returns the set of live states of A that are in STATES hash table. A state is live if an accepting state is reachable from it." (let ((map (make-hash-table))) (loop for s being the hash-key of states do (setf (gethash s map) (make-hash-table))) (loop for s being the hash-key of states do (with-ht (tr nil) (transitions s) (setf (gethash s (gethash (to tr) map)) t))) (let* ((live (accepting-states a)) (worklist (loop for s being the hash-key of live collect s))) (loop while worklist for s = (pop worklist) do (loop for p being the hash-key of (gethash s map) unless (gethash p live) do (setf (gethash p live) t) (push p worklist))) live))) (defun remove-dead-transitions (a) "Returns reduced A with transitions to dead states removed. A state is dead if no accepting state is reachable from it." (if (singleton a) nil (let* ((states (states a)) (live (live-states2 a states))) (loop for s being the hash-key of states do (let ((st (transitions s))) (reset-transitions s) (with-ht (tr nil) st (when (gethash (to tr) live) (htadd (transitions s) tr))))) (areduce a)))) (defun sorted-transitions (states) "Renumerates each state in STATES hash table, and returns a vector of sorted vectors of transitions for each state, ordered by the NUM slot." (set-state-nums states) (let ((transitions (make-array (hash-table-count states)))) (loop for s being the hash-key of states do (setf (aref transitions (num s)) (sorted-transition-vector s nil))) transitions)) (defun empty-automaton () "Returns a new determinsitic automaton with the empty language." (let ((a (make-instance 'automaton)) (s (make-instance 'state))) (setf (initial a) s (deterministic a) t) a)) (defun empty-string-automaton () "Returns a new deterministic automaton that accepts only the empty string." (let ((a (make-instance 'automaton))) (setf (singleton a) "" (deterministic a) t) a)) (defun any-string-automaton () "Returns a new deterministic automaton that accepts any string." (let ((a (make-instance 'automaton)) (s (make-instance 'state))) (setf (initial a) s (accept s) t (deterministic a) t) (htadd (transitions s) (make-instance 'transition :minc +min-char-code+ :maxc +max-char-code+ :to s)) a)) (defun any-char-automaton () "Returns a new deterministic automaton that accepts any single character." (char-range-automaton +min-char-code+ +max-char-code+)) (defun char-automaton (c) "Returns a new deterministic automaton that accepts a single character whose code is C." (char-range-automaton c c)) (defun char-range-automaton (cmin cmax) "Returns a new deterministic automaton that accepts a single character whose code is in closed interval [CMIN, CMAX]." (let ((a (make-instance 'automaton)) (s1 (make-instance 'state)) (s2 (make-instance 'state))) (setf (initial a) s1 (accept s2) t (deterministic a) t) (when (<= cmin cmax) (htadd (transitions s1) (make-instance 'transition :minc cmin :maxc cmax :to s2))) a)) (defun char-set-automaton (str) "Returns a new deterministic automaton that accepts a single character in set STR." (let ((a (make-instance 'automaton)) (s1 (make-instance 'state)) (s2 (make-instance 'state))) (setf (initial a) s1 (accept s2) t (deterministic a) t) (loop with t-table = (transitions s1) for c across str do (htadd t-table (make-instance 'transition :minc (char-code c) :maxc (char-code c) :to s2))) (areduce a))) (defun any-of-right-length-subautomaton (str n) "Returns a new sub-automaton (root of a state graph) accepting non-negative (decimal) integers of length of (subseq STR N)." (let ((s (make-instance 'state))) (if (= (length str) n) (setf (accept s) t) (htadd (transitions s) (make-instance 'transition :minc (char-code #\0) :maxc (char-code #\9) :to (any-of-right-length-subautomaton str (1+ n))))) s)) (defun at-least-subautomaton (str n initials zeros) "Returns a new sub-automaton (root of a state graph) accepting non-negative (decimal) integers of value at least the one represented by (subseq STR N), and of length of (subseq STR N)." (let ((s (make-instance 'state))) (if (= (length str) n) (setf (accept s) t) (let ((c (elt str n))) (when zeros (push s (car initials))) (htadd (transitions s) (make-instance 'transition :minc (char-code c) :maxc (char-code c) :to (at-least-subautomaton str (1+ n) initials (and zeros (char= c #\0))))) (when (char< c #\9) (htadd (transitions s) (make-instance 'transition :minc (1+ (char-code c)) :maxc (char-code #\9) :to (any-of-right-length-subautomaton str (1+ n))))))) s)) (defun at-most-subautomaton (str n) "Returns a new sub-automaton (root of a state graph) accepting non-negative (decimal) integers of value at most the one represented by (subseq STR N), and of length of (subseq STR N)." (let ((s (make-instance 'state))) (if (= (length str) n) (setf (accept s) t) (let ((c (elt str n))) (htadd (transitions s) (make-instance 'transition :minc (char-code c) :maxc (char-code c) :to (at-most-subautomaton str (1+ n)))) (when (char> c #\0) (htadd (transitions s) (make-instance 'transition :minc (char-code #\0) :maxc (1- (char-code c)) :to (any-of-right-length-subautomaton str (1+ n))))))) s)) (defun between-subautomaton (str1 str2 n initials zeros) "Returns a new sub-automaton (root of a state graph) accepting non-negative (decimal) integers of value between the one represented by (subseq STR1 N) and (subseq STR2 N), inclusive, and of length of \(subseq STR1 N) = (subseq STR2 N)." (let ((s (make-instance 'state))) (if (= (length str1) n) (setf (accept s) t) (let ((c1 (elt str1 n)) (c2 (elt str2 n))) (when zeros (push s (car initials))) (if (char= c1 c2) (htadd (transitions s) (make-instance 'transition :minc (char-code c1) :maxc (char-code c1) :to (between-subautomaton str1 str2 (1+ n) initials (and zeros (char= c1 #\0))))) (progn (htadd (transitions s) (make-instance 'transition :minc (char-code c1) :maxc (char-code c1) :to (at-least-subautomaton str1 (1+ n) initials (and zeros (char= c1 #\0))))) (htadd (transitions s) (make-instance 'transition :minc (char-code c2) :maxc (char-code c2) :to (at-most-subautomaton str2 (1+ n)))) (when (< (1+ (char-code c1)) (char-code c2)) (htadd (transitions s) (make-instance 'transition :minc (1+ (char-code c1)) :maxc (1- (char-code c2)) :to (any-of-right-length-subautomaton str1 (1+ n))))))))) s)) (defun interval-automaton (min max digits) "Returns a new automaton that accepts strings representing non-negative (decimal) integers in interval [MIN, MAX]. If DIGITS > 0, uses the fixed number of digits (strings must be prefixed by 0s to obtain the right length). Otherwise, the number of digits is not fixed. If MIN > MAX or if the numbers in the interval cannot be expressed with the given fixed number of digits, an error is signaled." (flet ((%num-digits (n) (if (= n 0) 1 (1+ (floor (log n 10)))))) (assert (and (<= 0 min max) (or (<= digits 0) (<= (%num-digits max) digits))) () "MIN and MAX not expressible with the same number of digits") (let* ((a (make-instance 'automaton)) (d (if (> digits 0) digits (%num-digits max))) (str1 (format nil "~V,'0D" d min)) (str2 (format nil "~V,'0D" d max)) (initials (cons nil nil))) (setf (initial a) (between-subautomaton str1 str2 0 initials (<= digits 0))) (if (<= digits 0) (let ((pairs nil)) (loop for p in (car initials) unless (eq (initial a) p) do (push (make-instance 'state-pair :s1 (initial a) :s2 p) pairs)) (add-epsilons a pairs) (htadd (transitions (initial a)) (make-instance 'transition :minc (char-code #\0) :maxc (char-code #\0) :to (initial a))) (setf (deterministic a) nil)) (setf (deterministic a) t)) (check-minimize-always a)))) (defun expand-singleton (a) "Expands the singleton representation of A into the regular representation, and returns A." (with-slots ((st singleton)) a (when st (let ((p (make-instance 'state))) (setf (initial a) p) (loop for c across st do (let ((q (make-instance 'state))) (htadd (transitions p) (make-instance 'transition :minc (char-code c) :maxc (char-code c) :to q)) (setq p q))) (setf (accept p) t (deterministic a) t st nil)))) a) (defun string-automaton (str) "Returns a new deterministic automaton that accepts the single given string STR." (let ((a (make-instance 'automaton))) (setf (singleton a) str (deterministic a) t) a)) (defun aconcatenate (a1 a2) "Returns a new automaton that accepts the concatenation of the languages of A1 and A2. Complexity: linear in the number of states." (if (and (singleton a1) (singleton a2)) (string-automaton (concatenate 'string (singleton a1) (singleton a2))) (progn (setf a1 (clone-expanded a1) a2 (clone-expanded a2)) (loop for s being the hash-key of (accepting-states a1) do (setf (accept s) nil) (add-epsilon s (initial a2))) (setf (deterministic a1) nil) (check-minimize-always a1)))) (defun aconcatenate-many (l) "Returns a new automaton that accepts the concatenation of the languages of automata in list L, respecting the order. Complexity: linear in the total number of states." (if l (let* ((a1 (clone-expanded (car l))) (ac1 (accepting-states a1))) (loop for a2 in (cdr l) do (let* ((a2 (clone-expanded a2)) (ac2 (accepting-states a2))) (loop for s being the hash-key of ac1 do (setf (accept s) nil) (add-epsilon s (initial a2)) (when (accept s) (setf (gethash s ac2) t))) (setq ac1 ac2))) (setf (deterministic a1) nil) (check-minimize-always a1)) (empty-string-automaton))) (defun optional (a) "Returns a new automaton that accepts the union of the empty string and the language of A. Complexity: linear in the number of states." (let ((a (clone-expanded a)) (s (make-instance 'state))) (add-epsilon s (initial a)) (setf (accept s) t (initial a) s (deterministic a) nil) (check-minimize-always a))) (defun repeat (a) "Returns a new automaton that accepts the Kleene star (zero or more concatenated repetitions) of the language of A. Complexity: linear in the number of states." (let ((a (clone-expanded a)) (s (make-instance 'state))) (setf (accept s) t) (add-epsilon s (initial a)) (loop for p being the hash-key of (accepting-states a) do (add-epsilon p s)) (setf (initial a) s (deterministic a) nil) (check-minimize-always a))) (defun repeat-min (a min) "Returns a new automaton that accepts MIN or more concatenated repetitions of the language of A." (let ((a2 (repeat a))) (loop while (> min 0) do (setq a2 (aconcatenate a a2) min (1- min))) a2)) (defun repeat-minmax (a min max) "Returns a new automaton that accepts a number, from [MIN, MAX], of concatenated repetitions of the language of A. If MIN > MAX, the empty automaton is returned." (expand-singleton a) (when (> min max) (return-from repeat-minmax (empty-automaton))) (decf max min) (let ((a2 (cond ((= min 0) (empty-string-automaton)) ((= min 1) (clone a)) (t (loop with tmp = a while (> (decf min) 0) do (setq tmp (aconcatenate a tmp)) finally (return tmp)))))) (when (= max 0) (return-from repeat-minmax a2)) (let ((a3 (clone a))) (loop while (> (decf max) 0) do (let ((a4 (clone a))) (loop for p being the hash-key of (accepting-states a4) do (add-epsilon p (initial a3))) (setq a3 a4))) (loop for p being the hash-key of (accepting-states a2) do (add-epsilon p (initial a3))) (setf (deterministic a2) nil) (check-minimize-always a2)))) (defun acomplement (a) "Returns a new deterministic" (let ((a (clone-expanded a))) (determinize a) (totalize a) (loop for p being the hash-key of (states a) do (setf (accept p) (not (accept p)))) (remove-dead-transitions a) (check-minimize-always a))) (defun aintersection (a1 a2) "Returns a new deterministic automaton that accepts the intersection of the languages of A and A2. As a side-effect, both A1 and A2 are determinized if not already deterministic. Complexity: quadratic in the number of states (when deterministic)." (if (and (singleton a1) (singleton a2)) (if (string= (singleton a1) (singleton a2)) (string-automaton (singleton a1)) (empty-automaton)) (progn (determinize a1) (determinize a2) (let* ((trs1 (sorted-transitions (states a1))) (trs2 (sorted-transitions (states a2))) (a3 (make-instance 'automaton)) (worklist nil) (newstates (make-generalized-hash-table +equalp-key-situation+)) (s (make-instance 'state)) (p (make-instance 'state-pair :s s :s1 (initial a1) :s2 (initial a2)))) (setf (initial a3) s) (push p worklist) (setf (htref newstates p) p) (loop while worklist do (setq p (pop worklist)) (setf (accept (s p)) (and (accept (s1 p)) (accept (s2 p)))) (let* ((t1 (aref trs1 (num (s1 p)))) (t2 (aref trs2 (num (s2 p)))) (t1l (length t1)) (t2l (length t2))) (loop with n1 = 0 and n2 = 0 while (and (< n1 t1l) (< n2 t2l)) do (cond ((< (maxc (aref t1 n1)) (minc (aref t2 n2))) (incf n1)) ((< (maxc (aref t2 n2)) (minc (aref t1 n1))) (incf n2)) (t (let* ((q (make-instance 'state-pair :s1 (to (aref t1 n1)) :s2 (to (aref t2 n2)))) (r (htref newstates q)) (min (max (minc (aref t1 n1)) (minc (aref t2 n2)))) (max (min (maxc (aref t1 n1)) (maxc (aref t2 n2))))) (unless r (setf (s q) (make-instance 'state)) (push q worklist) (setf (htref newstates q) q) (setq r q)) (htadd (transitions (s p)) (make-instance 'transition :minc min :maxc max :to (s r))) (if (< (maxc (aref t1 n1)) (maxc (aref t2 n2))) (incf n1) (incf n2)))))))) (setf (deterministic a3) t) (remove-dead-transitions a3) (check-minimize-always a3))))) (defun aunion (a1 a2) "Returns a new automaton that accepts the union of the languages of A1 and A2. Complexity: linear in the number of states." (when (and (singleton a1) (singleton a2) (string= (singleton a1) (singleton a2))) (return-from aunion (clone a1))) (let ((a2 (clone-expanded a2)) (a3 (clone-expanded a1)) (s (make-instance 'state))) (add-epsilon s (initial a2)) (add-epsilon s (initial a3)) (setf (initial a2) s (deterministic a2) nil) (check-minimize-always a2))) (defun aunion-many (l) "Returns a new automaton that accepts the union of the languages of automata given in list L." (let ((s (make-instance 'state)) (a (make-instance 'automaton))) (loop for b in l do (add-epsilon s (initial (clone-expanded b)))) (setf (initial a) s (deterministic a) nil) (check-minimize-always a))) (defun determinize (a) "Determinizes A and returns it." (if (or (deterministic a) (singleton a)) a (let ((initialset (make-instance 'state-set))) (setf (gethash (initial a) (ht initialset)) t) (determinize2 a initialset)))) (defun determinize2 (a initialset) "Determinizes A using the set of initial states in INITIALSET state-set." (let ((points (start-points a)) (sets (make-generalized-hash-table +equalp-key-situation+)) (worklist nil) (newstate (make-generalized-hash-table +equalp-key-situation+))) (setf (htref sets initialset) initialset) (push initialset worklist) (setf (initial a) (make-instance 'state)) (setf (htref newstate initialset) (initial a)) (loop while worklist do (let* ((s (pop worklist)) (r (htref newstate s))) (loop for q being the hash-key of (ht s) when (accept q) do (setf (accept r) t) (return)) (loop with len = (length points) for c across points and n from 0 do (let ((p (make-instance 'state-set))) (loop for q being the hash-key of (ht s) do (with-ht (tr nil) (transitions q) (when (<= (minc tr) c (maxc tr)) (setf (gethash (to tr) (ht p)) t)))) (unless (htpresent sets p) (setf (htref sets p) p) (push p worklist) (setf (htref newstate p) (make-instance 'state))) (let ((q (htref newstate p)) (min c) (max (if (< (1+ n) len) (1- (aref points (1+ n))) +max-char-code+))) (htadd (transitions r) (make-instance 'transition :minc min :maxc max :to q))))))) (setf (deterministic a) t) (remove-dead-transitions a))) (defun minimize (a) "Minimizes, and determinizes if not already deterministic, A and returns it." (with-slots (singleton minimization hash-code) a (unless singleton (ecase minimization (huffman (minimize-huffman a)) (brzozowski (minimize-brzozowski a)) (hopcroft (minimize-hopcroft a)))) (setf hash-code (+ (* 3 (num-of-states a)) (* 2 (num-of-transitions a)))) (when (= hash-code 0) (setf hash-code 1))) a) (defun states-agree (trs mark n1 n2) (let ((t1 (aref trs n1)) (t2 (aref trs n2))) (loop with k1 = 0 and k2 = 0 and l1 = (length t1) and l2 = (length t2) while (and (< k1 l1) (< k2 l2)) do (cond ((< (maxc (aref t1 k1)) (minc (aref t2 k2))) (incf k1)) ((< (maxc (aref t2 k2)) (minc (aref t1 k1))) (incf k2)) (t (let ((m1 (num (to (aref t1 k1)))) (m2 (num (to (aref t2 k2))))) (when (> m1 m2) (rotatef m1 m2)) (when (aref mark m1 m2) (return nil)) (if (< (maxc (aref t1 k1)) (maxc (aref t2 k2))) (incf k1) (incf k2))))) finally (return t)))) (defun add-triggers (trs triggers n1 n2) (let ((t1 (aref trs n1)) (t2 (aref trs n2))) (loop with k1 = 0 and k2 = 0 while (and (< k1 (length t1)) (< k2 (length t2))) do (cond ((< (maxc (aref t1 k1)) (minc (aref t2 k2))) (incf k1)) ((< (maxc (aref t2 k2)) (minc (aref t1 k1))) (incf k2)) (t (unless (eq (to (aref t1 k1)) (to (aref t2 k2))) (let ((m1 (num (to (aref t1 k1)))) (m2 (num (to (aref t2 k2))))) (when (> m1 m2) (rotatef m1 m2)) (unless (aref triggers m1 m2) (setf (aref triggers m1 m2) (make-hash-table))) (setf (gethash (make-instance 'int-pair :n1 n1 :n2 n2) (aref triggers m1 m2)) t))) (if (< (maxc (aref t1 k1)) (maxc (aref t2 k2))) (incf k1) (incf k2))))))) (defun mark-pair (mark triggers n1 n2) (setf (aref mark n1 n2) t) (when (aref triggers n1 n2) (loop for p being the hash-key of (aref triggers n1 n2) do (let ((m1 (n1 p)) (m2 (n2 p))) (when (> m1 m2) (rotatef m1 m2)) (unless (aref mark m1 m2) (mark-pair mark triggers m1 m2)))))) (defun ht-set-to-vector (ht) (loop with vec = (make-array (hash-table-count ht)) for k being the hash-key of ht and i from 0 do (setf (aref vec i) k) finally (return vec))) (defun minimize-huffman (a) "Minimizes A using the standard textbook, Huffman's algorithm. Complexity: O(N ^ 2), where N is the number of states." (determinize a) (totalize a) (let* ((ss (states a)) (ss-cnt (hash-table-count ss)) (trs (make-array ss-cnt)) (states (ht-set-to-vector ss)) (mark (make-array `(,ss-cnt ,ss-cnt) :element-type 'boolean :initial-element nil)) (triggers (make-array `(,ss-cnt ,ss-cnt) :initial-element nil)) (numclasses 0)) (loop for n1 below ss-cnt do (setf (num (aref states n1)) n1 (aref trs n1) (sorted-transition-vector (aref states n1) nil)) (loop for n2 from (1+ n1) below ss-cnt unless (eq (accept (aref states n1)) (accept (aref states n2))) do (setf (aref mark n1 n2) t))) (loop for n1 below ss-cnt do (loop for n2 from (1+ n1) below ss-cnt unless (aref mark n1 n2) do (if (states-agree trs mark n1 n2) (add-triggers trs triggers n1 n2) (mark-pair mark triggers n1 n2)))) (loop for n below ss-cnt do (setf (num (aref states n)) -1)) (loop for n1 below ss-cnt when (= (num (aref states n1)) -1) do (setf (num (aref states n1)) numclasses) (loop for n2 from (1+ n1) below ss-cnt unless (aref mark n1 n2) do (setf (num (aref states n2)) numclasses)) (incf numclasses)) (let ((newstates (make-array numclasses))) (loop for n below numclasses do (setf (aref newstates n) (make-instance 'state))) (loop for n below ss-cnt do (setf (num (aref newstates (num (aref states n)))) n) (when (eq (aref states n) (initial a)) (setf (initial a) (aref newstates (num (aref states n)))))) (loop for n below numclasses do (let ((s (aref newstates n))) (setf (accept s) (accept (aref states (num s)))) (with-ht (tr nil) (transitions (aref states (num s))) (htadd (transitions s) (make-instance 'transition :minc (minc tr) :maxc (maxc tr) :to (aref newstates (num (to tr)))))))) (remove-dead-transitions a)))) (defun minimize-brzozowski (a) "Minimizes A using Brzozowski's algorithm. Complexity: O(2 ^ N), where N is the number of states, but works very well in practice (even better than Hopcroft's)." (if (singleton a) nil (progn (determinize2 a (make-instance 'state-set :ht (areverse a))) (determinize2 a (make-instance 'state-set :ht (areverse a)))))) (defun minimize-hopcroft (a) "Minimizes A using Hopcroft's algorithm. Complexity: O(N log N), regarded as one of the most generally efficient existing algorithms." (determinize a) (let ((trs (transitions (initial a)))) (when (= (cnt trs) 1) (with-ht (tr nil) trs (when (and (eq (to tr) (initial a)) (= (minc tr) +min-char-code+) (= (maxc tr) +max-char-code+)) (return-from minimize-hopcroft))))) (totalize a) (let* ((ss (states a)) (ss-cnt (hash-table-count ss)) (states (ht-set-to-vector ss))) (set-state-nums ss) (let* ((sigma (start-points a)) (sigma-cnt (length sigma)) (rvrs (make-array `(,ss-cnt ,sigma-cnt) :initial-element nil)) (rvrs-ne (make-array `(,ss-cnt ,sigma-cnt) :element-type 'boolean :initial-element nil)) (partition (make-array ss-cnt :initial-element nil)) (block (make-array ss-cnt :element-type 'fixnum)) (active (make-array `(,ss-cnt ,sigma-cnt))) (active2 (make-array `(,ss-cnt ,sigma-cnt) :initial-element nil)) (pending nil) (pending2 (make-array `(,sigma-cnt ,ss-cnt) :element-type 'boolean :initial-element nil)) (split nil) (split2 (make-array ss-cnt :element-type 'boolean :initial-element nil)) (refine nil) (refine2 (make-array ss-cnt :element-type 'boolean :initial-element nil)) (splitblock (make-array ss-cnt :initial-element nil)) (k 2)) (loop for j below ss-cnt do (loop for i below sigma-cnt do (setf (aref active j i) (make-instance 'state-list)))) (loop for q below ss-cnt for qq = (aref states q) do (let ((j (if (accept qq) 0 1))) (push qq (aref partition j)) (setf (aref block (num qq)) j) (loop for i below sigma-cnt do (let* ((aa (code-char (aref sigma i))) (p (sstep qq aa))) (push qq (aref rvrs (num p) i)) (setf (aref rvrs-ne (num p) i) t))))) (loop for j from 0 to 1 do (loop for i below sigma-cnt do (loop for qq in (aref partition j) when (aref rvrs-ne (num qq) i) do (setf (aref active2 (num qq) i) (slnadd (aref active j i) qq))))) (loop for i below sigma-cnt for i0 = (size (aref active 0 i)) and i1 = (size (aref active 1 i)) do (let ((j (if (<= i0 i1) 0 1))) (push (make-instance 'int-pair :n1 j :n2 i) pending) (setf (aref pending2 i j) t))) (loop while pending for ip = (pop pending) for p = (n1 ip) and i = (n2 ip) do (setf (aref pending2 i p) nil) (loop for m = (fst (aref active p i)) then (succ m) while m do (loop for s in (aref rvrs (num (q m)) i) unless (aref split2 (num s)) do (setf (aref split2 (num s)) t) (push s split) (let ((j (aref block (num s)))) (push s (aref splitblock j)) (unless (aref refine2 j) (setf (aref refine2 j) t) (push j refine))))) (loop for j in refine do (when (< (length (aref splitblock j)) (length (aref partition j))) (loop for s in (aref splitblock j) do (setf (aref partition j) (remove s (aref partition j))) (push s (aref partition k)) (setf (aref block (num s)) k) (loop for c below sigma-cnt for sn = (aref active2 (num s) c) when (and sn (eq (sl sn) (aref active j c))) do (slnremove sn) (setf (aref active2 (num s) c) (slnadd (aref active k c) s)))) (loop for c below sigma-cnt for ij = (size (aref active j c)) and ik = (size (aref active k c)) if (and (not (aref pending2 c j)) (< 0 ij) (<= ij ik)) do (setf (aref pending2 c j) t) (push (make-instance 'int-pair :n1 j :n2 c) pending) else do (setf (aref pending2 c k) t) (push (make-instance 'int-pair :n1 k :n2 c) pending)) (incf k)) (loop for s in (aref splitblock j) do (setf (aref split2 (num s)) nil)) (setf (aref refine2 j) nil) (setf (aref splitblock j) nil)) (setq split nil) (setq refine nil)) (let ((newstates (make-array k))) (loop for n below k for s = (make-instance 'state) do (setf (aref newstates n) s) (loop for q in (aref partition n) do (when (eq q (initial a)) (setf (initial a) s)) (setf (accept s) (accept q) (num s) (num q) (num q) n))) (loop for n below k for s = (aref newstates n) do (with-ht (tr nil) (transitions (aref states (num s))) (setf (num s) n) (htadd (transitions s) (make-instance 'transition :minc (minc tr) :maxc (maxc tr) :to (aref newstates (num (to tr))))))) (remove-dead-transitions a))))) (defun areverse (a) "Reverses the language of non-singleton A. Returns a hash table of new initial states." (let ((m (make-hash-table)) (states (states a)) (astates (accepting-states a))) (loop for r being the hash-key of states do (setf (gethash r m) (make-generalized-hash-table +equalp-key-situation+) (accept r) nil)) (loop for r being the hash-key of states do (with-ht (tr nil) (transitions r) (htadd (gethash (to tr) m) (make-instance 'transition :minc (minc tr) :maxc (maxc tr) :to r)))) (loop for r being the hash-key of states do (setf (transitions r) (gethash r m))) (setf (accept (initial a)) t (initial a) (make-instance 'state)) (loop for r being the hash-key of astates do (add-epsilon (initial a) r)) (setf (deterministic a) nil) astates)) (defun add-epsilons (a pairs) "Adds epsilon transitions to A and returns it. This is done by adding extra character interval transitions that are equivalent to the given set of epsilon transitions. PAIRS is a list of state-pair objects representing pairs of source-destination states where the epsilon transitions should be added." (expand-singleton a) (let ((forward (make-hash-table)) (back (make-hash-table))) (loop for p in pairs do (let ((tos (gethash (s1 p) forward)) (froms (gethash (s2 p) back))) (unless tos (setq tos (make-hash-table)) (setf (gethash (s1 p) forward) tos)) (setf (gethash (s2 p) tos) t) (unless froms (setq froms (make-hash-table)) (setf (gethash (s2 p) back) froms)) (setf (gethash (s1 p) froms) t))) (let ((worklist pairs) (workset (make-generalized-hash-table +equalp-key-situation+))) (loop for p in pairs do (htadd workset p)) (loop while worklist for p = (pop worklist) do (htremove workset p) (let ((tos (gethash (s2 p) forward)) (froms (gethash (s1 p) back))) (when tos (loop for s being the hash-key of tos for pp = (make-instance 'state-pair :s1 (s1 p) :s2 s) unless (member pp pairs :test #'(lambda (o1 o2) (eqv o1 o2 +equalp-key-situation+))) do (push pp pairs) (setf (gethash s (gethash (s1 p) forward)) t) (setf (gethash (s1 p) (gethash s back)) t) (push pp worklist) (htadd workset pp) (when froms (loop for q being the hash-key of froms for qq = (make-instance 'state-pair :s1 q :s2 (s1 p)) unless (htpresent workset qq) do (push qq worklist) (htadd worklist qq))))))) (loop for p in pairs do (add-epsilon (s1 p) (s2 p))) (setf (deterministic a) nil) (check-minimize-always a)))) (defun run (a str) "Returns true if STR is accepted by A. As a side-effect, A is determinized if not already deterministic. Complexity: linear in the length of STR (when A is deterministic)." (if (singleton a) (string= str (singleton a)) (progn (determinize a) (let ((p (initial a))) (loop for i below (length str) for q = (sstep p (elt str i)) unless q return nil do (setq p q) finally (return (accept p))))))) (defun run-to-first-match (a str &optional (start 0) (end (length str))) "Returns the end position of match if a substring of STR, optionally between positions START and END, is found that is accepted by A; otherwise, returns nil. Complexity: linear in the length of STR (when A is deterministic)." (if (singleton a) (let ((from (search (singleton a) str :start2 start :end2 end))) (when from (+ from (length str)))) (progn (determinize a) (let ((p (initial a))) (loop for i from start below end for q = (sstep p (elt str i)) do (unless q (return nil)) (if (accept q) (return (1+ i)) (setq p q)) finally (return nil)))))) (defun run-to-first-unmatch (a str &optional (start 0) (end (length str))) "Returns the end position of match if a substring of STR, optionally between positions START and END, is found that is accepted by A; otherwise, returns nil. A greedy approach is taken until the first match failure or the end of STR (whatever happens first), trying to extend the match length one character at a time. Complexity: linear in the length of STR (when A is deterministic)." (if (singleton a) (let ((from (search (singleton a) str :start2 start :end2 end))) (when from (+ from (length str)))) (progn (determinize a) (let* ((p (initial a)) (matched (accept p))) (loop for i from start below end for q = (sstep p (elt str i)) if (not q) return (if matched i nil) else do (if (accept q) (setq matched t) (when matched (return i))) (setq p q) finally (return (if matched i nil))))))) (defun num-of-states (a) "Returns the number of states of A." (if (singleton a) (1+ (length (singleton a))) (hash-table-count (states a)))) (defun num-of-transitions (a) "Returns the number of transitions of A." (if (singleton a) (length (singleton a)) (loop for s being the hash-key of (states a) sum (cnt (transitions s))))) (defun empty-p (a) "Returns true if A accepts no strings." (if (singleton a) nil (and (not (accept (initial a))) (= (cnt (transitions (initial a))) 0)))) (defun subset-of (a a2) "Returns true if the language of A is a subset of the language of A2." (if (singleton a) (if (singleton a2) (string= (singleton a) (singleton a2)) (run a2 (singleton a))) (empty-p (aintersection a (acomplement a2))))) (defmethod eqv ((a1 automaton) (a2 automaton) (s (eql +equalp-key-situation+))) "Returns true if the language of A1 is equal to the language of A2." (or (and (singleton a1) (singleton a2) (string= (singleton a1) (singleton a2))) (and (= (hash a1 s) (hash a2 s)) (subset-of a1 a2) (subset-of a2 a1)))) (defmethod hash ((a automaton) (s (eql +equalp-key-situation+))) "Returns the hash code for automaton A." (when (= (hash-code a) 0) (minimize a)) (hash-code a)) (defvar *print-renumerate-states* nil) (defmethod print-object ((a automaton) s) (let* ((a (if *print-renumerate-states* (clone a) a)) (states (states a))) (when *print-renumerate-states* (set-state-nums states)) (format s "~@<initial state: ~A ~_~@<~{~W~^ ~_~}~:>~:>" (num (initial a)) (loop for st being the hash-key of states collect st))) a) (defun clone-expanded (a) "Returns a clone of A, expanded if singleton." (let ((a (clone a))) (expand-singleton a) a)) (defmethod clone ((a automaton)) "Returns a clone of A." (let ((a2 (make-instance 'automaton))) (setf (minimization a2) (minimization a) (deterministic a2) (deterministic a) (info a2) (info a) (hash-code a2) (hash-code a) (minimize-always a2) (minimize-always a)) (if (singleton a) (setf (singleton a2) (singleton a)) (let ((map (make-hash-table)) (states (states a))) (loop for s being the hash-key of states do (setf (gethash s map) (make-instance 'state))) (loop for s being the hash-key of states do (let ((p (gethash s map))) (setf (accept p) (accept s)) (when (eq s (initial a)) (setf (initial a2) p)) (let ((p-table (transitions p))) (with-ht (tr nil) (transitions s) (htadd p-table (make-instance 'transition :minc (minc tr) :maxc (maxc tr) :to (gethash (to tr) map))))))))) a2)) (defun slnadd (sl q) "Adds state Q to state-list SL and returns a new state-list-node object." (make-instance 'state-list-node :q q :sl sl)) (defmethod initialize-instance :after ((sln state-list-node) &rest initargs) (declare (ignorable initargs)) (if (= (incf (size (sl sln))) 1) (setf (fst (sl sln)) sln (lst (sl sln)) sln) (setf (succ (lst (sl sln))) sln (pred sln) (lst (sl sln)) (lst (sl sln)) sln))) (defun slnremove (sln) "Removes state-list-node SLN from its state-list object." (decf (size (sl sln))) (if (eq sln (fst (sl sln))) (setf (fst (sl sln)) (succ sln)) (setf (succ (pred sln)) (succ sln))) (if (eq sln (lst (sl sln))) (setf (lst (sl sln)) (pred sln)) (setf (pred (succ sln)) (pred sln))))
41,592
Common Lisp
.lisp
1,142
31.718039
79
0.640193
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
9ab915b409824f9dfecd16d011eaea6bd9152cfcceeca8987e5914270092beef
13,628
[ -1 ]
13,629
state-and-transition-test.lisp
amb007_cl-automaton/state-and-transition-test.lisp
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package :automaton-user) (deftest clone.transition.test-1 (let* ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (t2 (automaton::clone t1))) (and (eqv t1 t2 +equalp-key-situation+) (eql (hash t1 +equalp-key-situation+) (hash t2 +equalp-key-situation+)))) t) (deftest transition<.test-1 (let ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\c) :maxc (char-code #\d) :to (make-instance 'automaton::state))) (automaton::*to-first* nil)) (automaton::transition< t1 t2)) t) (deftest transition<.test-2 (let ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\c) :maxc (char-code #\d) :to (make-instance 'automaton::state))) (automaton::*to-first* t)) (setf (automaton::num (automaton::to t1)) 1) (automaton::transition< t2 t1)) t) (deftest transition<.test-2a (let ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\d) :to (make-instance 'automaton::state))) (automaton::*to-first* t)) (automaton::transition< t2 t1)) t) (deftest transition<.test-3 (let ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\c) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (automaton::*to-first* nil)) (automaton::transition< t1 t2)) t) (deftest sstep.test-1 (let* ((s (make-instance 'automaton::state)) (tr (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to s))) (htadd (automaton::transitions s) tr) (eq (automaton::sstep s #\a) s)) t) (deftest sstep.test-2 (let* ((s (make-instance 'automaton::state)) (tr (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to s))) (htadd (automaton::transitions s) tr) (automaton::sstep s #\c)) nil) (deftest add-epsilon.test-1 (let* ((s1 (make-instance 'automaton::state)) (s2 (make-instance 'automaton::state)) (tr (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to s2))) (htadd (automaton::transitions s2) tr) (automaton::add-epsilon s1 s2) (htpresent (automaton::transitions s1) tr)) t) (deftest sorted-transition-vector.test-1 (let* ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\c) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (s (make-instance 'automaton::state))) (htadd (automaton::transitions s) t1) (htadd (automaton::transitions s) t2) (equalp (automaton::sorted-transition-vector s nil) (vector t1 t2))) t) (deftest sorted-transition-list.test-1 (let* ((t1 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\c) :to (make-instance 'automaton::state))) (t2 (make-instance 'automaton::transition :minc (char-code #\a) :maxc (char-code #\b) :to (make-instance 'automaton::state))) (s (make-instance 'automaton::state))) (htadd (automaton::transitions s) t1) (htadd (automaton::transitions s) t2) (equal (automaton::sorted-transition-list s nil) (list t1 t2))) t)
3,995
Common Lisp
.lisp
104
33.961538
62
0.647514
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
8cc3919b084cd535607981255df49cde2d1d02084f9a4aee732e57c9918fc789
13,629
[ -1 ]
13,630
automaton.asd
amb007_cl-automaton/automaton.asd
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package #:asdf) (defsystem #:automaton :depends-on ("rt") :components ((:file "automaton-package") (:file "eqv-hash" :depends-on ("automaton-package")) (:file "state-and-transition" :depends-on ("eqv-hash")) (:file "automaton" :depends-on ("state-and-transition" "eqv-hash")) (:file "regexp" :depends-on ("automaton"))))
440
Common Lisp
.asd
13
31.230769
70
0.643192
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
641b7cd38a9682fb3a4d2ad402477a5421ff5b0a1ba5b60d0bffd266bc271080
13,630
[ -1 ]
13,631
automaton-test.asd
amb007_cl-automaton/automaton-test.asd
;;; -*- mode: lisp -*- ;;; ;;; (c) copyright 2005 by Aleksandar Bakic ([email protected]) ;;; (in-package #:asdf) (defsystem #:automaton-test :depends-on ("automaton") :components ((:file "automaton-test-package") (:file "eqv-hash-test" :depends-on ("automaton-test-package")) (:file "state-and-transition-test" :depends-on ("automaton-test-package")) (:file "automaton-test" :depends-on ("automaton-test-package")) (:file "regexp-test" :depends-on ("automaton-test-package"))))
515
Common Lisp
.asd
13
35.846154
79
0.656
amb007/cl-automaton
7
0
0
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
f31ecf2d392ed1b236b82c653ec653338373679f37f49883d23a4d73667d1bd3
13,631
[ -1 ]
13,657
main.lisp
kat-co_gir2cl/src/main.lisp
(defpackage gir2cl (:use :cl) (:import-from #:cxml) (:import-from #:gir) (:import-from #:kebab) (:import-from #:simple-date-time) (:export #:generate)) (in-package :gir2cl) ;; repository ;; |- include ;; |- package ;; |- namespace ;; |-+ ;; | |- class ;; | |-+ ;; | | |- source-position ;; | | |- method ;; | | |-+ ;; | | | |- source-position ;; | | | |- return-value ;; | | | |- parameters ;; | | | |-+ ;; | | | | |- instance-parameter ;; | | | | |-+ ;; | | | | | |- doc ;; | | | | | |- type ;; | | | | |- parameter ;; | | | | |-+ ;; | | | | | |- doc ;; | | | | | |- type (defun generate (package-name namespace stream gir-pathname) "Generates low-level Common Lisp bindings from the GIR filepath passed in. Returns a list of exported symbols." (check-type package-name string) (check-type gir-pathname pathname) (check-type stream (or stream boolean)) (let ((*package* (find-package :cl-user)) (handler (make-instance 'gir-handler :namespace namespace :output-stream stream))) (format stream ";;;; Generated by gir2cl on ~a~%~%" (simple-date-time:rfc-2822 (simple-date-time:now))) (format stream "(in-package ~a)~%~%" package-name) (format stream "(defparameter *ns* (gir:require-namespace \"~@*~a\"))~%~%" namespace) (format stream "~(~s~)~%~%" '(defclass cl-user::gir-object () ((cl-user::native-pointer :initarg :native-pointer :reader cl-user::native-pointer)))) (cxml:parse-file gir-pathname handler) (cons 'cl-user::gir-object (cons 'cl-user::native-pointer (reverse (all-symbols handler)))))) (defclass gir-class () ((name :type symbol :initarg :name :reader name) (gir-name :type string :initarg :gir-name :reader gir-name) (slots :type list :initform (list) :accessor slots) (parent-clos-class :type symbol :initarg :parent-clos-class :initform nil) (constructors :type list :initform (list) :accessor constructors) (methods :type list :initform (list) :accessor methods))) (defmethod print-object ((class gir-class) stream) (with-slots (name slots parent-clos-class) class (format stream "~(~s~)" `(defclass ,name ,(if parent-clos-class (list parent-clos-class) '(cl-user::gir-object)) (,@slots))))) (defclass gir-method () ((name :type symbol :initarg :name :reader name) (gir-name :type string :initarg :gir-name) (class-name :type string :initarg :class-name) (parameters :type list :initform (list) :accessor parameters))) (defmethod print-object ((method gir-method) stream) (with-slots (name gir-name class-name parameters) method (let ((parameters (reverse parameters))) (format stream "~(~s~)" `(defmethod ,name ((,class-name ,class-name) ,@parameters) (with-slots (cl-user::native-pointer) ,class-name (gir:invoke (cl-user::native-pointer ,gir-name) ,@parameters))))))) (defclass gir-function () ((clos-class-name :type symbol :initarg :clos-class-name) (gir-class-name :type string :initarg :gir-class-name) (name :type symbol :initarg :name) (gir-name :type string :initarg :gir-name) (parameters :type list :initform (list) :accessor parameters))) (defmethod name-symbol ((function gir-function)) "Generates a symbol for the name of the constructor." (with-slots (clos-class-name name) function (intern (format nil "~:@(make-~a-~s~)" clos-class-name name)))) (defmethod print-object ((function gir-function) stream) (with-slots (clos-class-name gir-class-name gir-name parameters) function (let ((parameters (reverse parameters))) ;; First format is to inject the GIR class name in its proper ;; case. The second is to print the lisp bits in lowercase. (format stream (format nil "~(~s~)" `(defun ,(name-symbol function) (,@parameters) (let ((cl-user::pointer (gir:invoke (cl-user::*ns* "~a" ,gir-name) ,@parameters))) (make-instance ',clos-class-name :native-pointer cl-user::pointer)))) gir-class-name)))) (defclass gir-parameter () ((name :type string :initarg :name :reader name) (type :type type :initarg :type :initform nil :accessor gir-type))) (defmethod print-object ((parameter gir-parameter) stream) (with-slots (name) parameter (format stream "~(~a~)" name))) (defclass gir-enumeration () ((namespace :type symbol :initarg :namespace :initform (error ":symbol is required.") :reader namespace) (name :type string :initarg :name :reader name) (members :type list :initform (list) :accessor members))) (defmethod print-object ((enumeration gir-enumeration) stream) (loop with namespace = (namespace enumeration) with enumeration-name = (name enumeration) for member in (members enumeration) ;; Must be upcase so that it's not interned as case-sensitive ;; symbols. for name-upcase = (string-upcase (name member)) for name-global = (global-symbol-from member) for name-keyword = (intern name-upcase :keyword) for defparam-form = `(defparameter ,name-global (gir:nget ,namespace "~a" ,name-keyword)) do (format stream (format nil "~(~s~)~%" defparam-form) enumeration-name))) (defclass gir-enumeration-member () ((enum-name :type string :initarg :enum-name :initform (error ":enum-name is required") :reader enum-name) (name :type string :initarg :name :initform (error ":name is required.") :reader name))) (defmethod global-symbol-from ((enum-member gir-enumeration-member)) (intern (format nil "*~a-~a*" (string-upcase (kebab:to-kebab-case (enum-name enum-member))) (string-upcase (kebab:to-kebab-case (name enum-member)))))) (defclass gir-handler (sax:default-handler) ((namespace :type string :initarg :namespace :initform (error "namespace must be specified.") :reader namespace) (clos-from-gir :type hash-table :initform (make-hash-table :test #'equalp) :accessor clos-from-gir) (output-stream :type stream :initarg :output-stream :initform (error "output-stream must be specified.") :reader output-stream) (current-class :type gir-class :initform nil :accessor current-class) (current-constructor :type gir-class :initform nil :accessor current-constructor) (current-method :type gir-method :initform nil :accessor current-method) (current-parameter :type gir-parameter :initform nil :accessor current-parameter) (current-enumeration :type gir-enumeration :initform nil :accessor current-enumeration) (current-enumeration-member :type gir-enumeration-member :initform nil :accessor current-enumeration-member) (all-symbols :type list :initform (list) :accessor all-symbols :documentation "A list of all symbols that are generated."))) (defmethod sax:start-element ((handler gir-handler) namespace-uri local-name qname attributes) ;; All of the logic for skipping XML nodes of certain types should ;; be centralized here. By doing this, the logic in `end-element` ;; only need check to see if an instance of instantiated. (flet ((element-attr (attr-name) (sax:attribute-value (find attr-name attributes :key #'sax:attribute-local-name :test #'string=)))) (cond ((string= local-name "class") (let* ((name (element-attr "name")) (parent (element-attr "parent")) (shadowed (find-symbol (string-upcase (kebab:to-kebab-case name)))) (acceptable-name (kebab-symbol-from-string (if shadowed (concatenate 'string (namespace handler) name) name))) (class (make-instance 'gir-class :name acceptable-name :gir-name name :parent-clos-class (gethash parent (clos-from-gir handler))))) (setf (gethash name (clos-from-gir handler)) acceptable-name (current-class handler) class))) ((and (string= local-name "constructor") ;; Only constructors within classes are currently ;; supported. (current-class handler)) (let* ((name (element-attr "name")) (constructor (make-instance 'gir-function :name (kebab-symbol-from-string name) :gir-name name :clos-class-name (name (current-class handler)) :gir-class-name (gir-name (current-class handler))))) (setf (current-constructor handler) constructor))) ((string= local-name "enumeration") (setf (current-enumeration handler) (make-instance 'gir-enumeration :name (element-attr "name") :namespace 'cl-user::*ns*))) ((and (string= local-name "member") (current-enumeration handler)) (setf (current-enumeration-member handler) (make-instance 'gir-enumeration-member :enum-name (name (current-enumeration handler)) :name (element-attr "name")))) ((and (string= local-name "method") ;; Only methods within classes are currently supported. (current-class handler)) (let* ((name (element-attr "name")) (class-namespaced-name (format nil "~(~a-~a~)" (name (current-class handler)) name)) (shadowed (find-symbol (string-upcase (kebab:to-kebab-case class-namespaced-name)))) (acceptable-name (kebab-symbol-from-string (if shadowed (concatenate 'string (namespace handler) class-namespaced-name) class-namespaced-name))) (method (make-instance 'gir-method :name acceptable-name :gir-name name :class-name (name (current-class handler))))) (setf (current-method handler) method))) ((and (string= local-name "parameter") (or (current-method handler) (current-constructor handler)) ;; The cl-gobject-introspection library handles passing the ;; length of sequences for us. Don't include the parameter ;; in our bindings. (not (length-parameter-p handler))) (let* ((name (element-attr "name")) (parameter (make-instance 'gir-parameter :name (kebab-symbol-from-string name)))) (setf (current-parameter handler) parameter))) ((and (string= local-name "array") (current-parameter handler)) ;; For array parameters, we need only know that they are arrays ;; so that we can ellide the subsequent length parameter. (setf (gir-type (current-parameter handler)) 'array))))) (defmethod sax:end-element ((handler gir-handler) namespace-uri local-name qname) ;; Before processing a element when exiting its XML node, first ;; check that the handler has instantiated an instance for the ;; elment. There are conditionals which may cause the handler to ;; bypass certain elements. (with-accessors ((out output-stream) (class current-class) (all-symbols all-symbols) (ctor current-constructor) (param current-parameter) (method current-method) (enum current-enumeration) (enum-member current-enumeration-member)) handler (cond ((string= local-name "class") (format out "~a~%~%" class) (dolist (c (reverse (constructors class))) (format out "~a~%~%" c)) (dolist (m (reverse (methods class))) (format out "~a~%~%" m)) (setf all-symbols (cons (name class) all-symbols) class nil)) ((and (string= local-name "constructor") ctor) (dolist (p (parameters ctor)) (pushnew p (slots class) :key #'name :test #'string=)) (pushnew ctor (constructors class)) (setf all-symbols (cons (name-symbol ctor) all-symbols) ctor nil)) ((and (string= local-name "method") method) (pushnew method (methods class)) (setf all-symbols (cons (name method) all-symbols) method nil)) ((and (string= local-name "parameter") param) (if method (pushnew param (parameters method)) (pushnew param (parameters ctor))) (setf param nil)) ((and (string= local-name "member") enum enum-member) (pushnew enum-member (members enum)) (setf all-symbols (cons (global-symbol-from enum-member) all-symbols) enum-member nil)) ((string= local-name "enumeration") enum (format out "~a~%~%" enum) (setf enum nil))))) (defun length-parameter-p (handler) "Determines whether this parameter is meant to contain the length of the previous parameter." ;; TODO(katco): How does the gir lib check this, and can we use that here? (let* ((current-obj (or (current-method handler) (current-constructor handler))) (last-param (when current-obj (car (parameters current-obj))))) (if last-param (eq (gir-type last-param) 'array) nil))) (defun kebab-symbol-from-string (s) (check-type s string) (intern (string-upcase (kebab:to-kebab-case s))))
14,803
Common Lisp
.lisp
346
32
100
0.572033
kat-co/gir2cl
7
1
1
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
e9192c631af8cc913b92b6d960537991ef7179869d5d8ad992fed85f2dc8e429
13,657
[ -1 ]
13,658
main.lisp
kat-co_gir2cl/tests/main.lisp
(defpackage gir2cl/tests/main (:use :cl :gir2cl :rove)) (in-package :gir2cl/tests/main) ;; NOTE: To run this test file, execute `(asdf:test-system :gir2cl)' in your Lisp. (deftest test-target-1 (testing "should (= 1 1) to be true" (ok (= 1 1))))
272
Common Lisp
.lisp
9
26.333333
82
0.639847
kat-co/gir2cl
7
1
1
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
429f4715334ab9035a0aa4678c4ecf4577b6d2efb6edf51c36aa265fbc190340
13,658
[ -1 ]
13,659
gir2cl.asd
kat-co_gir2cl/gir2cl.asd
(defsystem "gir2cl" :version "0.1.2" :author "Katherine Cox-Buday <[email protected]>" :license "GPLv3" :depends-on (#:cxml #:cl-gobject-introspection #:kebab #:simple-date-time) :components ((:module "src" :components ((:file "main")))) :description "gir2cl generates Common Lisp code from GIR files." :in-order-to ((test-op (test-op "gir2cl/tests")))) (defsystem "gir2cl/tests" :author "Katherine Cox-Buday <[email protected]>" :license "GPLv3" :depends-on ("gir2cl" "rove") :components ((:module "tests" :components ((:file "main")))) :description "Test system for gir2cl" :perform (test-op (op c) (symbol-call :rove :run c)))
799
Common Lisp
.asd
24
25.916667
59
0.586563
kat-co/gir2cl
7
1
1
LGPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
3dbb2077955ff461d402aa6d6b4edd2aff1a3c63ea9e66c2201063839c9417b8
13,659
[ -1 ]
13,679
page.lisp
foggynight_typewriter/src/page.lisp
;; Pages are a representation of files, they contain a text buffer which is a ;; list of lines. All pages are associated with a file where their text content ;; is read from/written to. (in-package #:typewriter) (defclass page () ((text-buffer :accessor text-buffer :documentation "Text contained within the page represented as a list of lines.")) (:documentation "Page class representing a file.")) (defmethod line-count ((object page)) "Get the number of lines contained within the text buffer of a page." (length (text-buffer object))) (defmethod add-lines ((object page) line-list) "Add a list of lines to the end of the text buffer of a page." (setf (text-buffer object) (append (text-buffer object) line-list))) (defmethod add-char ((object page) char y x) "Add a character at the given y-x position of a page. Any character located at the y-x position before calling add-char is overwritten." (let ((page-line-count (line-count object))) (unless (> page-line-count y) (let ((new-line-list (make-list (1+ (- y page-line-count))))) (setq new-line-list (map 'list #'make-line new-line-list)) (add-lines object new-line-list)))) (let ((line (car (nthcdr y (text-buffer object))))) (if (> (length line) x) (setf (aref line x) char) (progn (loop while (< (length line) x) do (vector-push-extend #\space line)) (vector-push-extend char line)))))
1,467
Common Lisp
.lisp
32
41.0625
79
0.678097
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
6d4b35b6cffa0bc3960e57c6f8f2dfee7822e5b4cc40a2778499d7213921da01
13,679
[ -1 ]
13,680
line.lisp
foggynight_typewriter/src/line.lisp
;; Lines are extendable vectors of characters which represent a line of text. ;; They do not include the newline character ending the line nor any other ;; string terminator. (in-package #:typewriter) (defparameter *initial-line-size* 80 "Initial size of lines created by the make-line function.") (defun make-line (&optional arg) "Make an empty line. The single optional parameter is ignored, this allows it to be used with the map function to map a sequence of anything to empty lines." (declare (ignore arg)) (make-array *initial-line-size* :adjustable t :element-type 'character :fill-pointer 0)) (defun string-to-line (string) "Convert a string to a line." (let ((line (make-line))) (loop for char across string do (vector-push-extend char line)) line)) (defun line-to-string (line) "Convert a line to a string." (coerce line 'string)) (defun line-blank-p (line) "Determine if a line is blank, that is, if it contains only spaces." (let ((is-blank t)) (loop for char across line while is-blank do (unless (eql char #\space) (setq is-blank nil))) is-blank)) (defun trim-trailing-whitespace (line) "Trim all whitespace from the end of a line." (let ((last-char -1) (walk 0)) (loop for char across line do (unless (eql char #\space) (setq last-char walk)) (incf walk)) (subseq line 0 (1+ last-char))))
1,519
Common Lisp
.lisp
40
31.6
80
0.648538
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
0ac09d26ba3d43462eaa30c11efd9ffcb6ff130f732f78fcf8f04b12f4667736
13,680
[ -1 ]
13,681
main.lisp
foggynight_typewriter/src/main.lisp
(in-package #:typewriter) (defun main () (let* ((args (uiop:command-line-arguments)) (filename (car args)) (cursor (make-instance 'cursor :y 0 :x 0)) (page nil)) (when (or (< (length args) 1) (> (length args) 1)) (format t "typewriter: Wrong number of arguments~%~ Usage: typewriter FILENAME~%") (sb-ext:exit)) (setq page (read-page-from-file filename)) (crt:with-screen (scr :input-echoing nil :process-control-chars nil) ;;; <CTRL> Command Events (crt:bind scr #\ 'crt:exit-event-loop) (crt:bind scr #\ (lambda (w e) (declare (ignore w e)) (write-page-to-file filename page))) ;;; Movement Events (macrolet ((bind (key direction &optional (n 1)) `(crt:bind scr ,key (lambda (w e) (declare (ignore w e)) (if (> ,n 1) (move cursor ,direction ,n) (move cursor ,direction)) (screen-draw-page scr cursor page))))) (bind :backspace :left) (bind #\tab :right *slide-width*) (bind :btab :left *slide-width*) (bind :up :up) (bind :down :down) (bind :left :left) (bind :right :right)) (crt:bind scr #\newline (lambda (w e) (declare (ignore w e)) (newline cursor) (screen-draw-page scr cursor page))) ;;; Window Events (crt:bind scr :resize (lambda (w e) (declare (ignore w e)) (screen-center-cursor scr) (screen-draw-page scr cursor page))) ;;; Print Events ;; For any unbound character: if the character is a standard character, ;; add it to the page and move the cursor, otherwise do nothing. (crt:bind scr t (lambda (w e) (declare (ignore w)) (when (standard-char-p e) (add-char page e (y cursor) (x cursor)) (move cursor :right) (screen-draw-page scr cursor page)))) (screen-center-cursor scr) (screen-draw-page scr cursor page) (crt:run-event-loop scr))))
2,438
Common Lisp
.lisp
60
26.583333
77
0.478921
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
fc73471d2bef8c1dbbf312434139196b1aa8f619b17ba73c586c34bc35541366
13,681
[ -1 ]
13,682
config.lisp
foggynight_typewriter/src/config.lisp
(in-package #:typewriter) (defparameter *slide-width* 4 "Number of characters to slide the text cursor on slide commands.")
127
Common Lisp
.lisp
3
40.333333
69
0.772358
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
7a81a4845b0c213b91bd7bdd32b94760da2ef8917bc2539367bb533cfc9cfe88
13,682
[ -1 ]
13,683
screen.lisp
foggynight_typewriter/src/screen.lisp
(in-package #:typewriter) (defun screen-center-cursor (scr) "Move the screen cursor to the center of the screen." (apply #'crt:move (cons scr (crt:center-position scr)))) (defun screen-newline (scr start-x) "Move the screen cursor to the start-x'th column of the next row." (let* ((pos (crt:cursor-position scr)) (y (car pos))) (crt:move scr (1+ y) start-x))) (defun screen-draw-line (scr cursor line) "Draw a line at the current position of the screen cursor, leaving the screen cursor unmoved." (when (> (length line) 0) (let* ((width (crt:width scr)) (win-center (crt:center-position scr)) (center-x (cadr win-center)) (first-char (- (x cursor) center-x)) (char-count (if (< first-char 0) (+ width first-char) width))) ;; The screen cursor must be returned to its previous position after ;; drawing a line, otherwise lines that run to the end of the page will ;; cause the cursor to end up on the next line, causing the following line ;; to be drawn in the wrong position. (crt:save-excursion scr (when (< first-char 0) (crt:move-direction scr :right (- first-char)) (setq first-char 0)) (when (< first-char (length line)) (let ((line-to-draw (subseq line first-char))) (when (< char-count (length line-to-draw)) (setq line-to-draw (subseq line-to-draw 0 char-count))) (crt:add scr (line-to-string line-to-draw)))))))) (defun screen-draw-page (scr cursor page) "Draw a page with its text content positioned such that the screen is centered on the text cursor." (let* ((height (crt:height scr)) (win-center (crt:center-position scr)) (center-y (car win-center)) (first-line (- (y cursor) center-y)) (line-count (if (< first-line 0) (+ height first-line) height))) (crt:save-excursion scr (crt:clear scr) (loop while (< first-line 0) do (screen-newline scr 0) (incf first-line)) (when (< first-line (line-count page)) (let ((lines-to-draw (if (> first-line 0) (subseq (text-buffer page) first-line) (text-buffer page)))) (when (< line-count (length lines-to-draw)) (setq lines-to-draw (subseq lines-to-draw 0 line-count))) (dolist (line lines-to-draw) (screen-draw-line scr cursor line) (screen-newline scr 0)))))))
2,631
Common Lisp
.lisp
57
36.140351
80
0.580545
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
54284435d4ace69649dd0c5287b79cc6ddf581071ebdcf0c812f09f3ecb9d05b
13,683
[ -1 ]
13,684
file.lisp
foggynight_typewriter/src/file.lisp
(in-package #:typewriter) (defun read-page-from-file (filename) "Create a new page with its text buffer filled with the contents of the file named filename." (let ((page (make-instance 'page))) (with-open-file (stream filename :if-does-not-exist nil) (if stream (setf (text-buffer page) (loop for line = (read-line stream nil) while line collect (string-to-line line))) (setf (text-buffer page) '()))) page)) (defun write-page-to-file (filename page) "Write the text content of a page to a file named filename. Before writing, text content is stripped of trailing empty lines and the remaining lines are stripped of trailing whitespace." (let ((out-lines (text-buffer page))) ;; Remove trailing empty lines (let ((last-line -1) (walk 0)) (dolist (line out-lines) (unless (line-blank-p line) (setq last-line walk)) (incf walk)) (setq out-lines (subseq out-lines 0 (1+ last-line)))) ;; Remove trailing whitespace (dotimes (i (length out-lines)) (setf (nth i out-lines) (trim-trailing-whitespace (nth i out-lines)))) (with-open-file (stream filename :direction :output :if-exists :supersede) (dolist (line out-lines) (format stream "~A~%" line)))))
1,376
Common Lisp
.lisp
33
33.727273
78
0.620896
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
a88bbf27e875518c486668b10523f7e3949359967e6074bada00a6683915bd17
13,684
[ -1 ]
13,685
cursor.lisp
foggynight_typewriter/src/cursor.lisp
;; There are two categories of cursor in this program: text and screen cursors. ;; ;; Text cursors are used to identify the point in a page that will be affected ;; by user input. In this program the page moves rather than the cursor, so text ;; cursors do not move across the screen like traditional cursors. ;; ;; There is also a single screen cursor, which is handled by ncurses and moves ;; across the screen during draw operations, but is effectively always located ;; at the center of the screen from the user's perspective. (in-package #:typewriter) (defclass cursor () ((y :accessor y :initarg :y :documentation "Index of the line currently containing the cursor.") (x :accessor x :initarg :x :documentation "Index of the character within its containing line on which the cursor is located.")) (:documentation "Cursor class used to identify the location on a page that will be affected by user input.")) (defmethod move ((object cursor) direction &optional (n 1)) "Move a cursor in the direction specified by the direction keyword. Optionally, an argument may be passed for n, which represents the number of spaces to move the cursor in the given direction; the default is one." (flet ((multiply (x) (* n x))) (let* ((dir (crt:get-direction direction)) (offset (if (> n 1) (mapcar #'multiply dir) dir))) (setf (y object) (+ (y object) (car offset))) (when (< (y object) 0) (setf (y object) 0)) (setf (x object) (+ (x object) (cadr offset))) (when (< (x object) 0) (setf (x object) 0))))) (defmethod newline ((object cursor)) "Move a cursor to the beginning of the next line." (setf (y object) (1+ (y object))) (setf (x object) 0))
1,781
Common Lisp
.lisp
42
38.02381
80
0.683968
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
8d32e6f1ea575775070eb2a7b2db4b50463f31e13e5a73e280c6ac53e5636a4d
13,685
[ -1 ]
13,686
typewriter.asd
foggynight_typewriter/typewriter.asd
(asdf:defsystem #:typewriter :description "Typewriter inspired text editor." :author "Robert Coffey" :license "GPLv3" :version "1.0.5" :build-operation "asdf:program-op" :build-pathname "../typewriter" :depends-on (:croatoan) :entry-point "typewriter:main" :pathname "src/" :serial t :components ((:file "package") (:file "config") (:file "line") (:file "cursor") (:file "page") (:file "file") (:file "screen") (:file "main")))
561
Common Lisp
.asd
19
21.526316
49
0.548507
foggynight/typewriter
7
0
0
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
bf655002a9b67f53b008ad0bed8a0755c3e4ca29039f2f09b7e1d1fd18b4c7d6
13,686
[ -1 ]
13,709
package.lisp
yoelmatveyev_nutes/package.lisp
(defpackage :cl-nutes (:use :common-lisp) (:export st-width st-range st-power width range power tape-halted tape-position tape-counter tape-length tape-special create-tape one-step run-tape bmod 3n-split 3n-digits ternary-string ternary-print op-split op-gen trytes-chars chars-trytes eval-addr decode-op convert-minus ternary-input ternary-output set-addr prg-label-value prg-list-labels create-prg prg-var prg-3jmp prg-- prg-sub prg-add prg-swap prg-mov prg-sign prg-mul2 prg-mul3 prg-cmp prg-smul hello prg-factorial prg-io prg-fib-pair prg-movtrit prg-overadd prg-shift prg-width prg-invert prg-trit-count )) (in-package :cl-nutes)
860
Common Lisp
.lisp
58
9.965517
22
0.629537
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
77eb68b67c7427b63850f4446f03fd6c82f8c7a1728f831d46a689a4960299be
13,709
[ -1 ]
13,710
ternary-print.lisp
yoelmatveyev_nutes/ternary-print.lisp
(in-package :cl-nutes) ;; A couple of simple functions to represent numbers in balanced 3, 9 and 27 base. ;; Requires Unicode, because negative digits are overlined (perfectly works in Emacs) ;; Balanced version of modulo (defun bmod (n b) (let ((a (floor b 2))) (- (mod (+ n a) b) a))) ;; Getting the sequence of digits in 3^n balanced base (defun 3n-split (n &key (b 3)) (labels ((f1 (n &key b) (let ((bmod (bmod n b))) (unless (zerop n) (cons bmod (f1 (floor (- n bmod) b) :b b )))))) (if (zerop n) '(0) (f1 n :b b)))) ;; "Little-endian" version of the same (defun 3n-digits (n &key (b 3) (l nil)) (let* ((res (reverse (3n-split n :b b))) (ln (length res))) (when l (if (<= l ln) (setf res (subseq res (- ln l) ln)) (setf res (append (make-list (- l ln) :initial-element 0) res)))) res)) (defun ternary-list (n &optional (b 3)) (let ((b3 #("1̅" "0" "1")) (b9 #("4̅" "3̅" "2̅" "1̅" "0" "1" "2" "3" "4")) (b27 #("D̅" "C̅" "B̅" "A̅" "9̅" "8̅" "7̅" "6̅" "5̅" "4̅" "3̅" "2̅" "1̅" "0" "1" "2" "3" "4" "5" "6" "7" "8" "9" "A" "B" "C" "D" )) (digits nil)) (setf digits (3n-digits n :b b)) (case b (3 (mapcar (lambda (x) (elt b3 (+ x 1))) digits)) (9 (mapcar (lambda (x) (elt b9 (+ x 4))) digits)) (27 (mapcar (lambda (x) (elt b27 (+ x 13))) digits))))) ;; Produce a string representing a balanced 3,9 or 27-base number (defun ternary-string (n &key (b 27)(l nil)) (let* ((lst (ternary-list n b)) (ln (length lst))) (if l (if (< l ln) (setf lst (subseq lst (- ln l) ln)) (setf lst (append (make-list (- l ln) :initial-element "0") lst)))) (apply #'concatenate 'string lst))) ;; Print a number in 3,9 or 27 balanced base (defun ternary-print (n &key (b 27) (l nil) (stream t)) (format stream "~a" (ternary-string n :b b :l l)))
1,895
Common Lisp
.lisp
47
35.617021
132
0.547305
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
133844ed2b60e849e004b5998cffab3cbbb0624d25b25cb4ed6d30b7249dd57f
13,710
[ -1 ]
13,711
io.lisp
yoelmatveyev_nutes/io.lisp
(in-package :cl-nutes) ;; Interrupt and IO engine (defparameter op-pointer (expt 3 9)) (defparameter 3^6 (expt 3 6)) ;; Decode and encode operands for an interrupt (defun op-split (n &key (width 36)) (when (<= width 3) (setf width 3)) (coerce (3n-digits n :b (expt 3 (floor width 3)) :l 3) 'vector)) (defun op-gen (x &key (width 36)) (let* ((w (floor width 3)) (b (expt 3 w))) (setf x (mapcar (lambda (_) (coerce-width _ :width w)) x)) (reduce (lambda (h l)(+ (* h b) l)) (coerce x 'list)))) ;; Decode and encode strings of trytes (defun trytes-chars (n) (let ((str) (d (3n-split n :b 3^6))) (loop for x from 0 to (1- (length d)) do (if (nth x d) (progn (push (code-char (abs (nth x d))) str) (if (< (nth x d) 0)(push (code-char #x0305) str))))) (coerce str 'string))) (defun chars-trytes (str &key neg) (let ((codes)(res)) (setf codes (map 'list (lambda (x) (char-code x)) str)) (setf res (reduce (lambda (h l)(+ (* h 3^6) l)) codes))(if neg (- res) res))) ;; Find values of relative addresses on a tape (defun eval-addr (tape spl) (let ((pos (tape-position tape)) (l (tape-length tape))) (if (numberp spl) (elt (tape-vector tape) (mod (+ pos spl) l)) (map 'vector (lambda (x) (elt (tape-vector tape) (mod (+ pos x) l))) (coerce spl 'vector))))) ;; Decode opcodes (defun decode-op (n) (let ((split (op-split n :width (length (3n-split n)))) (flags) (dir (signum n))(param)(op)(halt)) (if (zerop dir) (setf halt t) (setf flags (cdr (mapcar (lambda (_) (* _ dir)) (3n-digits (elt split 0)))) param (* (elt split 1) dir) op (* (elt split 2) dir))) (coerce (list dir flags param op halt) 'vector))) ;; Input (defun convert-minus (s &key (b 27)) (let ((res '()) (sign (if (equal (subseq s 0 1) "-") (progn (setf s (subseq s 1 (length s))) -1) 1)) (flip 1)) (loop for x across s do (if (eq x #\|) (setf flip -1) (progn (push (* (parse-integer (string x) :radix 14) flip) res) (setf flip 1)))) (op-gen (reverse (mapcar (lambda (x)(* x sign)) res)) :width (* (log b 3)3 )))) ;; Input (unchecked) (defun ternary-input (&key (mode 0)) (let ((l (read-line))) (case mode (-1 (parse-integer l)) (-2 (convert-minus l :b 3)) (1 (convert-minus l :b 9)) (4 (convert-minus l :b 27)) (t (chars-trytes l))))) ;; Output (defun ternary-output (n &key (mode 0)) (case mode (-1 (print n)) (-2 (ternary-print n :b 3)) (1 (ternary-print n :b 9)) (4 (ternary-print n :b 27)) (t (format t "~a" (trytes-chars n)))) nil) ;; Set a tape cell at a relative address (defun set-addr (tape a v) (setf (aref (tape-vector tape)(mod (+ (tape-position tape) a)(tape-length tape)))v)) (defun run-io-engine (tape) (let* ((width (tape-width tape)) (length (tape-length tape)) (op (decode-op (tape-special tape))) (a1)(a2)(jmp) (dir (elt op 0)) (halt (elt op 4))) (unless halt (progn (setf jmp (mod (+ (tape-position tape) (* 3 dir)) length) (tape-position tape) jmp a1 (eval-addr tape (- dir)) a2 (eval-addr tape dir)) (multiple-value-bind (new-a1 new-a2 sign) (process-op (eval-addr tape a1)(eval-addr tape a2) op) (progn (set-addr tape a1 (coerce-width new-a1 :width width)) (set-addr tape a2 (coerce-width new-a2 :width width)) (setf (tape-halted tape) nil (tape-special tape) nil (tape-position tape) (mod (+ (tape-position tape) (eval-addr tape (+ (eval-addr tape 0) sign))) length))))))))
3,646
Common Lisp
.lisp
112
28.044643
86
0.583405
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
0ca06b7f13c7100ccbc7b496ddc3a784f4c1450feeb704ee3b6b6afd1a9007c8
13,711
[ -1 ]
13,712
instructions.lisp
yoelmatveyev_nutes/instructions.lisp
(in-package :cl-nutes) ;; Some common composed instructions ;; Note that this subtraction can be used with all possible combinations of sign-based branches, including the Subleq known to be Turing-complete ; jmp (-(b=b-a)) (defun prg-sub (prg a b &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg 'z1 'z2) (prg-- prg 'z1 'z1) (prg-- prg b 'z2) (prg-- prg 'z2 'z2 :jmp jmp :jlabel jlabel)) ; jmp (-(b=b+a)) (defun prg-add (prg a b &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg b 'z1) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel)) ; jmp (-a) (defun prg-sign (prg a &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel)) ; jmp(-(b=a)) (defun prg-mov (prg a b &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg b b) (prg-- prg 'z1 b) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel)) ; swap(a,b) (defun prg-swap (prg a b &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg b 'z2) (prg-- prg b b) (prg-- prg b 'z1) (prg-- prg a a) (prg-- prg a 'z2) (prg-- prg 'z1 'z1) (prg-- prg 'z2 'z2 :jmp jmp :jlabel jlabel)) ; jmp(-(a=a*2)) (defun prg-mul2 (prg a &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg a 'z1) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel)) ; jmp(-(a=a*3)) (defun prg-mul3 (prg a &key label jlabel (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg 'z1 'z2) (prg-- prg 'z1 'z2) (prg-- prg a 'z1) (prg-- prg 'z2 'z2) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel)) ; jmp(b-a) (defun prg-cmp (prg a b &key label (jlabel nil) (jmp 'jmp+3)) (prg-- prg a 'z1 :label label) (prg-- prg b 'z2) (prg-- prg 'z1 'z2) (prg-- prg 'z2 'z2) (prg-- prg 'z1 'z1 :jmp jmp :jlabel jlabel))
1,842
Common Lisp
.lisp
55
30.818182
145
0.605204
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
6bad1800f1194964a8bbc57f90aac0d7c2ffbfc11013911fc10773a051e54558
13,712
[ -1 ]
13,713
machine.lisp
yoelmatveyev_nutes/machine.lisp
(in-package :cl-nutes) ;; Defining the main structures: ; For the actual virtual machines ; The 'special' field is reserved for IO and other later extensions (defstruct tape width power range position flex vector length halted special counter ) ; For the assembled code (defstruct program id direction entry data code labels first last length ) ; Constants for standard tapes according to the system architecture (if (> (floor (log most-positive-fixnum 3)) 36) (defconstant st-width 36) (defconstant st-width 18)) (defconstant st-width 36) (defconstant st-power (expt 3 st-width)) (defconstant st-range (/ (1- st-power) 2)) (defparameter width st-width) ; Setting the default word width of flexible machines (defun create-tape (length &key (pos 0) (count 0) (flex nil) (width width)) (let ((p)(r)) (setf flex (if (> width 39) t flex) p (expt 3 width) r (/ (1- p) 2)) (make-tape :width width :power p :range r :position pos :flex flex :vector (if flex (make-array length) (if (<= width 9) (make-array length :element-type '(signed-byte 16)) (if (<= width 19) (make-array length :element-type '(signed-byte 32)) (make-array length :element-type 'fixnum)))) :length length :halted nil :special nil :counter count))) ;; We convert integers to balanced ternary numbers of a given range (defun coerce-width (x &key (width st-width)) (let* ((power (expt 3 width)) (range (/ (1- power) 2)) (n (mod x power))) (if (> n range) (- n power) n))) ;; Sign sum function. Not used in the machine, but may be useful elsewhere. (defun sign-sum (x y) (signum (+ (signum x)(signum y)))) ;; Our 'CPU' (declaim (inline one-step signum tape-position tape-vector tape-counter tape-halted tape-special mod)) (defun one-step (tape) (declare (optimize (speed 3) (safety 0)(debug 0))) (let ((l (tape-length tape)) (p (tape-position tape)) (v (tape-vector tape)) (power (tape-power tape)) (range (tape-range tape)) (p+ 0) (p- 0) (j 0) (new-jmp 0) (m+ 0) (m- 0) (a+ 0) (a- 0) (sub 0) (sign 0)) (declare (type fixnum l p p+ p- j new-jmp m+ m- a+ a- sub sign power range)) (if (plusp p) (if (= 1 (- l p)) (setf p+ (aref v 0) p- (aref v (1- p))) (setf p- (aref v (1- p)) p+ (aref v (1+ p)))) (setf p- (aref v (1- l)) p+ (aref v (1+ p)))) (setf j (mod (+ (aref v p) p) l) m+ (mod (+ p p+) l) m- (mod (+ p p-) l) a+ (aref v m+) a- (aref v m-) sub (let ((n (- a+ a-))) (if (> n range) (- n power) (if (< n (- range)) (+ power n) n))) sign (+ (signum a+)(signum a-))) (if (zerop sign) (setf new-jmp (aref v j)) (if (plusp sign) (setf new-jmp (if (plusp j) (if (= 1 (- l j)) (aref v 0) (aref v (1+ j))) (aref v (1+ j)))) (setf new-jmp (if (plusp j) (if (= 1 (- l j)) (aref v (1- j)) (aref v (1- j))) (aref v (1- l)))))) (incf (tape-counter tape)) (if (and (zerop new-jmp) (zerop sign)) (progn (setf (tape-halted tape) t (tape-special tape) (if (> (abs a-)(abs a+)) a- (if (< (abs a-)(abs a+)) a+ 0))) (run-io-engine tape)) (progn (setf (tape-position tape) (mod (+ p new-jmp) l) (aref v m+) sub (aref v m-) (- sub)) t)))) ;; Flexible word width version not optimized for fixnums (defun one-step-flex (tape) (declare (optimize (speed 3) (safety 0)(debug 0))) (let* ((l (tape-length tape)) (p (tape-position tape)) (v (tape-vector tape)) (power (tape-power tape)) (range (tape-range tape)) p+ p- j pj j- j+ j0 m- m+ a+ a- sub sign) (if (plusp p) (if (= 1 (- l p)) (setf p+ (aref v 0) p- (aref v (1- p))) (setf p- (aref v (1- p)) p+ (aref v (1+ p)))) (setf p- (aref v (1- l)) p+ (aref v (1+ p)))) (setf j (mod (+ (aref v p) p) l) m+ (mod (+ p p+) l) m- (mod (+ p p-) l) a+ (aref v m+) a- (aref v m-) sub (let ((n (- a+ a-))) (if (> n range) (- n power) (if (< n (- range)) (+ power n) n))) sign (+ (signum a+)(signum a-))) (if (zerop sign) (setf new-jmp (aref v j)) (if (plusp sign) (setf new-jmp (if (plusp j) (if (= 1 (- l j)) (aref v 0) (aref v (1+ j))) (aref v (1+ j)))) (setf new-jmp (if (plusp j) (if (= 1 (- l j)) (aref v (1- j)) (aref v (1- j))) (aref v (1- l)))))) (incf (tape-counter tape)) (if (and (zerop new-jmp) (zerop sign)) (progn (setf (tape-halted tape) t (tape-special tape) (if (> (abs a-)(abs a+)) a- (if (< (abs a-)(abs a+)) a+ 0))) (run-io-engine tape)) (progn (setf (tape-position tape) (mod (+ p new-jmp) l) (aref v m+) sub (aref v m-) (- sub)) t)))) ;; Write your program using the tools provides by instructions.lisp and feed it to the tape (defun load-tape (tape prg &key (offset 0) (middle nil)) (let ((list)) (if middle (setf offset (+ (floor (/ (tape-length tape) 2)) offset))) (if (listp prg) (setf list prg) (setf list (append (program-data prg) (program-code prg)) (tape-position tape) (mod offset (tape-length tape)) offset (+ offset (program-first prg)))) (loop for p from 0 to (1- (length list)) do (setf (elt (tape-vector tape) (mod (+ p offset) (tape-length tape))) (coerce-width (pop list) :width (tape-width tape)))))) ;; Running our tape ; By a certain number of steps (defun step-tape (tape &optional (n 1)) (if (< n 1) (setf n 1)) (loop for x from 1 to n unless (tape-halted tape) do (if (tape-flex tape) (one-step-flex tape) (one-step tape)))) ; Indefinitely (defun run-tape (tape) (if (tape-flex tape) (loop do (one-step-flex tape) while (not (tape-halted tape))) (loop do (one-step tape) while (not (tape-halted tape)))))
5,990
Common Lisp
.lisp
216
23.203704
102
0.565263
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
d482f7ab5b42bcce0baa2f836bfa006fb65fdf3e0b86b4574b475e1815d98fc7
13,713
[ -1 ]
13,714
opcodes.lisp
yoelmatveyev_nutes/opcodes.lisp
(in-package :cl-nutes) ;; Process opcodes (defun process-op (a1 a2 de-op) (let ((param (elt de-op 2)) (op (elt de-op 3)) (sign 0)) (case op (1 (ternary-output a1 :mode param)) (0 (ternary-output a1 :mode param) (setf a1 (ternary-input :mode param))) (-1 (setf a1 (ternary-input :mode param)))) (values a1 a2 sign)))
351
Common Lisp
.lisp
12
25.333333
49
0.617211
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
22893f98e2d4a31e05445b2133cf8db78a209615dccfb42ca9e679ffb01e3e73
13,714
[ -1 ]
13,715
examples.lisp
yoelmatveyev_nutes/examples.lisp
(in-package :cl-nutes) ;;; Some practical examples of Nutes programs ;; Example of usage: ; (defparameter prg1 (create-prg)) ; (hello prg1) ; (defparameter tape1 (create-tape (expt 3 6)))(load-tape tape1 prg1) ; (run-tape tape1) ; Slow multiplication by repeating addition, A must be positive ; b=a*b (defun prg-smul (prg a b &key label (jmp 'jmp+3)) (let ((loop (gensym))(next (gensym))(end (gensym))) (prg-mov prg b 'z3 :label label) (prg-mov prg a 'z4) (prg-sub prg 'v=1 'z4 :label loop :jmp (list next end end)) (prg-add prg 'z3 b :label next) (prg-- prg 'z1 'z1 :jmp loop) (prg-- prg 'z3 'z3 :label end :jmp jmp))) ; Find the nth pair of consequent Fibonacci numbers ; One of the most natural and efficient operations in our system (defun prg-fib-pair (prg n res1 res2 &key label (jmp 'jmp+3)) (let ((loop (gensym))(next (gensym))) (prg-- prg 'v=-1 res1 :label label) (prg-- prg res1 'z3 :label loop) (prg-- prg res2 'z3) (prg-add prg 'v=-1 n :jmp (list loop loop next)) (prg-- prg 'z3 'z3 :label next :jmp jmp))) ;; Factorial (defun prg-factorial (prg n res &key label (jmp 'jmp+3)) (let ((loop (gensym))(end (gensym))(next (gensym))) (prg-mov prg n res :label label) (prg-sign prg n :jmp (list loop end end)) (prg-add prg 'v=-1 n :label loop :jmp (list next end end)) (prg-smul prg n res :label next :jmp loop) (prg-sign prg 'z1 :label end :jmp jmp))) ;; Basic input and "Hello World", requires width>=36 (defun hello (prg) (prg-var prg 'hello (chars-trytes "Hello ")) (prg-var prg 'world (chars-trytes "World,")) (prg-var prg 'name (chars-trytes "Name? ")) (prg-var prg 'io 9) (prg-var prg 'out 10) (prg-io prg 'io 'name 0) (prg-io prg 'out 'hello 0) (prg-io prg 'out 'world 0) (prg-io prg 'out 'name 0)) ;; Determine the highest trit of the first operand, left-shift both operands and add the resulting trit to the second operand. This is a basic construction block for right shifts, tritwise operations and double-operand arithmetics. (defun prg-movtrit (prg l h &key (label (gensym)) (jmp 'jmp+3)) (let ((j- (gensym)) (j0 (gensym)) (j+ (gensym))) (prg-- prg l 'z1 :label label) (prg-- prg 'z1 'z2) (prg-- prg 'z1 'z2) (prg-- prg l 'z1 :jmp (list j- (jmp-r prg 3) j+)) (prg-- prg 'z1 'z2 :jmp (list j- j0 j+)) (prg-- prg 'v=-1 'z3 :label j- :jmp j0) (prg-- prg 'v=1 'z3 :label j+) (prg-- prg 'z1 'z1 :label j0) (prg-- prg 'z2 'z2) (prg-mul3 prg h) (prg-- prg h 'z3) (prg-- prg 'z3 'z3 :jmp jmp))) ;; Add 2 operands, shift the third operand to the left and add the overflow sign to it. (defun prg-overadd (prg a b h &key (label (gensym)) (jmp 'jmp+3)) (let ((j- (gensym)) (j0 (gensym)) (j+ (gensym))) (prg-- prg a 'z1 :label label) (prg-- prg 'z1 'z2) (prg-- prg b 'z1 :jmp (list j0 (jmp-r prg 3) j0)) (prg-- prg 'z1 'z2 :jmp (list j- j0 j+)) (prg-- prg 'v=-1 'z3 :label j- :jmp j0) (prg-- prg 'v=1 'z3 :label j+ :jmp j0) (prg-- prg 'z1 'z1 :label j0) (prg-- prg 'z2 'z2) (prg-mul3 prg h) (prg-- prg h 'z3) (prg-- prg 'z3 'z3 :jmp jmp))) (defun prg-shift (prg a n &key (label (gensym)) (jmp 'jmp+3)) (let ((loop (gensym)) (out (gensym)) (movtrit (gensym))) (prg-var prg 'v=36 -36) (prg-- prg 'v=36 'z4 :label label) (prg-- prg n 'z4) (prg-- prg 'v=1 'z1) (prg-- prg 'z1 'z4) (prg-- prg 'z1 'z1) (prg-var prg 'v=-1 -1) (prg-- prg 'v=-1 'z1 :label loop) (prg-- prg 'z1 'z4) (prg-- prg 'z1 'z1 :jmp (list movtrit out out)) (prg-movtrit prg a 'z5 :label movtrit :jmp loop) (prg-- prg 'z4 'z4 :label out) (prg-- prg a a) (prg-- prg 'z5 'z1) (prg-- prg 'z1 a) (prg-- prg 'z5 'z5) (prg-- prg 'z1 'z1 :jmp jmp))) ;; Define the tape's width programmatically. Normally it's predefined. (defun prg-width (prg) (let ((loop (gensym))(end (gensym))) (prg-- prg 'width 'width) (prg-- prg 'v=1 'z3) (prg-add prg 'v=1 'width :label loop) (prg-mul3 prg 'z3 :jmp (list end end loop)) (prg-- prg 'z3 'z3 :label end))) ;; Invert the first operand rigth to left and move the result to the second operand (defun prg-invert (prg a b &key (label (gensym)) (jmp 'jmp+3)) (let ((loop (gensym)) (end (gensym)) (next (gensym)) (j- (gensym)) (j0 (gensym)) (j+ (gensym))) (prg-- prg 'width 'z4 :label label) (prg-- prg 'v=1 'z5) (prg-- prg 'v=-1 'z6) (prg-- prg a 'z1 :label loop) (prg-- prg 'z1 'z2) (prg-- prg 'z1 'z2) (prg-- prg a 'z1 :jmp (list j- (jmp-r prg 3) j+)) (prg-- prg 'z1 'z2 :jmp (list j- j0 j+)) (prg-- prg 'z5 'z3 :label j-) (prg-- prg b 'z3) (prg-- prg 'z3 'z3 :jmp j0) (prg-- prg 'z6 'z3 :label j+) (prg-- prg b 'z3) (prg-- prg 'z3 'z3) (prg-- prg 'z1 'z1 :label j0) (prg-- prg 'z2 'z2) (prg-add prg 'v=1 'z4 :jmp (list end end next)) (prg-mul3 prg 'z5 :jmp next) (prg-- prg 'z6 'z6) (prg-- prg 'z5 'z6 :jmp loop) (prg-- prg 'z1 'z1 :label end :jmp jmp))) (defun prg-trit-count (prg a b &key label (jmp 'jmp+3)) (let ((out (gensym)) (j- (gensym)) (j0 (gensym)) (j+ (gensym)) (j3 (gensym))) (prg-- prg a 'z1 :label label :jmp (list j3 out j3)) (prg-- prg 'z1 'z2 :jlabel j3) (prg-- prg 'z1 'z2) (prg-- prg a 'z1 :jmp (list j- j3 j+)) (prg-- prg 'z1 'z2 :jmp (list j- j0 j+)) (prg-- prg 'v=-1 'z3 :label j- :jmp j0) (prg-- prg 'v=1 'z3 :label j+) (prg-- prg 'z1 'z1 :label j0) (prg-- prg 'z2 'z2) (prg-- prg b 'z3) (prg-- prg 'z3 'z3 :jmp label) (prg-- prg 'z3 'z3 :label out :jmp jmp)))
5,615
Common Lisp
.lisp
154
32.662338
231
0.589069
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
4fe07d8cf41ecfce9a5c61a8fdb0dfe4b264da3ae365184f6d564641414a839e
13,715
[ -1 ]
13,716
asm.lisp
yoelmatveyev_nutes/asm.lisp
(in-package :cl-nutes) ;;; Rudimentary assembler emulating a conventional computer ;; Checking whether an operand affects a jump or an instruction (defun modifp (addr op) (if (< (abs (- addr op)) 2) t)) (defun find-addr (prg x) (let ((addr x)) (if (symbolp x) (setf addr (cadr (gethash x (program-labels prg)))) x))) ;; Generate a single instruction with an emulated absolute address ;; Perform basic checks for halting and self-modification (defun one-inst (addr a b j) (let ((lst)) (setf a (- a addr) b (- b addr) j (- j addr) lst (list a j b)) (values lst (remove nil (list (if (and (= b a) (zerop j)) 'halt) (if (or (modifp addr a) (modifp addr b)) 'op-modif) (if (or (= j a) (= j b)) 'jmp-addr-modif) (if (or (modifp j a) (modifp j b)) 'jmps-modif) (if (= a b) 'zero)))))) ;; Add an emulated absolute jump for an instruction to the data section of a program (defun prg-3jmp (prg addr jmp &key (label nil) (ignore nil) (sign nil)) (let ((jmpaddr (- (program-first prg) 2))) (setf addr (find-addr prg addr)) (if (and (not ignore) (not (gethash label (program-labels prg)))) (progn (if label (setf (gethash label (program-labels prg)) (if sign (list 'jmp jmpaddr addr sign) (list 'jmp jmpaddr addr)))) (if (not (listp jmp)) (setf jmp (make-list 3 :initial-element (find-addr prg jmp)))) (unless sign (setf (program-data prg) ; (append jmp (program-data prg)) (reduce #'cons (mapcar (lambda (_) (- (find-addr prg _) addr)) jmp) :initial-value (program-data prg) :from-end t) (program-length prg) (+ (program-length prg) 3) (program-first prg) (- (program-first prg) 3))) (if sign (setf (program-data prg) (reduce #'cons (mapcar (lambda (_) (- (find-addr prg _) addr)) jmp) :initial-value (program-data prg) :from-end t) (program-length prg) (+ (program-length prg) 3) (program-first prg) (- (program-first prg) 3))))) jmpaddr)) (defun prg-label-value (prg value) (let ((cadr (cadr (gethash value (program-labels prg))))) (if (< cadr -1) (nth (- cadr (program-first prg)) (program-data prg)) (nth (1+ cadr) (program-code prg))))) ;; Add a variable (defun prg-var (prg label value &key (insert nil) (set nil)) (if (symbolp value) (setf value (prg-label-value prg value))) (if (or (not (gethash label (program-labels prg))) (eq label nil)) (progn (if insert (setf (program-code prg) (append (program-code prg)(list value)) (program-last prg) (1+ (program-last prg))) (setf (program-data prg) (append (list value) (program-data prg)) (program-first prg) (1- (program-first prg)))) (if label (setf (gethash label (program-labels prg)) (list 'var (if insert (program-last prg) (program-first prg))))) (setf (program-length prg) (1+ (program-length prg))))) (if set (setf (nth (- (cadr (gethash label (program-labels prg))) (program-first prg)) (program-data prg)) value)) label) ;; Check if a jump label exists, mark it as pending if not ;; Temporarity set the pointer to it to the next instruction (defun chk-jmp (prg jmp addr) (let ((labels (program-labels prg)) (next (+ 5 (program-last prg)))) (if (or (symbolp jmp)(numberp jmp)) (setf jmp (make-list 3 :initial-element jmp))) (loop for x from 0 to 2 do (let ((j (nth x jmp))) (if (symbolp j) (cond ((not (gethash j labels)) (setf (gethash j labels) (list '? (make-hash-table))) (let ((h (cadr (gethash j labels)))) (setf (gethash addr h) (make-list 3 :initial-element '+)) (setf (nth x (gethash addr h)) '?) ) (setf (nth x jmp) next)) ((eql (car (gethash j labels)) '?) (let ((h (cadr (gethash j labels)))) (if (not (gethash addr h)) (setf (gethash addr h) (make-list 3 :initial-element '+))) (setf (nth x (gethash addr h)) '?) ) (setf (nth x jmp) next)))))) jmp)) ;; When a label appears, set all it previous occurences to the proper address (defun chk-label (prg label addr newjmp) (let ((length (length (program-data prg)))) (if (eql (car (gethash label (program-labels prg))) '?) (let ((jaddr) (ad-ht (cadr (gethash label (program-labels prg))))) (loop for a being each hash-key of ad-ht using (hash-value v) do (loop for n from 0 to 2 do (setf jaddr (nth (1+ a) (program-code prg))) (if (eql (nth n v) '?) (setf (nth (+ length jaddr n a) (program-data prg)) (- addr a))))))) (setf (gethash label (program-labels prg)) (list 'inst addr newjmp)))) ;; Recalculate a relative address for programming. (defun jmp-r (prg n) (+ (program-last prg) 2 n)) ;; Add one instruction to a program, add a 3-jump to the data if needed ;; Jump to the next instruction by default (defun prg-- (prg a b &key (jmp 'jmp+3) (forbid '('op-modif 'jmp-addr-modif)) label jlabel zero) (let* ((addr (+ (program-last prg) 2)) (newjmp) (abs-jump nil) (nj nil) (jlabel-existed nil)) (if (and (symbolp a) (not (gethash a (program-labels prg)))) (prg-var prg a 0)) (setf a (find-addr prg a)) (if (and (symbolp b) (not (gethash b (program-labels prg)))) (prg-var prg b 0)) (setf b (find-addr prg b)) (if (gethash jlabel (program-labels prg)) (setf jlabel-existed t)) (if (not (equal (car (gethash jmp (program-labels prg))) 'jmp)) (if jlabel-existed (setf newjmp (caddr (gethash jlabel (program-labels prg)))) (setf newjmp (- (program-first prg) 2))) (setf newjmp (cadr (gethash jmp (program-labels prg))) nj t)) (multiple-value-bind (inst flags) (one-inst addr a b newjmp) (if (not (intersection forbid flags)) (progn (setf (program-code prg) (append (program-code prg) '(0 0 0))) (if label (chk-label prg label addr newjmp)) (if (eq label jmp) (setf zero t)) (setf jmp (chk-jmp prg jmp addr)) (if (or (symbolp jmp)(numberp jmp)) (setf jmp (make-list 3 :initial-element (find-addr prg jmp))) (setf jmp (mapcar (lambda (_) (find-addr prg _)) jmp))) (if zero (progn (setf (cadr inst) 0) (if label (gethash label (program-labels prg)) (list 'inst addr addr))) (setf jmp (- (if jlabel (if (setf abs-jump (prg-3jmp prg addr jmp :label jlabel :ignore nj)) abs-jump (caddr (gethash jlabel (program-labels prg)))) (prg-3jmp prg addr jmp :ignore nj)) addr))) (loop for n from 0 to 2 do (let ((length (length (program-code prg)))) (setf (nth (+ length n -3) (program-code prg)) (nth n inst)))) (setf (program-last prg)(1+ addr) (program-length prg) (- (program-last prg)(program-first prg) -1))))))) ;; Set an IO environment (defun prg-io (prg op a1 a2 &key label (jmp 'jmp+3)) (prg-- prg op 'v=-1 :zero t :label label) (prg-- prg a1 a2 :jmp jmp)) ;; List all labels (defun prg-list-labels (prg) (loop for a being each hash-key of (program-labels prg) using (hash-value v) do (format t "~a->~a~&" a v) (if (eq (car v) '?) (loop for a2 being each hash-key of (cadr v) using (hash-value v2) do (format t " ~a->~a~&" a2 v2))))) ;; Create a program with the common +3 unconditional jump and standard variables preset (defun create-prg (&key (width 36)) (let ((prg (make-program :direction 1 :first -1 :last -2 :entry 0 :length 0 :labels (make-hash-table)))) ; Default jump to the next instruction to the right (prg-3jmp prg 0 3 :label 'jmp+3) ; Axillary variables for decrement, increment and tritwise operations (prg-var prg 'width width) (prg-var prg 'v=1 1) (prg-var prg 'v=-1 -1) ; 6 default placeholder variables for composing basic instructions ; Should alway be reset to zero after using them (mapcar (lambda (_) (prg-var prg _ 0)) (list 'z1 'z2 'z3 'z4 'z5 'z6)) prg))
8,292
Common Lisp
.lisp
245
28.334694
88
0.602875
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
e26d91a5f1b7b194aa8861eb2cd945d0d545f9a02f7d962a799f6ff3404f5d73
13,716
[ -1 ]
13,717
nutes.asd
yoelmatveyev_nutes/nutes.asd
(defsystem :nutes :name "Nutes" :version "0.0.6" :maintainer "Yoel Matveyev" :author "Yoel Matveyev" :licence "GNU General Public License v3.0" :description "OISC ternary virtual machine" :long-description "A signwise symmetrical balanced ternary base virtual machine with only one instruction" :components ((:file "package") (:file "machine") (:file "ternary-print") (:file "opcodes") (:file "io") (:file "asm") (:file "instructions") (:file "examples")))
537
Common Lisp
.asd
16
27.5625
108
0.637236
yoelmatveyev/nutes
7
2
1
GPL-3.0
9/19/2024, 11:27:05 AM (Europe/Amsterdam)
a50806251d209066012e138d767372a2ed426b2b8a33ccf1e8479b3f4200f02c
13,717
[ -1 ]
13,741
genetic-programming.asd
gdobbins_genetic-programming/genetic-programming.asd
(in-package :asdf-user) (defsystem "genetic-programming" :description "genetic-programming: genetic programming algorithms and other stochastic search methods." :version "0.0.1" :author "Graham Dobbins <[email protected]>" :licence "GPLv3" :depends-on ("alexandria" "lparallel") :components ((:file "gene")))
334
Common Lisp
.asd
8
37.625
107
0.72
gdobbins/genetic-programming
6
4
0
GPL-3.0
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
8ae1b70f4c9e4fce29e6cc45918d590c083ac6fbbe28d34d0255433e8c8ff19c
13,741
[ -1 ]
13,757
main.lisp
TheLostLambda_astonish/src/main.lisp
(defpackage astonish (:use :cl :alexandria) (:export :load-forms-from-file :select-conses :macroexpand-select)) (in-package :astonish) ;;; Public Functions ----------------------------------------------------------- ;; FIXME: Read things like defpackage and load first, run them, switch package, ;; then read the rest of the file. This way symbols can always be found by the ;; reader and are read into the correct packages (defun load-forms-from-file (file &optional package) "Read forms from a lisp file without any evaluation" (let ((current-package (or package *package*))) (uiop:with-safe-io-syntax (:package current-package) (uiop:read-file-forms (lisp-file file))))) (defun select-conses (path forms) "Given a path (a list of car's) and list of forms, return all matching conses. The second return value is the same selection, but inverted" (destructuring-bind (x &rest xs) path (let ((selected (filter-conses-by-car x forms))) (if (null xs) (values selected (cons-difference forms selected)) (select-conses xs (apply #'append selected)))))) (defun macroexpand-select (macros form) "Recursively expand all occurrences of select macros" (map-inodes (lambda (n) (if (find (car n) macros) (macroexpand n) n)) form)) ;;; Private Helper Functions --------------------------------------------------- (defun filter-conses-by-car (car forms) "Filter forms so that only ones with the specified car remain" (remove-if-not (lambda (x) (and (listp x) (string= car (car x)))) forms)) (defun map-inodes (function form) "Maps the given function over all the inner nodes of a tree" (if (proper-list-p form) (funcall function (mapcar (lambda (n) (map-inodes function n)) form)) form)) (defun cons-difference (a b) "Like set-difference, but filters for conses and preserves order" (remove-if (lambda (x) (or (find x b) (atom x))) a)) (defun lisp-file (file) "Adds a .lisp extension to pathnames without an extension" (if (pathname-type file) file (make-pathname :type "lisp" :defaults file)))
2,090
Common Lisp
.lisp
41
47.341463
80
0.67451
TheLostLambda/astonish
6
0
0
GPL-3.0
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
dd87fc1e60fe1910664e9767c4955f8ef537fe3335fc7870f5f4cab85c022b1a
13,757
[ -1 ]
13,758
main.lisp
TheLostLambda_astonish/tests/main.lisp
(defpackage astonish/tests/main (:use :cl :astonish :rove)) (in-package :astonish/tests/main) ;; NOTE: To run this test file, execute `(asdf:test-system :astonish)' in your Lisp. (deftest load-forms-from-file-test (testing "should be 10 top-level forms" (ok (= 10 (length (load-forms-from-file #P"tests/data/pal-picker-test")))))) (deftest select-conses-test (let ((all-forms (load-forms-from-file #P"tests/data/pal-picker-test" #.*package*))) (testing "should work for nested forms" (ok (equal '((PLAY-FETCH "Cat") (PLAY-FETCH "Fish") (PLAY-FETCH "Rabbit")(PLAY-FETCH "Bird")) (select-conses '(test is-true play-fetch) all-forms))) (ok (equal '((PET "Fish")) (nth-value 1 (select-conses '(test is-true play-fetch) all-forms))))))) (deftest macroexpand-select-test (defmacro three (x) `(,x ,x ,x)) (defmacro rev (&body body) (reverse body)) (let ((test-form '(defun wacky-stuff (maybe?) (if maybe? (loop :repeat 10 :collect '(three "cats")) (rev '(1 2 3) cadr)))) (expected-form '(defun wacky-stuff (maybe?) (if maybe? (loop :repeat 10 :collect '("cats" "cats" "cats")) (cadr '(1 2 3)))))) (testing "expands some, not all, macros" (ok (equal expected-form (macroexpand-select '(three rev) test-form))))))
1,458
Common Lisp
.lisp
28
42.178571
88
0.575736
TheLostLambda/astonish
6
0
0
GPL-3.0
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
236bae70d0db9a7d1c01e6497a60da5450768997e19780a2b02966850eabc3d1
13,758
[ -1 ]
13,759
pal-picker-test.lisp
TheLostLambda_astonish/tests/data/pal-picker-test.lisp
;; Ensures that pal-picker.lisp and the testing library are always loaded (eval-when (:compile-toplevel :load-toplevel :execute) (load "pal-picker") (ql:quickload :fiveam)) ;; Defines the testing package with symbols from pal-picker and FiveAM in scope ;; The `run-tests` function is exported for use by both the user and test-runner (defpackage :pal-picker-test (:use :cl :fiveam :pal-picker) (:export :run-tests)) ;; Enter the testing package (in-package :pal-picker-test) ;; Define and enter a new FiveAM test-suite (def-suite pal-picker-suite) (in-suite pal-picker-suite) (test pick-a-pal "Maps personality traits to fitting pets" (is (string= (pal-picker :lazy) "Cat")) (is (string= (pal-picker :energetic) "Dog")) (is (string= (pal-picker :quiet) "Fish")) (is (string= (pal-picker :hungry) "Rabbit")) (is (string= (pal-picker :talkative) "Bird")) (is (string= (pal-picker :fireproof) "I don't know... A dragon?"))) (test natural-habitat "Maps pet weights to habitat sizes" (is (eql (habitat-fitter 100) :massive)) (is (eql (habitat-fitter 40) :massive)) (is (eql (habitat-fitter 39) :large)) (is (eql (habitat-fitter 20) :large)) (is (eql (habitat-fitter 19) :medium)) (is (eql (habitat-fitter 10) :medium)) (is (eql (habitat-fitter 9) :small)) (is (eql (habitat-fitter 1) :small)) (is (eql (habitat-fitter 0) :just-your-imagination)) (is (eql (habitat-fitter -5) :just-your-imagination))) (test we-feast "Determines whether the food-bowl needs refilling from its fullness" (is (string= (feeding-time-p 10) "It's feeding time!")) (is (string= (feeding-time-p 36) "All is well.")) (is (string= (feeding-time-p 74) "All is well.")) (is (string= (feeding-time-p 3) "It's feeding time!")) (is (string= (feeding-time-p 90) "All is well."))) (test code-of-conduct "Is the given action unsuitable for the given pet?" (is-false (pet "Cat")) (is-false (pet "Dog")) (is-true (pet "Fish")) (is-false (pet "Rabbit")) (is-false (pet "Bird")) (is-true (play-fetch "Cat")) (is-false (play-fetch "Dog")) (is-true (play-fetch "Fish")) (is-true (play-fetch "Rabbit")) (is-true (play-fetch "Bird"))) ;; Either provides human-readable results to the user or machine-readable ;; results to the test runner. The default upon calling `(run-tests)` is to ;; explain the results in a human-readable way (defun run-tests (&optional (explain t)) (let ((tests (run 'pal-picker-suite))) ; Run the tests once (if explain (explain! tests) tests))) ; Optionally explain the results
2,541
Common Lisp
.lisp
55
43.654545
83
0.691562
TheLostLambda/astonish
6
0
0
GPL-3.0
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
b6dd2714b3efc47bad720718281f3f2fef737079a16fd06be444169d36635091
13,759
[ 36376 ]
13,760
astonish.asd
TheLostLambda_astonish/astonish.asd
(defsystem "astonish" :version "0.1.0" :author "Brooks J Rady <[email protected]>" :license "GPLv3" :depends-on ("uiop" "alexandria") :components ((:module "src" :components ((:file "main")))) :description "A small library for querying and manipulating Lisp ASTs" :in-order-to ((test-op (test-op "astonish/tests")))) (defsystem "astonish/tests" :author "Brooks J Rady <[email protected]>" :license "GPLv3" :depends-on ("astonish" "rove") :components ((:module "tests" :components ((:file "main")))) :description "Test system for astonish" :perform (test-op (op c) (symbol-call :rove :run c)))
701
Common Lisp
.asd
20
28.75
72
0.607353
TheLostLambda/astonish
6
0
0
GPL-3.0
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
e260d4e02d90837fd9ed25f73cf5d29b42300b89ed9a5794aa6da5f660a86b98
13,760
[ -1 ]
13,779
build.lisp
rpav_spell-and-dagger/build.lisp
;;; build-it.lisp --- script for making SBCL binaries for Linux and ;;; MS Windows using only Free Software (GNU/Linux and ;;; Wine) ;;; (C) Copyright 2011-2016 by David O'Toole <[email protected]> ;;; (C) Copyright 2011-2016 by David O'Toole <[email protected]> ;; ;; Permission is hereby granted, free of charge, to any person obtaining ;; a copy of this software and associated documentation files (the ;; "Software"), to deal in the Software without restriction, including ;; without limitation the rights to use, copy, modify, merge, publish, ;; distribute, sublicense, and/or sell copies of the Software, and to ;; permit persons to whom the Software is furnished to do so, subject to ;; the following conditions: ;; ;; The above copyright notice and this permission notice shall be ;; included in all copies or substantial portions of the Software. ;; ;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE ;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION ;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION ;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ;;; Note, I modified this of course to build spell-and-dagger. (defpackage :build (:use #:cl) (:export *name* *system* *binary* *startup*)) (in-package :build) #-quicklisp (load #P"~/quicklisp/setup.lisp") (require 'sb-posix) (setf sb-impl::*default-external-format* :utf-8) (defun argument (name) (let* ((args sb-ext:*posix-argv*) (index (position name args :test 'equal)) (value (when (and (numberp index) (< index (length args))) (nth (1+ index) args)))) value)) (defparameter *name* (argument "--name")) (defparameter *binary* (or (argument "--binary") #+win32 (concatenate 'string *name* ".exe") #+linux (concatenate 'string *name* ".bin"))) (defparameter *system* (or (argument "--system") (intern *name* :keyword))) (ql:quickload *system*) (defparameter *startup* (or (argument "--startup") (concatenate 'string (string-upcase *name*) "::" (string-upcase *name*)))) (sb-ext:save-lisp-and-die *binary* :toplevel (lambda () (sdl2:make-this-thread-main (lambda () (sb-ext:disable-debugger) (setup-library-paths) (gk:gk-init) (funcall (read-from-string *startup*)) 0))) :executable t)
2,807
Common Lisp
.lisp
61
39.213115
80
0.6355
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
9dcd726d0682a785c44629df843c39b54bdb6694b47f3145d732de734047029a
13,779
[ -1 ]
13,780
ui.lisp
rpav_spell-and-dagger/src/ui.lisp
;;; This was also taken conceptually from how I've done things elsewhere. (in-package :game) ;; UI (defclass ui () ((visible :initform nil :accessor ui-visible) (children :initform (make-hash-table)))) (defmethod ui-add ((ui ui) &rest children) (with-slots ((c children)) ui (loop for child in children do (setf (gethash child c) t)))) (defmethod ui-remove ((ui ui) &rest children) (with-slots ((c children)) ui (loop for child in children do (remhash child c)))) (defmethod ui-clear ((ui ui)) (with-slots ((c children)) ui (clrhash c))) (defmethod draw ((ui ui) lists m) (with-slots ((c children)) ui (loop for child being each hash-key in c do (draw child lists m)))) ;; SCREEN (defclass screen (ui) ()) (defmethod screen-opening ((s screen))) (defmethod screen-closing ((s screen))) (defmethod (setf ui-visible) (v (s screen)) (call-next-method) (if v (unless (and (current-screen) (eq s (current-screen))) (screen-opening s) (setf (current-screen) s)) (when (and (current-screen) (eq s (current-screen))) (screen-closing s) (setf (current-screen) nil))))
1,181
Common Lisp
.lisp
34
30.147059
73
0.646127
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
5db63c2c30941219fcb5456332af0a5b15c9cb2074a65f110be2a7115469577f
13,780
[ -1 ]
13,781
package.lisp
rpav_spell-and-dagger/src/package.lisp
(in-package :cl-user) (defpackage :build (:use #:cl) (:export *name* *system* *binary* *startup*)) (in-package :build) (defvar *name* nil) (defvar *system* nil) (defvar *binary* nil) (defvar *startup* nil) (in-package :cl-user) (defpackage+-1:defpackage+ :game (:use #:cl #:alexandria #:util.rpav-1) (:import-except #:gk #:create #:process #:destroy) (:import-from #:kit.sdl2 #:define-start-function) (:export #:run)) (in-package :game) ;; Variables
470
Common Lisp
.lisp
17
25.470588
52
0.675615
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
e5b2839016999bf43c0e59a75cbf147f3b5b65364ff58cacb93d674191f391dd
13,781
[ -1 ]
13,782
util.lisp
rpav_spell-and-dagger/src/util.lisp
;;; Some of this may have been scraped from elsewhere (in-package :game) (defvar +time-units+ (coerce internal-time-units-per-second 'float)) (declaim (inline time-to-float)) (declaim (ftype (function (integer) float) time-to-float)) (defun time-to-float (time) (/ time +time-units+)) (defun current-time () (time-to-float (get-internal-real-time))) ;; Box shortcut (defmacro with-box ((x0 y0 x1 y1) box &body body) (once-only (box) `(let* ((,x0 (vx (car ,box))) (,y0 (vy (car ,box))) (,x1 (+ ,x0 (vx (cdr ,box)))) (,y1 (+ ,y0 (vy (cdr ,box))))) ,@body))) (defmacro with-int-box ((x0 y0 x1 y1) box &body body) (once-only (box) `(let* ((,x0 (truncate (vx (car ,box)))) (,y0 (truncate (vy (car ,box)))) (,x1 (truncate (+ ,x0 (vx (cdr ,box))))) (,y1 (truncate (+ ,y0 (vy (cdr ,box)))))) ,@body))) (defmacro with-point ((x y) point &body body) (once-only (point) `(let ((,x (vx ,point)) (,y (vy ,point))) ,@body))) (declaim (inline box box/16)) (defun box (x0 y0 x1 y1) (cons (gk-vec2 x0 y0) (gk-vec2 x1 y1))) (defun box/16 (x0 y0 x1 y1) "Like BOX, but scaled to 0..16 so pixels may be specified instead of 0..1.0" (box (/ x0 16.0) (/ y0 16.0) (/ x1 16.0) (/ y1 16.0))) (defun box+ (box offset) (incf (vx (car box)) (vx offset)) (incf (vy (car box)) (vy offset))) (defun box- (box offset) (decf (vx (car box)) (vx offset)) (decf (vy (car box)) (vy offset))) (defun box-intersect-p (box-a box-b offs-a offs-b) (with-box (ax0 ay0 ax1 ay1) box-a (when offs-a (incf ax0 (vx offs-a)) (incf ay0 (vy offs-a)) (incf ax1 (vx offs-a)) (incf ay1 (vy offs-a))) (with-box (bx0 by0 bx1 by1) box-b (when offs-b (incf bx0 (vx offs-b)) (incf by0 (vy offs-b)) (incf bx1 (vx offs-b)) (incf by1 (vy offs-b))) (and (< ax0 bx1) (< ay0 by1) (>= ax1 bx0) (>= ay1 by0))))) ;; :say (defvar *return-value* nil) (defvar *say-io* *debug-io*) (defmacro :say (&rest vars) (let (formats vals (tabbing 0)) (labels ((join (&rest strings) (apply #'concatenate 'string strings)) (format-expr (var more-exprs-p) (push (join (format nil "~~~A,0T" tabbing) (if more-exprs-p "~A = ~S, " "~A = ~S")) formats) (if (symbolp var) (push (symbol-name var) vals) (push `',var vals)) (push var vals)) (format-val (val &optional (with-space-p nil)) (if with-space-p (push "~S " formats) (push "~S" formats)) (push val vals)) (format-str (val &optional (with-space-p nil)) (if with-space-p (push "~A " formats) (push "~A" formats)) (push val vals))) (loop for x on vars as var = (car x) as next = (cdr x) as next-expr-p = (and next (not (stringp (car next)))) do (typecase var ((or string number) (format-str var)) (keyword (case var (:br (push "~%" formats)))) (list (case (car var) (:tab (setf tabbing (cadr var))) ((:val :vals) (mapcar #'format-val (cdr var) (maplist (lambda (x) (and (cdr x) t)) (cdr var)))) (t (format-expr var next-expr-p)))) (t (format-expr var next-expr-p)))) `(let ((*return-value*)) (format *say-io* ,(join "~&" (apply #'join (nreverse formats)) "~%") ,@(nreverse vals)) *return-value*))))
3,857
Common Lisp
.lisp
106
26.971698
68
0.491299
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
af6cd6a78eb2f3a408817fb2312b008559394fa85e0017b1927598796195e4b4
13,782
[ -1 ]
13,783
presetup.lisp
rpav_spell-and-dagger/src/presetup.lisp
(defpackage #:build (:use #:cl)) (in-package :build) (eval-when (:compile-toplevel :load-toplevel :execute) (defun setup-library-paths () (let* ((argv0 (first sb-ext:*posix-argv*)) (path (directory-namestring argv0))) (format t "Adding ~A~%" path) (push path cffi:*foreign-library-directories*))))
330
Common Lisp
.lisp
9
32.111111
55
0.65
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
a0da496193e258f6a104c1f6c7b53e3995ca8e52efecb0a49e5c15b2e0bb43a9
13,783
[ -1 ]
13,784
game-map.lisp
rpav_spell-and-dagger/src/game-map.lisp
(in-package :game) (defclass game-map () ((tilemap :initform nil) (gktm :initform nil) (physics :initform (make-instance 'physics)))) (defmethod initialize-instance :after ((gm game-map) &key map) (with-slots (tilemap physics gktm) gm (let* ((tm (load-tilemap map)) (size (tilemap-size tm)) (max (* 16.0 (max (vx size) (vy size))))) (setf tilemap tm physics (make-instance 'physics :quadtree (make-instance 'quadtree :key #'entity-box :size max)) gktm (make-instance 'gk-tilemap :tilemap tm)) (gm-setup-physics gm) (physics-start physics)))) (defun map-find-start (map &optional target) (with-slots (tilemap) map ;; This should probably be done via GF, but (typecase target (gk-vec2 target) (gk-vec3 target) (t (let* ((ob (tilemap-find-object tilemap "objects" (or target "start")))) (values (let ((x (or (aval :x ob) 0)) (y (or (aval :y ob) 0))) (gk-vec2 x y)) (aval :properties ob))))))) (defun map-add (map &rest objects) (with-slots (physics) map (apply 'physics-add physics objects) (apply 'entity-added-to-map map objects))) (defun map-remove (map &rest objects) (with-slots (physics) map (apply 'physics-remove physics objects))) (defun map-move (map object new-pos) (with-slots (physics) map (physics-remove physics object) (setf (entity-pos object) new-pos) (physics-add physics object))) (defun map-update (map) (with-slots (physics) map (physics-update physics))) (defun map-find-in-box (map box &optional offs) (with-slots (physics) map (physics-find physics box offs))) (defmethod draw ((gm game-map) lists m) (with-slots (gktm physics) gm (draw gktm lists m) (physics-map (lambda (ob) (draw ob lists m)) physics))) ;; (defun gm-object-type (ob) (let ((type (aval :type ob))) (if (or (not type) (string= "" type)) 'simple-blocker (intern (string-upcase type) :game)))) (defun gm-make-instance (gm tm ob) (let* ((type (gm-object-type ob)) (pos (gk-vec3 (aval :x ob) (aval :y ob) 0)) (size (gk-vec2 (aval :width ob) (aval :height ob))) (sprite-name (when-let (tile (tilemap-find-gid tm (aval :gid ob))) (tile-image tile)))) (and type (make-instance type :name (aval :name ob) :sprite-name sprite-name :pos pos :size size :props (aval :properties ob))))) (defun gm-add-object (gm tm ob) (with-slots (physics) gm (when-let (instance (gm-make-instance gm tm ob)) (physics-add physics instance)))) (defun gm-setup-physics (gm) (with-slots ((tm tilemap) physics) gm ;; Really just need to iterate all object layers... (map-tilemap-objects (lambda (x) (gm-add-object gm tm x)) tm "collision") (map-tilemap-objects (lambda (x) (gm-add-object gm tm x)) tm "objects") (map-tilemap-objects (lambda (x) (gm-add-object gm tm x)) tm "interacts") (map-tilemap-objects (lambda (x) (gm-add-object gm tm x)) tm "spawners") (map-tilemap-objects (lambda (x) (gm-add-object gm tm x)) tm "npcs") ;; Map boundaries .. we should fill map/target props in from map props (physics-add physics (make-instance 'map-link :map (tilemap-property tm :s) :direction :s :pos (gk-vec3 -1 -1 0) :size (gk-vec2 256 1))) (physics-add physics (make-instance 'map-link :map (tilemap-property tm :w) :direction :w :pos (gk-vec3 -1 -1 0) :size (gk-vec2 1 144))) (physics-add physics (make-instance 'map-link :map (tilemap-property tm :n) :direction :n :pos (gk-vec3 -1 144 0) :size (gk-vec2 256 1))) (physics-add physics (make-instance 'map-link :map (tilemap-property tm :e) :direction :e :pos (gk-vec3 256 -1 0) :size (gk-vec2 1 144)))))
4,281
Common Lisp
.lisp
100
33.09
81
0.566971
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
80d9f73c4df1acc2b39da221b8a4c0906f851b53e2762ded7e0349bcf5f02237
13,784
[ -1 ]
13,785
tilemap.lisp
rpav_spell-and-dagger/src/tilemap.lisp
(in-package :game) (defparameter *tileset-cache* (make-hash-table :test 'equal)) ;; TILE, TILESET (defclass tile () ((props :initform nil :accessor props) (image :initform nil :initarg :image :reader tile-image))) (defclass tileset () ((props :initform nil :accessor props) (tiles :initform nil :initarg :tiles :accessor tileset-tiles))) (defmethod initialize-instance :after ((tm tileset) &key (tilecount 4) props) (with-slots (tiles (p props)) tm (setf tiles (make-array tilecount :adjustable t :initial-element nil :fill-pointer 0) p props))) (defun tileset-append (ts tile) (with-slots (tiles) ts (vector-push-extend tile tiles))) (defun tileset-tile (ts i) (with-slots (tiles) ts (aref tiles i))) (defun translate-props (props) (mapcar (lambda (x) (cons (make-keyword (string-upcase (car x))) (cdr x))) props)) (defun tilemap-name-to-key (s) (or (parse-integer s :junk-allowed t) (make-keyword (string-upcase s)))) (defun load-tileset (path &key reload) (let ((oldset (gethash (namestring path) *tileset-cache*))) (if (or reload (not oldset)) (with-open-file (s path) (let* ((json:*json-identifier-name-to-lisp* #'identity) (json:*identifier-name-to-key* #'tilemap-name-to-key) (json (json:decode-json s)) (tilecount (aval :tilecount json)) (ts (make-instance 'tileset :tilecount tilecount :props (translate-props (aval :properites json))))) (setf (fill-pointer (tileset-tiles ts)) tilecount) (loop for tile in (aval :tiles json) as i = (car tile) as img = (aval :image (cdr tile)) do (setf (aref (tileset-tiles ts) i) (make-instance 'tile :image img))) (loop for prop in (aval :tileproperties json) as i = (car prop) do (setf (props (aref (tileset-tiles ts) i)) (translate-props (cdr prop)))) (setf (gethash (namestring path) *tileset-cache*) ts) ts)) oldset))) ;; TILE-MERGESET (defclass tile-mergeset () ((offsets :initform nil) (sets :initform nil))) (defmethod initialize-instance :after ((tms tile-mergeset) &key sets &allow-other-keys) (let ((len (length sets)) (sets (sort sets (lambda (a b) (< (aval :firstgid a) (aval :firstgid b)))))) (with-slots (offsets (s sets)) tms (setf offsets (make-array len :element-type '(unsigned-byte 16) :initial-contents (mapcar (lambda (x) (aval :firstgid x)) sets))) (setf s (make-array len :initial-contents (mapcar (lambda (x) (load-tileset (get-path "assets" "map" (aval :source x)))) sets)))))) (defun tms-find (tms num) (if (= num 0) nil (with-slots (offsets sets) tms (loop for i from 0 as offset = (aref offsets i) as next-offset = (and (< (1+ i) (length offsets)) (aref offsets (1+ i))) when (or (not next-offset) (< num next-offset)) do (let ((set (aref sets i))) (return-from tms-find (tileset-tile set (- num offset)))))))) ;; TILEMAP (defclass tile-layer () ((props :initform nil :initarg :props :accessor props) (tiles :initform nil :reader tile-layer-tiles))) (defun tile-layer-parse (json) (let ((layer (make-instance 'tile-layer :props (aval :properties json))) (data (aval :data json))) (with-slots (tiles) layer (setf tiles (make-array (length data) :element-type '(unsigned-byte 16) :initial-contents data)) layer))) (defclass object-layer () ((props :initform nil :initarg :props :accessor props) (objects :initform nil :reader object-layer-objects) (names :initform (make-hash-table :test 'equal)))) (defun object-layer-parse (tm json) (let* ((layer (make-instance 'object-layer :props (aval :properties json))) (names (slot-value layer 'names)) (objects (aval :objects json)) (size (tilemap-size tm))) (loop for object in objects as y-before = (aval :y object) do (setf (aval :y object) (- (* 16 (vy size)) (+ (aval :height object) (aval :y object)))) (when-let (name (aval :name object)) (setf (gethash name names) object))) (setf (slot-value layer 'objects) objects) layer)) (defclass tilemap () ((props :initform nil :reader tilemap-props :initarg :props) (size :initform nil :reader tilemap-size :initarg :size) (layers :initform nil :reader tilemap-layers) (layer-names :initform (make-hash-table :test 'equal)) (mergeset :initform nil :initarg :mergeset :reader tilemap-mergeset) (render-order :initform nil :initarg :render-order :reader tilemap-render-order))) (defmethod initialize-instance :after ((tm tilemap) &key layercount) (with-slots (layers) tm (setf layers (make-array layercount)))) (defun load-tilemap (path) (with-open-file (s path) (let* ((json:*json-identifier-name-to-lisp* #'identity) (json:*identifier-name-to-key* #'tilemap-name-to-key) (json (json:decode-json s)) (layers (aval :layers json)) (mergeset (make-instance 'tile-mergeset :sets (aval :tilesets json))) (tm (make-instance 'tilemap :props (aval :properties json) :size (gk-vec2 (aval :width json) (aval :height json)) :layercount (length layers) :render-order (make-keyword (string-upcase (aval :renderorder json))) :mergeset mergeset)) (names (slot-value tm 'layer-names))) (loop for layer in layers for i from 0 do (setf (gethash (aval :name layer) names) i (aref (tilemap-layers tm) i) (cond ((aval :data layer) (tile-layer-parse layer)) ((aval :objects layer) (object-layer-parse tm layer))))) tm))) (defun tilemap-find-layer (tm name) (with-slots (layers layer-names) tm (typecase name (string (when-let (i (gethash name layer-names)) (aref layers i))) (integer (aref layers name))))) (defun map-tilemap-tiles (function tm layer) (with-slots (size layers mergeset) tm (let ((layer (tilemap-find-layer tm layer))) (when (typep layer 'tile-layer) (with-slots (tiles props) layer (loop for idx across tiles for i from 0 as key = (or (aval :layer props) i) as tile = (tms-find mergeset idx) as x = (truncate (mod i (vx size))) as y = (- (vy size) (truncate (/ i (vx size))) 1) do (funcall function tile x y key))))))) (defun map-tilemap-objects (function tm layer) (with-slots (size layers) tm (let ((layer (tilemap-find-layer tm layer))) (when (typep layer 'object-layer) (with-slots (objects) layer (loop for ob in objects do (funcall function ob))))))) (defun tilemap-find-object (tm layer name) (with-slots (layers) tm (let ((layer (tilemap-find-layer tm layer))) (when (typep layer 'object-layer) (gethash name (slot-value layer 'names)))))) (defun tilemap-find-gid (tm gid) (when gid (with-slots (mergeset) tm (tms-find mergeset gid)))) (defun tilemap-property (tm name) (with-slots (props) tm (aval name props))) ;; GK-TILEMAP (defclass gk-tilemap () ((tilemap :initform nil :initarg :tilemap) (sprites :initform (make-array 150 :adjustable t :fill-pointer 0)))) ;;; This could in theory be done slightly more ideally, but at great ;;; inconvenience. (defmethod initialize-instance :after ((gktm gk-tilemap) &key (sheet (asset-sheet *assets*)) &allow-other-keys) (with-slots (tilemap sprites) gktm (let ((layer-count (length (tilemap-layers tilemap)))) (loop for i from 0 below layer-count do (map-tilemap-tiles (lambda (tile x y key) (when tile (let ((sprite (make-instance 'sprite :sheet sheet :key key :name (tile-image tile) :pos (gk-vec3 (* 16 x) (* 16 y) 0)))) (vector-push-extend sprite sprites)))) tilemap i))))) (defmethod draw ((gktm gk-tilemap) lists m) (with-slots (sprites) gktm (loop for sprite across sprites do (draw sprite lists m))))
9,341
Common Lisp
.lisp
212
32.575472
89
0.55321
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
07189570e45e43de7994f3ca7ba05e263e46771b874398e4b9e676ffeeb793c0
13,785
[ -1 ]
13,786
image.lisp
rpav_spell-and-dagger/src/image.lisp
;;; Modified from the example in cl-gamekernel (in-package :game) (defclass image () (anchor quad trs)) (defmethod initialize-instance ((s image) &key key (tex 0) anchor size pos) (with-slots (quad trs scale) s (setf quad (cmd-quad tex :key key)) (setf trs (cmd-tf-trs :out (quad-tfm quad) :translate pos :scale size)) (setf (image-anchor s) anchor))) (defun image-tex (s) (quad-tex (slot-value s 'quad))) (defun (setf image-tex) (v s) (setf (quad-tex (slot-value s 'quad)) v)) (defun image-pos (s) (tf-trs-translate (slot-value s 'trs))) (defun (setf image-pos) (v s) (setf (tf-trs-translate (slot-value s 'trs)) v)) (defun image-anchor (image) (slot-value image 'anchor)) (defun (setf image-anchor) (v image) (with-slots (anchor quad) image (setf anchor v) (let* ((x+ (- 1 (vx v))) (x- (vx v)) (y+ (- 1 (vy v))) (y- (vy v)) (verts (list (gk-quadvert x- y- 0 1 0 1) (gk-quadvert x- y+ 0 1 0 0) (gk-quadvert x+ y- 0 1 1 1) (gk-quadvert x+ y+ 0 1 1 0)))) (setf (quad-attr quad) verts))) v) (defmethod draw ((image image) lists m) (with-slots (pre-list sprite-list) lists (with-slots (quad trs) image (setf (tf-trs-prior trs) m) (cmd-list-append pre-list trs) (cmd-list-append sprite-list quad))))
1,442
Common Lisp
.lisp
40
28.9
75
0.566092
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
5aee879f8ae51d1c36327da19a38f1ef8dba3b32d4e27b5152235ec9aae14b1d
13,786
[ -1 ]
13,787
sprite.lisp
rpav_spell-and-dagger/src/sprite.lisp
;;; Modified from the example in cl-gamekernel (in-package :game) (defclass sprite () (qs trs (visiblep :initform t :accessor sprite-visible))) (defmethod initialize-instance ((s sprite) &key sheet index name pos size key) (call-next-method) (with-slots (qs trs scale) s (let* ((sheet (or sheet (asset-sheet *assets*))) (index (if name (or (find-frame sheet name) (find-frame sheet "nosprite.png")) (or index (find-frame sheet "nosprite.png"))))) (setf qs (cmd-quadsprite sheet index :key key))) (setf trs (cmd-tf-trs :out (quadsprite-tfm qs) :translate pos :scale size)))) (defun sprite-pos (s) (tf-trs-translate (slot-value s 'trs))) (defun (setf sprite-pos) (v s) (setf (tf-trs-translate (slot-value s 'trs)) v)) (defun sprite-index (s) (quadsprite-index (slot-value s 'qs))) (defun (setf sprite-index) (v s) (with-slots (qs) s (setf (quadsprite-index qs) v))) (defun (setf sprite-name) (name s) (let ((sheet (asset-sheet *assets*))) (setf (sprite-index s) (or (find-frame sheet name) (progn (format t "Warning: Can't find sprite \"~A\"~%" name) (find-frame sheet "nosprite.png")))))) (defun sprite-key (sprite) (cmd-key (slot-value sprite 'qs))) (defun (setf sprite-key) (v sprite) (with-slots (qs) sprite (setf (cmd-key qs) v))) (defmethod draw ((sprite sprite) lists m) (with-slots (pre-list sprite-list) lists (with-slots (qs trs visiblep) sprite (when visiblep (setf (tf-trs-prior trs) m) (cmd-list-append pre-list trs) (cmd-list-append sprite-list qs))))) ;; Spritesheet animations (defclass sprite-anim () ((indexes :initform (make-array 2 :element-type '(unsigned-byte 16) :adjustable t :fill-pointer 0) :reader sprite-anim-indexes))) (defun sprite-anim-append (sa index) (with-slots (indexes) sa (vector-push-extend index indexes))) (defun sprite-anim-frame (sa frame) (with-slots (indexes) sa (aref indexes frame))) (defun sprite-anim-length (sa) (with-slots (indexes) sa (length indexes))) (defclass sheet-animations () ((sheet :initarg :sheet :initform nil) (anims :initform (make-hash-table :test 'equalp)))) (defmethod initialize-instance :after ((s sheet-animations) &key &allow-other-keys) (with-slots (sheet anims) s (map-spritesheet (lambda (x i) (let* ((m (nth-value 1 (ppcre:scan-to-strings "(.*)_(\\d+)\\.png$" x)))) (when m (let* ((name (ppcre:regex-replace-all "_" (aref m 0) "-")) (anim (ensure-gethash (nstring-upcase name) anims (make-instance 'sprite-anim)))) (sprite-anim-append anim i))))) sheet))) (defun find-anim-frame (animations name frame) (with-slots (anims) animations (sprite-anim-frame (gethash name anims) frame))) (defun find-anim (animations name) (with-slots (anims) animations (gethash name anims))) (defun sheet-anim-length (sheet name) (with-slots (anims) sheet (with-slots (indexes) (or (gethash sheet name) (error "Can't find animation: ~S" name)) (length indexes))))
3,369
Common Lisp
.lisp
86
31.77907
100
0.607296
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
6c2872091f5205911465928b289ff3126874ef117983035a37ed5d73b55c0523
13,787
[ -1 ]
13,788
window.lisp
rpav_spell-and-dagger/src/window.lisp
(in-package :game) (defclass game-lists () ((pass-list :initform (make-instance 'cmd-list :subsystem :config)) (pre-list :initform (make-instance 'cmd-list :prealloc 100 :subsystem :config)) (sprite-list :initform (make-instance 'cmd-list :prealloc 100 :subsystem :gl)) (ui-list :initform nil))) (defun game-lists-clear (game-lists) (with-slots (pre-list sprite-list ui-list) game-lists (cmd-list-clear pre-list) (cmd-list-clear sprite-list) (cmd-list-clear ui-list))) (defclass game-window (kit.sdl2:gl-window) (gk assets (map :initform nil :accessor game-window-map) (map-screen :initform nil :accessor game-window-map-screen) (char :initform nil :accessor game-window-char) (game-state :initform (make-hash-table)) (anim-manager :initform (make-instance 'anim-manager)) (screen :initform nil :accessor game-window-screen) (phase-stack :initform (make-instance 'phase-stack)) (render-bundle :initform (make-instance 'bundle)) (render-lists :initform (make-instance 'game-lists)))) (defmacro with-game-state ((gamewin) &body body) (once-only (gamewin) `(let ((*assets* (slot-value ,gamewin 'assets)) (*window* ,gamewin) (*time* (current-time)) (*anim-manager* (slot-value ,gamewin 'anim-manager)) (*scale* (/ (kit.sdl2:window-width ,gamewin) 256.0)) (*ps* (slot-value ,gamewin 'phase-stack))) ,@body))) (defmethod initialize-instance :after ((win game-window) &key w h &allow-other-keys) (with-slots (gk assets render-bundle render-lists) win (with-slots (pass-list pre-list sprite-list ui-list) render-lists (setf gk (gk:create :gl3)) (setf assets (load-assets gk)) (with-game-state (win) (let ((phase (make-instance 'title-phase))) (ps-push phase))) (let ((pre-pass (pass 1)) (sprite-pass (pass 2 :asc)) (ui-pass (pass 3))) (setf ui-list (make-instance 'cmd-list-nvg :width w :height h)) (cmd-list-append pass-list pre-pass sprite-pass ui-pass) (bundle-append render-bundle pass-list ; 0 pre-list ; 1 sprite-list ; 2 ui-list ; 3 )) (sdl2:gl-set-swap-interval 1) (setf (kit.sdl2:idle-render win) t)))) (defmethod kit.sdl2:close-window :before ((w game-window)) (with-slots (gk) w (gk:destroy gk))) (defmethod kit.sdl2:render ((w game-window)) (gl:clear-color 0.0 0.0 0.0 1.0) (gl:clear :color-buffer-bit :stencil-buffer-bit) (with-slots (gk assets render-bundle render-lists) w (game-lists-clear render-lists) (with-game-state (w) (when-let (screen (current-screen)) (anim-update *anim-manager*) (draw screen render-lists (asset-proj *assets*)) (gk:process gk render-bundle))))) (defgeneric key-event (ob key state) (:method (ob key state))) (defmethod kit.sdl2:keyboard-event ((window game-window) state ts repeat-p keysym) (with-game-state (window) (let ((scancode (sdl2:scancode keysym))) (when (or (eq :scancode-escape scancode)) (if build:*binary* (progn (kit.sdl2:close-window window) (kit.sdl2:quit)) (kit.sdl2:close-window window))) (unless repeat-p (when-let (screen (current-screen)) (key-event screen scancode state)))))) (define-start-function run (&key (w 1280) (h 720)) (static-startup) (sdl2:gl-set-attr :context-major-version 3) (sdl2:gl-set-attr :context-minor-version 3) (sdl2:gl-set-attr :context-profile-mask 1) (sdl2:gl-set-attr :stencil-size 8) (make-instance 'game-window :w w :h h)) ;;; (run) ;; Utility (defun current-screen () (and *window* (game-window-screen *window*))) (defun (setf current-screen) (v) (setf (game-window-screen *window*) v)) (defun current-map () (and *window* (game-window-map *window*))) (defun (setf current-map) (v) (setf (game-window-map *window*) v)) (defun current-char () (and *window* (game-window-char *window*))) (defun (setf current-char) (v) (setf (game-window-char *window*) v)) (defun map-change (map &optional target) (let ((char (current-char))) (setf (current-map) (make-instance 'game-map :map (get-path "assets" "map" (string+ map ".json")))) (multiple-value-bind (map-target props) (map-find-start (current-map) target) (setf (entity-pos char) map-target) (setf (entity-motion char) +motion-none+) (map-add (current-map) char) (map-update (current-map)) (when-let (text (aval :text props)) (show-textbox text))))) (defun window-size () (kit.sdl2:window-size *window*)) (defun window-width () (kit.sdl2:window-width *window*)) (defun window-height () (kit.sdl2:window-height *window*)) (defun game-value (name) (with-slots (game-state) *window* (gethash name game-state))) (defun (setf game-value) (v name) (with-slots (game-state) *window* (setf (gethash name game-state) v)))
5,115
Common Lisp
.lisp
124
35.096774
84
0.636254
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
d35ae50dc9be3d92d79aa8a7b64b9d8ae16d512576cbd91a2cc2a59154e5b134
13,788
[ -1 ]
13,789
phase.lisp
rpav_spell-and-dagger/src/phase.lisp
;;; This was taken, conceptually, from how I do things in some other ;;; games. But it was rewritten, since that was Lua and this is Lisp! (in-package :game) ;; PHASE (defclass game-phase () ()) ;;; When the phase begins after being pushed or ends before being popped (defgeneric phase-start (game-phase) (:method ((p game-phase)) (phase-resume p))) (defgeneric phase-finish (game-phase) (:method ((p game-phase)))) ;;; When the phase is paused or resumed (defgeneric phase-pause (game-phase) (:method ((p game-phase)))) (defgeneric phase-resume (game-phase) (:method ((p game-phase)))) ;;; When something signals a phase it should probably quit (defgeneric phase-back (game-phase) (:method ((p game-phase)))) ;; PHASE-STACK (defclass phase-stack () ((phases :initform (make-array 10 :adjustable t :fill-pointer 0 :initial-element nil)) (cur :initform -1 :reader ps-cur) (phase-refs :initform 0))) (defmethod print-object ((o phase-stack) s) (print-unreadable-object (o s :type t) (format s "CUR: ~A (~A) PHASE-REFS: ~A" (class-name (class-of (ps-cur-phase o))) (ps-cur o) (slot-value o 'phase-refs)))) (defun ps-incref (&optional (ps *ps*)) (incf (slot-value ps 'phase-refs))) (defun ps-decref (&optional (ps *ps*)) (decf (slot-value ps 'phase-refs)) (ps-update ps)) (defun ps-top (ps) (aref (slot-value ps 'phases) (ps-cur ps))) (defun ps-cur-phase (&optional (ps *ps*)) (with-slots (cur phases) ps (when (>= cur 0) (aref phases cur)))) (defun ps-push (new-phase &optional (ps *ps*)) (with-slots (phases cur) ps (vector-push-extend new-phase phases) (ps-update ps))) (defun ps-pop (&optional (ps *ps*)) (with-slots (phases cur) ps (vector-pop phases))) (defun ps-pop-to (type &optional (ps *ps*)) (with-slots (phases phase-refs cur) ps (loop as phase = (vector-pop phases) do (decf cur) (when (typep phase type) (setf phase-refs 0) (ps-push phase ps) (return))))) (defun ps-interrupt (new-phase &optional (ps *ps*)) (with-slots (phase-refs) ps (setf phase-refs 0) (ps-push new-phase ps))) (defun ps-replace (new-phase &optional (ps *ps*)) (with-slots (phase-refs phases) ps (phase-finish (ps-cur-phase)) (setf phase-refs 0) (setf (aref phases (ps-cur ps)) new-phase) (phase-start new-phase))) (defun ps-has-up-phase (ps) (with-slots (cur phases) ps (< cur (1- (length phases))))) (defun ps-has-down-phase (ps) (>= (ps-cur ps) 0)) (defun ps-step-up-phase (ps) (with-slots (cur phases) ps (when-let (phase (ps-cur-phase ps)) (when phase (phase-pause phase))) (incf cur) (when-let (new-phase (ps-cur-phase ps)) (phase-start new-phase)))) (defun ps-step-down-phase (ps) (with-slots (cur phases) ps (when-let (phase (ps-cur-phase ps)) (decf cur) (vector-pop phases) (phase-finish phase)))) (defun ps-update (ps) (with-slots (phase-refs) ps (loop while (= 0 phase-refs) do (if (ps-has-up-phase ps) (ps-step-up-phase ps) (progn (ps-step-down-phase ps) (when (and (not (ps-has-up-phase ps)) (ps-has-down-phase ps)) (phase-resume (ps-cur-phase ps)))))))) (defun ps-back (&optional (ps *ps*)) (phase-back (ps-cur-phase ps)))
3,448
Common Lisp
.lisp
93
31.451613
88
0.616517
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
b390073f5c1afe703c660ffd5f276372c5a936177a57ee891ba7e6ee145e9b10
13,789
[ -1 ]
13,790
entity.lisp
rpav_spell-and-dagger/src/entity.lisp
(in-package :game) (defun relative-motion (a b) "Return the \"direction\" of `B` in relation to `A`, e.g., if `B` is \"left of\" `A`, return `+motion-left+`." (let ((dx (- (vx a) (vx b))) (dy (- (vy a) (vy b)))) (if (< (abs dy) (abs dx)) (if (< dx 0.0) +motion-right+ +motion-left+) (if (< dy 0.0) +motion-up+ +motion-down+)))) ;;; May convert this to be prototypey later (defclass entity () ((name :initform nil :initarg :name :accessor entity-name) (pos :initform (gk-vec3 0 0 0) :reader entity-pos) (size :initform (gk-vec2 16 16) :reader entity-size) (motion :initform (gk-vec2 0 0) :reader entity-motion) (state :initform nil :accessor entity-state) (sprite :initform nil :initarg :sprite :accessor entity-sprite) (props :initform nil :initarg :props))) (defmethod initialize-instance ((e entity) &key pos size &allow-other-keys) (call-next-method) (with-slots ((_pos pos) (_size size)) e ;; Using set-vec2 makes it so everyone can specify them. We don't use Z. (when pos (set-vec2 _pos pos)) (when size (set-vec2 _size size)))) (defmethod print-object ((e entity) s) (with-slots (name pos size) e (print-unreadable-object (e s :type t :identity t) (when name (format s "~A " name)) (format s "[~S ~S ~S ~S]" (vx pos) (vy pos) (vx size) (vy size))))) (defmethod (setf entity-pos) ((v gk-vec2) (e entity)) (with-slots (pos) e (set-vec2 pos v))) (defmethod (setf entity-pos) ((v gk-vec3) (e entity)) (with-slots (pos) e (set-vec2 pos v))) (defmethod (setf entity-motion) ((v gk-vec2) (e entity)) (with-slots (motion) e (set-vec2 motion v))) (defmethod (setf entity-motion) ((v gk-vec3) (e entity)) (with-slots (motion) e (set-vec2 motion v))) (defgeneric entity-box (entity) (:documentation "Return a `BOX` or `(values BOX OFFSET)` for `ENTITY`") (:method ((e entity)) (with-slots (pos) e (values +default-box+ pos)))) (defgeneric entity-update (entity) (:method (e) (with-slots (pos sprite) e (when sprite (setf (sprite-pos sprite) pos))))) (defgeneric entity-action (entity action) (:method (e a))) (defun default-interact (e a) (declare (ignorable e a)) (show-textbox "Nothing here.")) (defgeneric entity-interact (entity actor) (:method (e a) (default-interact e a)) (:documentation "Called when `ACTOR` interacts with `ENTITY`.")) (defgeneric entity-attacked (entity actor weapon) (:method (e a w)) (:documentation "Called when `ACTOR` attacks `ENTITY` with `WEAPON`")) (defgeneric entity-collide (e1 e2) (:documentation "Called when `E1` moves and collides with `E2`.") (:method (e1 e2))) (defgeneric entity-touch (e1 e2) (:documentation "Called when `E1` moves and touches `E2`. This happens only when `E2` is not `ENTITY-SOLID-P`.") (:method (e1 e2))) (defgeneric entity-added-to-map (map entity) (:documentation "Called when `ENTITY` has been added to `MAP`") (:method (m e) (entity-update e))) (defgeneric entity-magic-hit (entity magic) (:documentation "Called when `ENTITY` is hit by `MAGIC`.") (:method (e m))) (defgeneric entity-property (e name) (:method ((e entity) name) (aval name (slot-value e 'props)))) (defmethod draw ((e entity) lists m) (with-slots (sprite) e (when sprite (draw sprite lists m)))) ;;; A more complex system would allow channels or entity-entity tests ;;; or whatnot. For now this is a simple boolean. Default is T, ;;; because it it seems there are more solid than non-solid entities. (defgeneric entity-solid-p (entity) (:documentation "Specialize to determine if `ENTITY` can be passed.") (:method (e) t)) (defmacro define-entity-solid-p (type val) `(defmethod entity-solid-p ((e ,type)) ,val))
3,783
Common Lisp
.lisp
92
37.532609
77
0.662033
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
14c3f094fc53f1d906057c58f66369cb7aef8a53f38cf2412b5ab18fab0b764c
13,790
[ -1 ]
13,791
quadtree.lisp
rpav_spell-and-dagger/src/quadtree.lisp
;;; - NOTICE - NOTICE - NOTICE - ;;; ;;; This was taken from some other code I had laying around for a ;;; quadtree; it was not written during the jam. It may have been ;;; modified though. ;;; ;;; - NOTICE - NOTICE - NOTICE - (in-package :game) ;; Quadtree (defclass qt-node () ((size :initform nil :initarg :size) (center-point :initform nil :initarg :at) (quads :initform (make-array 4 :initial-element nil)) (objects :initform nil))) (defclass quadtree () ((top-node) (max-depth :initform 3 :initarg :max-depth) (object-node :initform (make-hash-table)) (key-fun :initform #'identity :initarg :key))) (defmethod initialize-instance :after ((qt quadtree) &key x y size &allow-other-keys) (with-slots (top-node) qt (let ((x (or x (/ size 2.0))) (y (or y (/ size 2.0)))) (setf top-node (make-instance 'qt-node :at (gk-vec2 x y) :size size))))) (defgeneric quadtree-add (quadtree item) (:documentation "Add `ITEM` to `QUADTREE`.")) (defgeneric quadtree-delete (quadtree item) (:documentation "Delete `ITEM` from `QUADTREE`.")) (defgeneric quadtree-select (quadtree box &optional offs) (:documentation "Select items from `QUADTREE` inside `BOX` with optional offset, `OFFS`")) (defun quadtree-contains (quadtree object) (with-slots (object-node) quadtree (nth-value 1 (gethash object object-node)))) (defun point-quad (x y qt-node &optional (test #'<)) "Return the quadrant `POINT` would occupy." (with-slots ((c center-point)) qt-node (let ((x< (funcall test x (vx c))) (y< (funcall test y (vy c)))) (cond ((and x< y<) 0) (y< 1) (x< 2) (t 3))))) (defun rect-quad (rect offs qt-node) "Return the quadrant `RECT` should occupy, or `NIL` if it does not fit into any single quad" (with-box (x0 y0 x1 y1) rect (when offs (incf x0 (vx offs)) (incf y0 (vy offs)) (incf x1 (vx offs)) (incf y1 (vy offs))) (let ((q1 (point-quad x0 y0 qt-node)) (q2 (point-quad x1 y1 qt-node #'<=))) (if (= q1 q2) q1 nil)))) (defun qn-pos (qn qt-node) (with-slots ((at center-point) size) qt-node (let ((offset (/ size 4.0)) (x (vx at)) (y (vy at))) (ecase qn (0 (gk-vec2 (- x offset) (- y offset))) (1 (gk-vec2 (+ x offset) (- y offset))) (2 (gk-vec2 (- x offset) (+ y offset))) (3 (gk-vec2 (+ x offset) (+ y offset))))))) (defun ensure-rect-quad (rect offs qt-node) (let ((qn (rect-quad rect offs qt-node))) (if qn (with-slots (quads size) qt-node (or (aref quads qn) (setf (aref quads qn) (make-instance 'qt-node :at (qn-pos qn qt-node) :size (/ size 2.0))))) qt-node))) (defun next-node (rect offs qt-node) "Return the next (child) node that `RECT` fits into in `QT-NODE`, or `NIL`" (with-slots (quads) qt-node (let ((qn (rect-quad rect offs qt-node))) (when qn (aref quads qn))))) (defmethod quadtree-add ((qt quadtree) item) (with-slots (top-node object-node max-depth key-fun) qt (multiple-value-bind (rect offs) (funcall key-fun item) (loop for depth from 0 below max-depth as last-node = nil then node as node = top-node then (ensure-rect-quad rect offs node) while (not (eq node last-node)) finally (push item (slot-value node 'objects)) (setf (gethash item object-node) node)))) item) (defmethod quadtree-delete ((qt quadtree) item) (with-slots (object-node) qt (let ((node (gethash item object-node))) (if node (progn (deletef (slot-value node 'objects) item) (remhash item object-node)) (error "Object ~S not in tree" item))))) (defun map-all-subtrees (function qt-node) "Call `FUNCTION` on all children of `QT-NODE`, but not `QT-NODE` itself." (loop for child across (slot-value qt-node 'quads) when child do (funcall function (slot-value child 'objects)) (map-all-subtrees function child))) (defun map-matching-subtrees (box offs function qt-node) "Call `FUNCTION` on `QT-NODE` and any children of `QT-NODE` which `BOX` fits in exactly. Return the last node `BOX` fits in." (funcall function (slot-value qt-node 'objects)) (if-let ((next-node (next-node box offs qt-node))) (map-matching-subtrees box offs function next-node) qt-node)) (defmethod quadtree-select ((qt quadtree) box &optional offs) "Select all objects which overlap with `BOX`" (let (overlaps) (with-slots (top-node object-node key-fun) qt (flet ((select (objects) (loop for object in objects when (multiple-value-bind (box1 offs1) (funcall key-fun object) (box-intersect-p box box1 offs offs1)) do (push object overlaps)))) (let ((subtree (map-matching-subtrees box offs #'select top-node))) (map-all-subtrees #'select subtree)) overlaps))))
5,155
Common Lisp
.lisp
131
32.580153
79
0.605195
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
2f8b95631e31a1b9c0620b96239e006ef3dd28ca8709002c8e0cd3997f2de4d5
13,791
[ -1 ]
13,792
util.rpav-1.lisp
rpav_spell-and-dagger/src/util.rpav-1.lisp
;; -*- lisp -*- ;; ;; Re-run this command to regenerate this file. It'll overwrite ;; whatever is there, so make sure it's going to the right place: #+(or) (make-util:make-util '(spell-and-dagger :src "util.rpav-1") :package "UTIL.RPAV-1" :symbols '(laconic:string-join laconic:string+ laconic:substr laconic:aval laconic:akey (setf laconic:aval)) :exportp t) ;; =================================================================== (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package "UTIL.RPAV-1") (make-package "UTIL.RPAV-1" :use '(#:cl)))) (in-package "UTIL.RPAV-1") (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'string-join) (defun string-join (list string) (labels ((zipper (c list) (when list (list* c (format nil "~A" (car list)) (zipper string (cdr list)))))) (apply #'concatenate 'string (zipper "" list)))))) (export 'string-join) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'string+) (defun string+ (string &rest strings) "=> NEW-STRING Concatenate string designators into a new string." (apply #'concatenate 'string (string string) (mapcar #'string strings))))) (export 'string+) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'substr) (defun substr (str start &optional end) "=> DISPLACED-SUBSTRING Make a shared substring of `STR` using `MAKE-ARRAY :displaced-to`" (let* ((end (or end (length str))) (len (- end start))) (make-array len :element-type (array-element-type str) :displaced-to str :displaced-index-offset start))))) (export 'substr) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'aval) (defun aval (akey alist &key (key 'identity) (test 'eq)) "Get the value for key `KEY` in `ALIST`" (cdr (assoc akey alist :key key :test test))))) (export 'aval) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'akey) (defun akey (val alist &key (key 'identity) (test 'eq)) "Get the key for value `VAL` in `ALIST`" (car (rassoc val alist :key key :test test))))) (export 'akey) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp '(setf aval)) (defun (setf aval) (v val alist &key (key 'identity) (test 'eq)) (setf (cdr (assoc val alist :key key :test test)) v))))
2,612
Common Lisp
.lisp
57
38.491228
82
0.600865
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
5e74707234704a4d1e29e09cee9bef1234ec1959a81b390fa700038a5b69fa19
13,792
[ -1 ]
13,793
proto.lisp
rpav_spell-and-dagger/src/proto.lisp
(in-package :game) (defparameter *default-map* "town") (defvar *assets* nil "This should be set to ASSETS when any game logic stuff is called") (defvar *time* nil "This should be set to the current frame time during game logic") (defvar *ps* nil "This should be set to the game's phase stack") (defvar *window* nil "The current game-window") (defvar *scale* nil "'Virtual resolution' scale; this represents 1px scaled.") (defvar *ps* nil "The phase stack") (defvar *anim-manager* nil "The animation manager") (defgeneric draw (thing lists matrix) (:documentation "Draw `THING` given `LISTS` and prior transformation `MATRIX`"))
653
Common Lisp
.lisp
18
33.888889
82
0.739617
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
82fb879ec1229333f6fe6722786061464328b6f76e759ca8684b518b4117954d
13,793
[ -1 ]
13,794
physics.lisp
rpav_spell-and-dagger/src/physics.lisp
;;; Physics! .. I use that term _very_ loosely. (in-package :game) (defclass physics () ((last-time :initform 0.0) (timestep :initform (/ 1.0 60.0)) (objects :initform (make-hash-table)) (rect :initform (box 0 0 0 0)) (quadtree :initform nil :initarg :quadtree))) (defun physics-add (phys &rest list) (declare (type physics phys)) (with-slots (objects quadtree) phys (loop for ob in list do (quadtree-add quadtree ob) (setf (gethash ob objects) t)))) (defun physics-remove (phys &rest list) (declare (type physics phys)) (with-slots (objects quadtree) phys (loop for ob in list do (when (quadtree-contains quadtree ob) (quadtree-delete quadtree ob)) (remhash ob objects)))) (defun physics-clear (phys) (declare (type physics phys)) (with-slots (objects) phys (setf objects nil))) (defun physics-start (phys) (declare (type physics phys)) (with-slots (last-time) phys (setf last-time (current-time)))) (defun physics-update (phys) (declare (type physics phys)) (with-slots (last-time timestep) phys (let* ((diff (- *time* last-time)) (steps (truncate diff timestep))) ;; Just let this depend on vsync for now, which isn't ideal, but ;; whatever (physics-step phys) (setf last-time *time*)))) ;;; This is probably horribly inefficient. (defun physics-move-object (physics ob) (unless (v2= +motion-none+ (entity-motion ob)) (with-slots (objects quadtree rect) physics (let* ((rect rect) (solidp (entity-solid-p ob))) (quadtree-delete quadtree ob) ;; check to see if anything is at the new position (multiple-value-bind (box offs) (entity-box ob) (set-vec2 (car rect) (car box)) (set-vec2 (cdr rect) (cdr box)) (gk:nv2+ (car rect) (entity-motion ob)) (let ((collisions (quadtree-select quadtree rect offs)) (collides-p nil)) (loop for c in collisions do (if (and solidp (entity-solid-p c)) (progn (setf collides-p t) (entity-collide ob c)) (entity-touch ob c))) ;; Only move it if it didn't collide, and hasn't ;; been removed in the interim (when (gethash ob objects) (unless (or collides-p) (gk:nv2+ (entity-pos ob) (entity-motion ob))) (quadtree-add quadtree ob)))))))) (defun physics-step (phys) (declare (type physics phys)) (with-slots (objects) phys (loop for ob being each hash-key of objects do (physics-move-object phys ob) (entity-update ob)))) (defun physics-map (function phys) (with-slots (objects) phys (loop for ob being each hash-key of objects do (funcall function ob)))) (defun physics-find (phys box &optional offs) (with-slots (quadtree) phys (quadtree-select quadtree box offs)))
3,031
Common Lisp
.lisp
77
31.441558
70
0.607543
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
c9da4ff8336d3287a5da746361fce8f499520c1ccd877f30697eb138cd1eb18f
13,794
[ -1 ]
13,795
startup.lisp
rpav_spell-and-dagger/src/startup.lisp
(in-package :game) ;;; Entity (defvar +motion-none+) (defvar +motion-up+) (defvar +motion-down+) (defvar +motion-left+) (defvar +motion-right+) (defvar +motions+) (defvar +reverse-motion+) (defvar +default-box+) ;;; Character (defvar *walking*) (defvar *attacking*) (defvar *casting*) (defvar *weapon*) (defvar +game-char-bbox+) (defvar +interact-box-left+) (defvar +interact-box-right+) (defvar +interact-box-up+) (defvar +interact-box-down+) (defvar +motion-mask+) ;;; simple-mob (defvar +simple-mob-bbox+) ;;; Spells (defvar +spell-bbox+) ;;; spawner (defvar +spawner-bbox+) ;;; Static startup initialization (defun static-startup () (setf +motion-none+ (gk-vec2 0 0)) (setf +motion-up+ (gk-vec2 0 1)) (setf +motion-down+ (gk-vec2 0 -1)) (setf +motion-left+ (gk-vec2 -1 0)) (setf +motion-right+ (gk-vec2 1 0)) (setf +motions+ (list +motion-up+ +motion-down+ +motion-left+ +motion-right+)) (setf +reverse-motion+ `((,+motion-none+ . ,+motion-none+) (,+motion-up+ . ,+motion-down+) (,+motion-down+ . ,+motion-up+) (,+motion-left+ . ,+motion-right+) (,+motion-right+ . ,+motion-left+))) (setf +default-box+ (cons (gk-vec2 0 0) (gk-vec2 16 16))) ;; We'll generate these later for actions, but we don't want to cons ;; up new strings everytime an action changes (setf *walking* `((,+motion-up+ . "ranger-f/walk-up") (,+motion-down+ . "ranger-f/walk-down") (,+motion-left+ . "ranger-f/walk-left") (,+motion-right+ . "ranger-f/walk-right"))) (setf *attacking* `((,+motion-up+ . "ranger-f/atk-up") (,+motion-down+ . "ranger-f/atk-down") (,+motion-left+ . "ranger-f/atk-left") (,+motion-right+ . "ranger-f/atk-right"))) (setf *casting* `((,+motion-up+ . "ranger-f/cast-up") (,+motion-down+ . "ranger-f/cast-down") (,+motion-left+ . "ranger-f/cast-left") (,+motion-right+ . "ranger-f/cast-right"))) (setf *weapon* `((,+motion-up+ . "weapon/sword_up.png") (,+motion-down+ . "weapon/sword_down.png") (,+motion-left+ . "weapon/sword_left.png") (,+motion-right+ . "weapon/sword_right.png"))) (setf +game-char-bbox+ (cons (gk-vec2 4 1) (gk-vec2 7 4))) (setf +interact-box-left+ (box -1 7 4 2)) (setf +interact-box-right+ (box 2 7 14 2)) (setf +interact-box-up+ (box 7 0 2 16)) (setf +interact-box-down+ (box 7 -4 2 16)) (setf +motion-mask+ `((,+motion-left+ . #b1000) (,+motion-right+ . #b0001) (,+motion-up+ . #b0100) (,+motion-down+ . #b0010))) (setf +simple-mob-bbox+ (cons (gk-vec2 2 2) (gk-vec2 14 12))) (setf +spell-bbox+ (cons (gk-vec2 4 4) (gk-vec2 8 8))) (setf +spawner-bbox+ (cons (gk-vec2 4 4) (gk-vec2 8 8))))
2,910
Common Lisp
.lisp
84
29.107143
80
0.574741
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
ec48121317ab250e9c70433810ef844a3f868efbdc8c96400b0bfa8d20f39c4e
13,795
[ -1 ]
13,796
anim.lisp
rpav_spell-and-dagger/src/anim.lisp
(in-package :game) ;;; Animation defines parameters for a particular animation, e.g. length, ;;; implements "doing" the animation, etc (defclass animation () ()) (defgeneric animation-instance (animation object &key &allow-other-keys) (:documentation "Create an appropriate ANIM-STATE for ANIMATION, given `OBJECT` to be animated and any other optional parameters.") (:method (a o &key on-stop &allow-other-keys) (make-instance 'anim-state :animation a :object o :on-stop on-stop))) ;;; ANIM-STATE keeps the _state_ of any active animation, so you can ;;; use the same ANIMATION instance for multiple different ongoing ;;; animations (defclass anim-state () ((animation :initarg :animation) (object :initarg :object :accessor anim-state-object) (start-time :initform 0 :accessor anim-state-start-time) (on-stop :initform nil :initarg :on-stop :accessor anim-state-on-stop))) (defgeneric anim-delta-time (anim-state) (:documentation "Return the current delta-time for `ANIM-STATE`") (:method ((s anim-state)) (with-slots (start-time) s (- *time* start-time)))) (defgeneric anim-normal-time (anim-state) (:documentation "Return the normalized time for `ANIM-STATE`, if its animation has a duration, or `NIL`.") (:method ((s anim-state)) (with-slots ((a animation)) s (with-slots ((dur duration)) a (when dur (/ (anim-delta-time s) dur)))))) (defgeneric animation-begin (anim anim-state) (:documentation "Called when the animation ANIM is started by ANIM-PLAY.") (:method ((a animation) state) (setf (slot-value state 'start-time) *time*))) (defgeneric animation-update (anim anim-state) (:documentation "Perform any updates for ANIMATION given ANIM-STATE. Specialize on one or both.")) (defgeneric animation-stopped (anim anim-state) (:documentation "Called when an animation is stopped, naturally or manually.") (:method ((a animation) s) (with-slots (on-stop) s (when on-stop (funcall on-stop s))))) ;; ANIMATION-PERIODIC (defclass animation-periodic (animation) ((duration :initform nil :initarg :duration))) (defmethod animation-update ((a animation-periodic) s) (with-slots (duration) a (when (and duration (>= (anim-normal-time s) 1.0)) (anim-stop *anim-manager* s)))) ;; ANIM-MANAGER (defclass anim-manager () ((animations :initform (make-hash-table)))) (defun anim-play (manager &rest anim-states) (let ((*anim-manager* manager)) (with-slots (animations) manager (loop for as in anim-states do (with-slots (animation) as (setf (gethash as animations) t) (animation-begin animation as)))))) (defun anim-update (manager) (let ((*anim-manager* manager)) (with-slots (animations) manager (loop for as being each hash-key in animations for i from 0 do (with-slots (animation) as (animation-update animation as)))))) (defun anim-stop (manager &rest anim-states) (let ((*anim-manager* manager)) (with-slots (animations) manager (loop for as in anim-states do (when (remhash as animations) (animation-stopped (slot-value as 'animation) as)))))) ;; spritesheet-anim ;;; If this were all really proper we'd keep a ref to the spritesheet. (defclass anim-sprite (animation) ((anim :initform nil :accessor anim-sprite-anim) (frame-length :initarg :frame-length :initform (/ 180.0 1000) :accessor anim-sprite-frame-length) (count :initform nil :initarg :count :accessor anim-sprite-count)) (:documentation "OBJECT should be a SPRITE.")) (defmethod initialize-instance :after ((a anim-sprite) &key name &allow-other-keys) (with-slots (anim) a (setf anim (find-anim (asset-anims *assets*) name)))) (defmethod print-object ((a anim-sprite) s) (with-slots (anim) a (print-unreadable-object (a s :type t) (format s "(FIRST-INDEX: ~A)" (sprite-anim-frame anim 0))))) (defmethod animation-begin ((a anim-sprite) s) (call-next-method) (with-slots (anim) a (with-slots (object) s (setf (sprite-index object) (sprite-anim-frame anim 0))))) (defmethod animation-update ((a anim-sprite) state) (with-slots (anim count frame-length) a (with-slots (object start-time) state (when object (let* ((frame-count (sprite-anim-length anim)) (delta (- *time* start-time)) (frame (truncate (* frame-count (mod (/ delta (* frame-count frame-length)) 1.0)))) (c (truncate (/ delta (* frame-count frame-length))))) (if (and count (>= c count)) (anim-stop *anim-manager* state) (setf (sprite-index object) (sprite-anim-frame anim frame)))))))) ;; anim-function (defclass anim-function (animation-periodic) ((function :initform (constantly 0.0) :initarg :function)) (:documentation "Call `FUNCTION` every update. It will be passed `OBJECT` and `TIME`. If `DURATION` is non-NIL, `TIME` will be normalized 0..1 over the duration. Otherwise, it will be the delta-time.")) (defmethod animation-update ((a anim-function) s) (with-slots (function) a (with-slots (object) s (let ((time (or (anim-normal-time s) (anim-delta-time s)))) (funcall function object time)))) (call-next-method))
5,426
Common Lisp
.lisp
123
38.414634
100
0.666667
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
2c4d5ace43b61bb5e72988c903906f7cba77fc585b6c9954aaa4d2c71731fb7a
13,796
[ -1 ]
13,797
assets.lisp
rpav_spell-and-dagger/src/assets.lisp
(in-package :game) (defun get-path (&rest dirs) (let* ((argv0 (if build:*binary* (first sb-ext:*posix-argv*) (asdf:component-pathname (asdf:find-system :spell-and-dagger)))) (path (merge-pathnames (string-join dirs "/") argv0))) (unless (probe-file path) (error "File not found: ~A" path)) (format t "Find ~A~%" path) path)) (defclass asset-pack () ((title :reader asset-title) (proj :initform (gk-mat4) :reader asset-proj) (font :reader asset-font) (spritesheet :reader asset-sheet) (anims :reader asset-anims))) (defun load-assets (gk) (let ((pack (make-instance 'asset-pack))) (with-slots (proj font title spritesheet anims tm) pack (with-bundle (b) (let* ((config (make-instance 'cmd-list :subsystem :config)) (ortho (cmd-tf-ortho proj 0 256 0 144 -10000 10000)) (load-title (cmd-image-create (get-path "assets" "image" "title.png") :mag :nearest)) (load-sprites (cmd-spritesheet-create (get-path "assets" "image" "spritesheet.json") :gk-ssf-texturepacker-json :flags '(:flip-y))) (load-font (cmd-font-create "hardpixel" (get-path "assets" "font" "hardpixel.ttf")))) (cmd-list-append config ortho load-title load-sprites load-font) (bundle-append b config) (gk:process gk b) (setf font (font-create-id load-font)) (setf title (image-create-id load-title)) (setf spritesheet (make-sheet load-sprites)) (setf anims (make-instance 'sheet-animations :sheet spritesheet))))) pack))
1,832
Common Lisp
.lisp
40
33.525
84
0.550895
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
6b2e8f42e2da11ef906cd6b819a30beb74b0817d9de0493d8d47026fecfc9529
13,797
[ -1 ]
13,798
map-phase.lisp
rpav_spell-and-dagger/src/phases/map-phase.lisp
(in-package :game) (defclass map-phase (game-phase) ((map-screen :initform (make-instance 'map-screen)))) (defmethod initialize-instance :after ((p map-phase) &key &allow-other-keys) (with-slots ((ms map-screen)) p (let* ((sprite (make-instance 'sprite :pos (gk-vec4 0 0 0 1) :sheet (asset-sheet *assets*) :key 1 :index (find-anim-frame (asset-anims *assets*) "ranger-f/walk-down" 1)))) (setf (game-window-map-screen *window*) ms) (setf (current-char) (make-instance 'game-char :sprite sprite))))) (defmethod phase-start ((p map-phase)) (phase-resume p)) (defmethod phase-resume ((p map-phase)) (ps-incref *ps*) (with-slots (map-screen) p (setf (ui-visible map-screen) t)) (unless (current-map) (map-change *default-map*))) (defmethod phase-pause ((p map-phase)) (clear-motion-bits (current-char))) (defmethod phase-finish ((p map-phase)) (with-slots (map-screen) p (setf (ui-visible map-screen) nil))) (defmethod phase-show-textbox ((phase map-phase) text) (ps-interrupt (make-instance 'text-phase :text text))) (defun show-textbox (text) (phase-show-textbox (ps-cur-phase) text)) (defun game-over () (ps-push (make-instance 'game-over-phase)) (ps-decref)) ;;; huge hack, yes (defun update-spell (id) (let ((map-screen (game-window-map-screen *window*))) (with-slots (hud) map-screen (hud-set-spell hud id)))) (defun phase-to-endgame () (ps-replace (make-instance 'end-game-phase)))
1,546
Common Lisp
.lisp
41
32.756098
88
0.649264
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
3ec1e8c18f796afa1c4edede8154b87ba7d41bdfbc4eae780a913825b6a18a01
13,798
[ -1 ]
13,799
end-game.lisp
rpav_spell-and-dagger/src/phases/end-game.lisp
(in-package :game) ;; (defclass end-game-phase (game-phase) ()) (defmethod phase-start ((p end-game-phase)) (setf (current-map) nil) (setf (current-char) nil) (show-textbox "You trudge north across a bridge and deep canyon you don't remember existing. What has happened to your home? To the world? Perhaps answers lie in the world beyond...")) (defmethod phase-resume ((p end-game-phase)) (ps-incref) (let ((screen (make-instance 'the-end-screen))) (setf (ui-visible screen) t))) (defmethod phase-show-textbox ((phase end-game-phase) text) (ps-interrupt (make-instance 'text-phase :map nil :text text))) (defmethod phase-back ((p end-game-phase)) (ps-pop-to 'title-phase))
702
Common Lisp
.lisp
15
44.066667
189
0.712188
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
7e423157ee3563a5d6430610e4769a7f97739077fbf8b75415fcc657907b30ed
13,799
[ -1 ]
13,800
text-phase.lisp
rpav_spell-and-dagger/src/phases/text-phase.lisp
(in-package :game) (defclass text-phase (game-phase) ((text-screen :initform nil))) (defmethod initialize-instance :after ((p text-phase) &key text (map t) &allow-other-keys) (with-slots (text-screen) p (setf text-screen (make-instance 'text-screen :text text :map map)))) (defmethod phase-resume ((p text-phase)) (ps-incref *ps*) (with-slots (text-screen) p (setf (ui-visible text-screen) t))) (defmethod phase-back ((p text-phase)) (ps-decref *ps*))
484
Common Lisp
.lisp
13
33.769231
90
0.683084
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
b6f1ce28dab9dcc99cb72651e589e9d2f8e29af4483a11687b00a7ce726baf51
13,800
[ -1 ]
13,801
game-over.lisp
rpav_spell-and-dagger/src/phases/game-over.lisp
(in-package :game) (defclass game-over-phase (game-phase) ((screen :initform (make-instance 'game-over-screen)))) (defmethod phase-resume ((p game-over-phase)) (ps-incref) (with-slots (screen) p (setf (current-map) nil) (setf (current-char) nil) (setf (ui-visible screen) t))) (defmethod phase-back ((p game-over-phase)) (ps-pop-to 'title-phase))
370
Common Lisp
.lisp
11
30.545455
57
0.688202
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
0dda6d33d91d98d8eac07cb75c499c9b94246276577cac12cd17854a4ecb4cc5
13,801
[ -1 ]
13,802
title.lisp
rpav_spell-and-dagger/src/phases/title.lisp
(in-package :game) (defclass title-phase (game-phase) ((screen :initform (make-instance 'title-screen)))) (defmethod phase-resume ((p title-phase)) (ps-incref) (with-slots (screen) p (setf (ui-visible screen) t))) (defun title-start () (ps-push (make-instance 'map-phase)) (ps-decref))
303
Common Lisp
.lisp
10
27.6
53
0.693103
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
1fda088d8f875422a25ee7892ed5e7d36dbe8aa5e223e724c462f5ca97d5de58
13,802
[ -1 ]
13,803
spell-interacts.lisp
rpav_spell-and-dagger/src/entity/spell-interacts.lisp
(in-package :game) (defun breakable-do-break (e) (with-slots (sprite brokenp) e (unless brokenp (let ((break-name (entity-property e :broken))) (setf (sprite-name sprite) break-name brokenp t))))) ;; breakable-base (defclass breakable-base (simple-text) ((brokenp :initform nil :reader breakable-brokenp))) (defmethod initialize-instance :after ((e breakable-base) &key sprite-name &allow-other-keys) (with-slots (pos sprite) e ;; For some bizarre and unknown reason, sprites in an object layer--- ;; nothing else---have their origin at the _lower left_ corner. (incf (vy pos) 16.0) (setf sprite (make-instance 'sprite :key -1 :name sprite-name)))) (defmethod entity-solid-p ((e breakable-base)) (not (breakable-brokenp e))) (defmethod entity-magic-hit :around ((e breakable-base) m) (with-slots (brokenp) e (unless brokenp (call-next-method)))) (defmethod entity-interact ((e breakable-base) a) (with-slots (brokenp props) e (if brokenp (show-textbox (aval :btext props)) (call-next-method)))) ;; breakable (defclass breakable (breakable-base) ()) (defmethod entity-magic-hit ((e breakable) (m spell-explode)) (breakable-do-break e) (when-let ((powerup (if (< (random 1.0) 0.5) (if (< (random 1.0) 0.5) (make-instance 'powerup-life :pos (entity-pos e)) (make-instance 'powerup-magic :pos (entity-pos e)))))) (map-add (current-map) powerup))) ;; fireball-breakable (defclass fireball-breakable (breakable-base) ()) (defmethod entity-magic-hit ((e fireball-breakable) (m spell-fireball)) (breakable-do-break e))
1,708
Common Lisp
.lisp
38
38.763158
93
0.656005
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
84b62c52adfaf7ceb663bc1f01cc841ce534dc0e8c53cdc83a9b2e7bf250aa46
13,803
[ -1 ]
13,804
more-interacts.lisp
rpav_spell-and-dagger/src/entity/more-interacts.lisp
(in-package :game) ;; text-once (defclass text-once (simple-entity) ((text :initform nil) (flag :initform nil))) (defmethod initialize-instance :after ((e text-once) &key props &allow-other-keys) (with-slots (flag text) e (unless (aval :text props) (format t "Warning: Text not specified for ~A~%" (class-name (class-of e)))) (unless (aval :flag props) (format t "Warning: Flag not specified for ~A~%" (class-name (class-of e)))) (when-let (s (aval :text props)) (setf text s)) (if-let (s (aval :flag props)) (setf flag (make-keyword (string-upcase s))) (setf flag 'text-once)))) (defmethod entity-solid-p ((e text-once)) nil) (defmethod entity-touch ((g game-char) (e1 text-once)) (with-slots (text flag) e1 (unless (game-value flag) (show-textbox text) (setf (game-value flag) t)))) ;; end-game (defclass end-game (simple-entity) ()) (defmethod entity-solid-p ((e1 end-game)) nil) (defmethod entity-touch ((g game-char) (e1 end-game)) (phase-to-endgame))
1,023
Common Lisp
.lisp
24
38.875
107
0.664315
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
3cded2144ea5f0ebc535413feaa32a2eee72456ad810f6182cd006e46e9fea39
13,804
[ -1 ]
13,805
spawner.lisp
rpav_spell-and-dagger/src/entity/spawner.lisp
(in-package :game) (defclass spawner (entity) ((last-dead-time :initform nil) (did-spawn-p :initform nil) (type :initform nil) (mob :initform nil))) (defmethod initialize-instance :after ((s spawner) &key props &allow-other-keys) (with-slots ((_type type) size) s (let* ((type (aval :type props)) (anim (find-anim (asset-anims *assets*) type))) (if anim (setf _type type) (format t "Warning: spawner can't find type ~S~%" type))))) (defmethod entity-box ((e spawner)) (with-slots (pos) e (values +spawner-bbox+ pos))) (defmethod entity-solid-p ((e spawner)) nil) (defun spawner-spawn (s) (with-slots (last-dead-time mob type) s (if (delete s (map-find-in-box (current-map) (entity-box s) (entity-pos s))) (progn (setf last-dead-time *time*)) ; Don't continuously try (when type (setf last-dead-time nil) (setf mob (make-instance 'simple-mob :sprite (make-instance 'sprite :index (find-anim-frame (asset-anims *assets*) type 0) :key 1) :name type :pos (entity-pos s))) (map-add (current-map) mob))))) (defmethod entity-update ((e spawner)) (with-slots (type did-spawn-p mob) e (when type (unless did-spawn-p (if (not mob) (spawner-spawn e))))))
1,434
Common Lisp
.lisp
37
29.918919
86
0.569375
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
f6db36254a494ca823408532015e6d7eb35d88a3eb66fb5dc4020d9b99f3e95e
13,805
[ -1 ]
13,806
move-manager.lisp
rpav_spell-and-dagger/src/entity/move-manager.lisp
(in-package :game) ;; MOVE-MANAGER ;;; This is a mixin for things that have complex "walk around" ;;; animations. (defclass move-manager () ((sprite-name :initform nil :initarg :sprite-name) sprite-anim sprite-anim-state)) (defun mm-move-name (mm move) (with-slots (sprite-name) mm (switch (move) (+motion-none+ (string+ sprite-name "walk-down")) (+motion-up+ (string+ sprite-name "walk-up")) (+motion-down+ (string+ sprite-name "walk-down")) (+motion-left+ (string+ sprite-name "walk-left")) (+motion-right+ (string+ sprite-name "walk-right"))))) (defun mm-play-facing (mm facing) (with-slots (sprite) mm (let ((move-name (mm-move-name mm facing))) (setf (sprite-index sprite) (find-anim-frame (asset-anims *assets*) move-name 1))))) (defun mm-play-motion (mm motion) (with-slots (sprite facing sprite-anim sprite-anim-state) mm (unless (eq motion +motion-none+) (setf facing motion)) (let ((move-name (mm-move-name mm motion))) (setf (anim-sprite-anim sprite-anim) (find-anim (asset-anims *assets*) move-name) (anim-sprite-frame-length sprite-anim) (/ 180 1000.0) (anim-sprite-count sprite-anim) nil (anim-state-object sprite-anim-state) sprite (anim-state-on-stop sprite-anim-state) nil) (anim-stop *anim-manager* sprite-anim-state) (if (v2= +motion-none+ motion) (mm-play-facing mm facing) (anim-play *anim-manager* sprite-anim-state))))) (defmethod initialize-instance :after ((mm move-manager) &key props &allow-other-keys) (with-slots (sprite sprite-anim sprite-anim-state sprite-name) mm (unless sprite-name (setf sprite-name (aval :sprite-name props))) (let ((start-name (mm-move-name mm (actor-facing mm)))) (setf sprite (make-instance 'sprite :index (find-anim-frame (asset-anims *assets*) start-name 0))) (setf sprite-anim (make-instance 'anim-sprite :name start-name)) (setf sprite-anim-state (animation-instance sprite-anim nil)) (mm-play-motion mm +motion-none+)))) (defmethod (setf entity-motion) :before (v (mm move-manager)) (mm-play-motion mm v)) (defmethod (setf actor-facing) :after (v (mm move-manager)) (setf (entity-motion mm) +motion-none+) (mm-play-facing mm v))
2,378
Common Lisp
.lisp
50
40.78
87
0.647845
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
7aa621711c931ac3d5fea2529337bd3441331c2324e2af227ae0e7c450a6823f
13,806
[ -1 ]
13,807
npc.lisp
rpav_spell-and-dagger/src/entity/npc.lisp
(in-package :game) ;; BEHAVIOR (defclass behavior () ()) (defgeneric behavior-act (behavior npc interacting-entity) (:documentation "Called when `NPC` is interacted with by `INTERACTING-ENTITY`.") (:method (b npc e) (if-let (text (entity-property npc :text)) (show-textbox text) (show-textbox "...")))) (defclass simple-behavior (behavior) ()) (defclass teacher-behavior (behavior) ()) (defmethod behavior-act ((b teacher-behavior) npc c) (if (game-value :has-spell) (show-textbox "Have you tried it? It can break certain things.") (progn (show-textbox "Let me teach you a useful spell. (Press X to use.)") (setf (game-value :has-spell) t) (char-teach-spell c 'spell-explode)))) ;; NPC (defclass npc (actor move-manager) ((knockback-speed :initform 0.1) (state :initform :starting) (behavior :initform nil) (act-start :initform 0))) (defmethod initialize-instance :after ((e npc) &key props &allow-other-keys) (with-slots (behavior) e (let ((behavior-class (aval :behavior props))) (setf behavior (if behavior-class (make-instance (intern (string-upcase behavior-class) :game)) (make-instance 'simple-behavior)))))) (defmethod entity-interact ((e npc) (g game-char)) (setf (actor-facing e) (aval (actor-facing g) +reverse-motion+)) (with-slots (behavior) e (behavior-act behavior e g))) ;;; This should all be folded into an AI controller and shared with monster (defun npc-change-action (e) (with-slots (state) e (case state (:starting (setf (entity-state e) :waiting)) (:waiting (setf (entity-motion e) (elt +motions+ (random 4))) (nv2* (entity-motion e) 0.5) (setf (entity-state e) :moving)) (:moving (setf (entity-motion e) +motion-none+) (setf (entity-state e) :waiting)))) (with-slots (act-start) e (setf act-start *time*))) (defmethod entity-update ((e npc)) (call-next-method) (with-slots (act-start) e (let ((d (- *time* act-start))) (when (> d (+ 0.5 (random 2.0))) (simple-mob-change-action e))))) ;; fireball-teacher (defclass fireball-teacher (simple-entity) ()) (defmethod initialize-instance :after ((e fireball-teacher) &key sprite-name &allow-other-keys) (with-slots (pos sprite) e (incf (vy pos) 16.0) (setf sprite (make-instance 'sprite :key -1 :name sprite-name)))) (defmethod entity-interact ((e fireball-teacher) (a game-char)) (if (game-value :has-fireball) (show-textbox "Statue of Phoenix. This is where you learned how to cast Fireball. (Press S to switch spells.)") (progn (setf (game-value :has-fireball) t) (char-teach-spell (current-char) 'spell-fireball) (show-textbox "Statue of Phoenix ... you learn how to cast Fireball! (Press S to switch spells.)"))))
2,935
Common Lisp
.lisp
69
36.536232
117
0.643735
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
649fa9cd0bfb14065b5757fa64837425ff88ae1fe845ee179d2b7b3daf519763
13,807
[ -1 ]
13,808
actor.lisp
rpav_spell-and-dagger/src/entity/actor.lisp
(in-package :game) ;; ACTOR (defclass actor (entity) ((life :initform 1 :accessor actor-life) (facing :initform +motion-down+ :accessor actor-facing) (knockback-time :initform 0.3 :accessor actor-knockback-time) (knockback-speed :initform 2.0 :accessor actor-knockback-speed) (hit-start :initform nil)) (:documentation "An actor is something that can move with animation, attack, take damage, etc., i.e. the character or a mob.")) (defgeneric actor-dead-p (actor) (:documentation "True if `ACTOR` is dead and should be (or is) removed.") (:method ((a actor)) (<= (slot-value a 'life) 0))) (defgeneric actor-knockback-begin (actor) (:method ((a actor)))) (defgeneric actor-knockback-end (actor) (:method ((a actor)))) (defun actor-knock-back (actor pos) (with-slots (hit-start) actor (setf hit-start *time*) (setf (entity-motion actor) (relative-motion pos (entity-pos actor))) (nv2* (entity-motion actor) (actor-knockback-speed actor)) (actor-knockback-begin actor))) (defmethod entity-attacked ((e actor) a w) (actor-knock-back e (entity-pos a))) (defmethod entity-update :after ((e actor)) (with-slots (hit-start) e (when hit-start (let ((delta (- *time* hit-start))) (when (> delta 0.2) (setf (entity-motion e) +motion-none+ hit-start nil) (actor-knockback-end e)))))) (defmethod entity-solid-p ((e actor)) (unless (actor-dead-p e) t))
1,451
Common Lisp
.lisp
34
38.382353
75
0.675656
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
3a0952ccd62edd5ec29dbed1ee5bdc8f1f084c66a764631549a06cb0cdd32f7e
13,808
[ -1 ]
13,809
game-char.lisp
rpav_spell-and-dagger/src/entity/game-char.lisp
(in-package :game) ;; Quick take on character (defclass game-char (actor) ((life :initform 5 :reader char-life) (max-life :initform 5 :accessor char-max-life) (magic :initform 5 :reader char-magic) (max-magic :initform 5 :accessor char-max-magic) (spells :initform nil :accessor char-spells) (eqp-spell :initform nil :accessor char-spell) (state :initform :moving) (motion-mask :initform 0) (wpn-box :initform (box 0 0 16 16)) (wpn-pos :initform (gk-vec2 0 0)) wpn-sprite anim anim-state hit-anim hit-ans)) (defmethod initialize-instance :after ((g game-char) &key &allow-other-keys) (with-slots (sprite wpn-sprite anim anim-state hit-anim hit-ans) g (setf anim (make-instance 'anim-sprite :name (aval +motion-down+ *walking*))) (setf anim-state (animation-instance anim nil)) (setf hit-anim (make-instance 'anim-function :duration 0.3 :function (lambda (o d) (with-slots (sprite) o (if (< d 1.0) (setf (sprite-visible sprite) (not (sprite-visible sprite))) (setf (sprite-visible sprite) t)))))) (setf hit-ans (animation-instance hit-anim g)) (setf wpn-sprite (make-instance 'sprite :sheet (asset-sheet *assets*) :index 0 :key 2)) (game-char-play-motion g +motion-none+))) (defmethod entity-box ((e game-char)) (with-slots (pos) e (values +game-char-bbox+ pos))) (defmethod entity-motion ((e actor)) (with-slots (state motion) e (case state (:attacking +motion-none+) (:casting +motion-none+) (otherwise motion)))) (defmethod entity-action ((e game-char) (a (eql :btn1))) (with-slots () e (setf (entity-state e) :attacking) (game-char-play-attack e))) (defmethod entity-action ((e game-char) (a (eql :btn2))) (let* ((map (current-map)) (box (switch ((actor-facing e)) (+motion-up+ +interact-box-up+) (+motion-down+ +interact-box-down+) (+motion-left+ +interact-box-left+) (+motion-right+ +interact-box-right+))) (matches (delete e (map-find-in-box map box (entity-pos e))))) (if matches (entity-interact (car matches) e) (default-interact e nil)))) (defmethod entity-action ((e game-char) (a (eql :btn3))) (when-let (spell (char-spell e)) (let ((cost (spell-cost (car spell)))) (when (> (char-magic e) cost) (decf (char-magic e) cost) (setf (entity-state e) :casting) (game-char-play-cast e))))) (defun char-teach-spell (e spell-name) (pushnew spell-name (char-spells e)) (char-first-spell e)) (defun char-first-spell (e) (setf (char-spell e) (char-spells e)) (update-spell (spell-icon (car (char-spell e))))) (defun char-next-spell (e) (if (cdr (char-spell e)) (progn (setf (char-spell e) (cdr (char-spell e))) (update-spell (spell-icon (car (char-spell e))))) (char-first-spell e))) (defmethod entity-action ((e game-char) (a (eql :btn4))) (char-next-spell e)) (defmethod draw ((e game-char) lists m) (with-slots (sprite wpn-sprite wpn-box wpn-pos) e (draw sprite lists m) (case (entity-state e) (:attacking (when (game-value :has-dagger) (draw wpn-sprite lists m)))))) (defmethod entity-collide ((e game-char) (c link)) (let ((map (entity-property c :map)) (target (entity-property c :target))) (when map (format t "Move via LINK to ~S@~S~%" map target) (map-change map target) (game-char-update-motion e)))) (defmethod entity-collide ((e game-char) (c map-link)) (with-slots (pos) e (let ((map (map-link-map c))) (when map (let ((target (gk-vec2 (vx pos) (vy pos)))) ;; Could we do this smarter? Probably. (case (map-link-direction c) (:n (setf (vy target) 0.0)) (:s (setf (vy target) (- 144 16.0))) (:e (setf (vx target) 0.0)) (:w (setf (vx target) (- 256 16.0)))) (map-change map target) (game-char-update-motion e)))))) (defmethod entity-collide ((e game-char) (c simple-mob)) (with-slots (life hit-start hit-ans) e (unless hit-start (decf life) (anim-play *anim-manager* hit-ans) (if (actor-dead-p e) (game-over) (actor-knock-back e (entity-pos c)))))) (defmethod entity-collide ((e simple-mob) (g game-char)) (entity-collide g e)) (defmethod actor-knockback-end ((a game-char)) (game-char-update-motion a)) (defun game-char-update-motion (e) (with-slots (motion-mask state) e (when (eq state :moving) (let ((motion (or (akey motion-mask +motion-mask+) +motion-none+))) (setf (entity-motion e) motion) (game-char-play-motion e motion))))) (defun set-motion-bit (e direction) (with-slots (motion-mask) e (let ((mask (aval direction +motion-mask+))) (setf motion-mask (logior motion-mask mask))) (game-char-update-motion e))) (defun clear-motion-bit (e direction) (with-slots (motion-mask) e (let ((mask (aval direction +motion-mask+))) (setf motion-mask (logandc2 motion-mask mask))) (game-char-update-motion e))) (defun clear-motion-bits (e) (setf (slot-value e 'motion-mask) 0) (game-char-update-motion e)) (defmethod (setf char-life) (v (c game-char)) (with-slots (life max-life) c (setf life v) (when (> life max-life) (setf life max-life)) life)) (defmethod (setf char-magic) (v (c game-char)) (with-slots (magic max-magic) c (setf magic v) (when (> magic max-magic) (setf magic max-magic)) magic)) ;; util (defun game-char-play-motion (e m) (with-slots (sprite facing anim anim-state) e (unless (eq m +motion-none+) (setf facing m)) (setf (anim-sprite-anim anim) (find-anim (asset-anims *assets*) (aval facing *walking*)) (anim-sprite-frame-length anim) (/ 180 1000.0) (anim-sprite-count anim) nil (anim-state-object anim-state) sprite (anim-state-on-stop anim-state) nil) (anim-stop *anim-manager* anim-state) (if (eq +motion-none+ m) (setf (sprite-index sprite) (find-anim-frame (asset-anims *assets*) (aval facing *walking*) 1)) (anim-play *anim-manager* anim-state)))) (defun game-char-play-attack (e) (with-slots (sprite facing wpn-sprite anim anim-state) e (setf (anim-sprite-count anim) 1 (anim-sprite-frame-length anim) (/ 20 1000.0) (anim-sprite-anim anim) (find-anim (asset-anims *assets*) (aval facing *attacking*)) (anim-state-on-stop anim-state) (lambda (s) (declare (ignore s)) (game-char-end-attack e))) (setf (sprite-index wpn-sprite) (find-frame (asset-sheet *assets*) (aval facing *weapon*))) (set-vec2 (sprite-pos wpn-sprite) (sprite-pos sprite)) (anim-play *anim-manager* anim-state))) (defun game-char-play-cast (e) (with-slots (sprite facing wpn-sprite anim anim-state) e (setf (anim-sprite-count anim) 1 (anim-sprite-frame-length anim) (/ 80 1000.0) (anim-sprite-anim anim) (find-anim (asset-anims *assets*) (aval facing *casting*)) (anim-state-on-stop anim-state) (lambda (s) (declare (ignore s)) (game-char-end-cast e))) (anim-play *anim-manager* anim-state))) (defun game-char-update-wpn-box (e) (with-slots (wpn-box wpn-pos facing) e (set-vec2 wpn-pos facing) (nv2* wpn-pos 8) (nv2+ wpn-pos (entity-pos e)))) (defun game-char-do-attack (e) (game-char-update-wpn-box e) (with-slots (wpn-box wpn-pos) e (when (game-value :has-dagger) (let* ((map (current-map)) (hits (delete e (map-find-in-box map wpn-box wpn-pos)))) (loop for ob in hits do (entity-attacked ob e nil)))))) (defun game-char-do-cast (e) (let ((spell-class (car (char-spell e)))) (when spell-class (let ((spell (make-instance spell-class))) (setf (entity-motion spell) (actor-facing e) (entity-pos spell) (actor-facing e)) (nv2* (entity-pos spell) 8.0) (nv2+ (entity-pos spell) (entity-pos e)) (map-add (current-map) spell))))) (defun game-char-end-attack (e) (game-char-do-attack e) (setf (entity-state e) :moving) (game-char-update-motion e)) (defun game-char-end-cast (e) (game-char-do-cast e) (setf (entity-state e) :moving) (game-char-update-motion e)) ;; dagger-pickup ;;; This is a hack for the jam, it should be moved into a more general ;;; class, more infrastructure for items etc. (defclass pickup-dagger (simple-entity) ()) (defmethod initialize-instance :after ((e pickup-dagger) &key sprite-name &allow-other-keys) (with-slots (pos sprite) e (incf (vy pos) 16.0) (setf sprite (make-instance 'sprite :key -1 :name sprite-name)))) (defmethod entity-interact ((e pickup-dagger) (g game-char)) (setf (game-value :has-dagger) t) (map-remove (current-map) e) (show-textbox "You grab the dagger stuck in the ground. This might help with those blobs, but you're still not sure how to get out. (Press Z to attack.) Monsters appeared!") (map-change "x-dungeon" (entity-pos g)))
9,726
Common Lisp
.lisp
233
33.699571
154
0.595558
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
928867f6aac8cf0b7915fd1fb98bd9553f651b3d1b524cf111e7248df18e59d5
13,809
[ -1 ]
13,810
simple.lisp
rpav_spell-and-dagger/src/entity/simple.lisp
(in-package :game) ;; simple-entity (defclass simple-entity (entity) ((box :initform nil))) (defmethod initialize-instance :after ((e simple-entity) &key &allow-other-keys) (with-slots (box) e (setf box (cons (entity-pos e) (entity-size e))))) (defmethod entity-box ((e simple-entity)) (slot-value e 'box)) ;; simple-text (defclass simple-text (simple-entity) ()) (defmethod initialize-instance :after ((e simple-text) &key props &allow-other-keys) (with-slots (text) e (unless (aval :text props) (format t "Warning: String not specified for ~A~%" (class-name (class-of e)))))) (defmethod entity-solid-p ((e simple-text)) nil) (defmethod entity-interact ((e simple-text) a) (with-slots (props) e (show-textbox (aval :text props)))) ;; simple-blocker (defclass simple-blocker (simple-text) ()) (defmethod entity-solid-p ((e simple-blocker)) t) ;; link (defclass link (simple-entity) ()) ;; map-link (defclass map-link (simple-entity) ((map :initarg :map :initform nil :reader map-link-map) (direction :initarg :direction :initform nil :reader map-link-direction)))
1,134
Common Lisp
.lisp
28
37
84
0.692942
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
7dbac1d735a22e0bd36634dd99c535613d1379674e911d0ed3313bee64afe6c0
13,810
[ -1 ]
13,811
simple-mob.lisp
rpav_spell-and-dagger/src/entity/simple-mob.lisp
(in-package :game) (defclass simple-mob (actor) ((life :initform 3) (state :initform :starting) (act-start :initform 0) (name :initform nil) (hit-name :initform nil) (anim :initform nil) (anim-state :initform nil))) (defmethod initialize-instance :after ((a simple-mob) &key name &allow-other-keys) (with-slots (anim anim-state sprite (_name name) hit-name) a (when name (setf _name name hit-name (string+ name "-hit")) (setf anim (make-instance 'anim-sprite :name name)) (setf anim-state (animation-instance anim sprite)) (anim-play *anim-manager* anim-state)))) (defmethod entity-box ((e simple-mob)) (with-slots (pos) e (values +simple-mob-bbox+ pos))) (defun spawn-simple-random-powerup (pos &key (pct 0.5) bounce) (let ((r (random 1.0))) (when (< r pct) (let* ((r (random 1.0)) (type (cond ((< r 0.5) 'powerup-life) ((< r 1.0) 'powerup-magic)))) (when type (map-add (current-map) (make-instance type :bounce-in bounce :pos pos))))))) (defmethod entity-attacked ((e simple-mob) a w) (with-slots (anim anim-state life hit-name) e (decf life) (if (actor-dead-p e) (unless (eq (entity-state e) :die) (spawn-simple-random-powerup (entity-pos e) :bounce t) (setf (entity-state e) :die (entity-motion e) +motion-none+ (anim-sprite-anim anim) (find-anim (asset-anims *assets*) "fx/splat") (anim-sprite-frame-length anim) (/ 100 1000.0) (anim-sprite-count anim) 1 (anim-state-on-stop anim-state) (lambda (s) (mob-died e))) (anim-play *anim-manager* anim-state)) (progn (setf (anim-sprite-anim anim) (find-anim (asset-anims *assets*) hit-name) (anim-sprite-frame-length anim) (/ 20 1000.0)) (anim-play *anim-manager* anim-state) (call-next-method))))) (defmethod mob-died ((m simple-mob)) (map-remove (current-map) m)) (defmethod actor-knockback-end :after ((a simple-mob)) (with-slots (anim name) a (unless (actor-dead-p a) (setf (anim-sprite-anim anim) (find-anim (asset-anims *assets*) name) (anim-sprite-frame-length anim) (/ 180 1000.0))))) (defun simple-mob-change-action (e) (with-slots (state) e (case state (:starting (setf (entity-state e) :waiting)) (:waiting (setf (entity-motion e) (elt +motions+ (random 4))) (nv2* (entity-motion e) 0.5) (setf (entity-state e) :moving)) (:moving (setf (entity-motion e) +motion-none+) (setf (entity-state e) :waiting)))) (with-slots (act-start) e (setf act-start *time*))) (defmethod entity-update ((e simple-mob)) (call-next-method) (with-slots (act-start) e (let ((d (- *time* act-start))) (when (> d 1) (simple-mob-change-action e)))))
2,958
Common Lisp
.lisp
74
32.540541
85
0.593739
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
e38ef624fae71be21c9197876433d2f4f12d773a695f1f5baf8cbcc0137c78e2
13,811
[ -1 ]
13,812
powerup.lisp
rpav_spell-and-dagger/src/entity/powerup.lisp
(in-package :game) (defparameter +powerup-bounce+ (make-instance 'anim-function :duration 0.2 :function (lambda (o d) (if (< d 1.0) ;; Cheap/fake bounce; we could increase the bounces by ;; increasing the muliplier and time but this should be ;; short. Could even do falloff, but useless with 1 bounce. (if (evenp (truncate (* d 2))) (setf (vy (entity-motion o)) 1.0) (setf (vy (entity-motion o)) -1.0)) (setf (vx (entity-motion o)) 0.0 (vy (entity-motion o)) 0.0))))) (defclass powerup (entity) ((anim-state :initform nil))) (defmethod initialize-instance :after ((p powerup) &key bounce-in &allow-other-keys) (when bounce-in (with-slots (anim-state) p (setf (vx (entity-motion p)) (if (< (random 1.0) 0.5) -1.0 1.0)) (setf anim-state (animation-instance +powerup-bounce+ p)) (anim-play *anim-manager* anim-state)))) (defmethod entity-solid-p ((e powerup)) nil) (defmethod entity-touch :after ((g game-char) (e powerup)) (map-remove (current-map) e)) ;; POWERUP-LIFE (defclass powerup-life (powerup) ((sprite :initform (make-instance 'sprite :key 0 :name "powerup/crystal-red.png")))) (defmethod entity-touch ((g game-char) (e powerup-life)) (incf (char-life g) 2)) ;; POWERUP-MAGIC (defclass powerup-magic (powerup) ((sprite :initform (make-instance 'sprite :key 0 :name "powerup/crystal-blue.png")))) (defmethod entity-touch ((g game-char) (e powerup-magic)) (incf (char-magic g) 2))
1,559
Common Lisp
.lisp
37
36.513514
87
0.639974
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
435745fe345c0917436fce787e409d5304a57e9896942209629e6995c465513c
13,812
[ -1 ]
13,813
spell.lisp
rpav_spell-and-dagger/src/entity/spell.lisp
(in-package :game) ;; SPELL (defclass spell (entity) ((sprite :initform (make-instance 'sprite :key 0)) (speed :initform 1.0) anim anim-state)) (defgeneric spell-icon (spell) (:documentation "Return the index for `SPELL`'s icon.") (:method (s) (find-frame (asset-sheet *assets*) "nosprite.png"))) ;;; This is kinda dumb. We need a real inventory system to keep spell ;;; instances. Then it'll just be a slot value. (defgeneric spell-cost (spell) (:method (s) 0.0)) (defmethod initialize-instance :after ((e spell) &key &allow-other-keys) (with-slots (anim anim-state sprite) e (setf anim-state (animation-instance anim sprite) (anim-state-on-stop anim-state) (lambda (s) (map-remove (current-map) e))))) (defmethod entity-box ((e spell)) (with-slots (pos) e (values +spell-bbox+ pos))) (defmethod (setf entity-motion) :after (v (e spell)) (with-slots (motion speed) e (nv2* motion speed))) (defmethod entity-solid-p ((e spell)) nil) (defmethod entity-added-to-map (map (e spell)) (with-slots (anim anim-state) e (anim-play *anim-manager* anim-state))) (defmethod entity-touch ((e spell) e2) #++ (when (and (entity-solid-p e2) (not (eq (current-char) e2))) (map-remove (current-map) e))) ;; SPELL-EXPLODE (defclass spell-explode (spell) ((speed :initform 1.2) (anim :initform (make-instance 'anim-sprite :name "spell/explode" :frame-length (/ 100 1000.0) :count 1)))) (defmethod spell-icon ((s (eql 'spell-explode))) (find-anim-frame (asset-anims *assets*) "spell/explode" 3)) (defmethod entity-touch ((e1 spell-explode) o) (entity-magic-hit o e1) (call-next-method)) ;; SPELL-FIREBALL (defclass spell-fireball (spell) ((speed :initform 1.2) (anim :initform (make-instance 'anim-sprite :name "spell/ias-fireball" :frame-length (/ 100 1000.0) :count 1)))) (defmethod spell-icon ((s (eql 'spell-fireball))) (find-anim-frame (asset-anims *assets*) "spell/ias-fireball" 0)) (defmethod spell-cost ((s (eql 'spell-fireball))) 2.0) (defmethod entity-touch ((e1 spell-fireball) o) (entity-magic-hit o e1) (call-next-method))
2,281
Common Lisp
.lisp
59
33.20339
72
0.642922
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
fb005438224b635954c23d36e45e69197639f550d1608ea5bbe67e6fcd7cac8a
13,813
[ -1 ]
13,814
textbox.lisp
rpav_spell-and-dagger/src/ui/textbox.lisp
(in-package :game) (defclass textbox (ui) ((text :initform nil :initarg :text :accessor textbox-text) (margin :initform 50.0 :initarg :margin) (path-cmd :initform nil) (fontstyle-cmd :initform nil) (text-cmd :initform nil))) (defmethod initialize-instance :after ((box textbox) &key &allow-other-keys) (with-slots (text path-cmd fontstyle-cmd text-cmd (m margin)) box (multiple-value-bind (w h) (window-size) (setf path-cmd (cmd-path (list :begin :rect m m (- w (* 2 m)) (/ h 3.0) :fill-color-rgba 0 0 128 200 :stroke-color-rgba 255 255 255 255 :stroke-width 5.0 :line-join gk.raw:+gk-linecap-round+ :fill :stroke :fill-color-rgba 255 255 255 255)) fontstyle-cmd (cmd-font-style :size (/ h 15.0) :align '(:top :left)) text-cmd (cmd-text text :break-width (- w (* 4 m)) :x (* m 1.4) :y (* m 1.2)))))) (defmethod (setf textbox-text) :after (v (box textbox)) (with-slots (text-cmd) box (setf (text-string text-cmd) v))) (defmethod draw ((box textbox) lists m) (with-slots (path-cmd fontstyle-cmd text-cmd) box (with-slots (ui-list) lists (cmd-list-append ui-list path-cmd fontstyle-cmd text-cmd))))
1,514
Common Lisp
.lisp
42
25.095238
76
0.517735
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
85fc8df7a27cc591994fd9f6edee06c3638e43f6d54cc8cea79796025605d73e
13,814
[ -1 ]
13,815
hud.lisp
rpav_spell-and-dagger/src/ui/hud.lisp
(in-package :game) (defclass hud (ui) (health magic p1 fs1 p2 fs2 (text-cmds :initform nil) (wpn-sprite :initform (make-instance 'sprite :key 9999)) (spell-sprite :initform (make-instance 'sprite :key 9999)) wpn-box spell-box)) (defmethod initialize-instance ((hud hud) &key &allow-other-keys) (call-next-method) (with-slots (health magic p1 fs1 p2 fs2 text-cmds wpn-box spell-box wpn-sprite spell-sprite) hud (multiple-value-bind (w h) (window-size) (declare (ignorable w h)) (let* ((m (* *scale* 2.0)) (fsize (/ h 15.0)) (bar-x (* *scale* 11.0)) (box-size (* *scale* 16.0)) (health-offset (* 1.2 m)) (magic-offset (+ (* 2.4 m) (* fsize 0.5)))) ;; This is just a hack, we _could_ do this with multiple ;; commands and redraw the healthbar and shadow using the same ;; path command. Or we could just draw it twice using 1. (setf health (cmd-path (list :begin :rect bar-x health-offset 0 (* 4 *scale*) :fill-color-rgba 255 0 0 255 :fill :begin :rect bar-x health-offset 0 (* 4 *scale*) :stroke-color-rgba 255 255 255 255 :stroke-width *scale* :stroke))) (setf magic (cmd-path (list :begin :rect bar-x magic-offset 16 (* 4 *scale*) :fill-color-rgba 0 0 255 255 :fill :begin :rect bar-x magic-offset 16 (* 4 *scale*) :stroke-color-rgba 255 255 255 255 :stroke-width *scale* :stroke))) (setf spell-box (cmd-path (list :begin :rect (- w m box-size) m box-size box-size :stroke-color-rgba 200 200 200 255 :stroke-width *scale* :stroke))) (setf wpn-box (cmd-path (list :begin :rect (- w m m (* 2 box-size)) m box-size box-size :stroke-color-rgba 200 200 200 255 :stroke-width *scale* :stroke))) (setf (sprite-pos spell-sprite) (gk-vec2 (- 256 2 16) (- 144 2 16))) (setf (sprite-name spell-sprite) "spell/ias_fireball_0.png") (setf (sprite-pos wpn-sprite) (gk-vec2 (- 256 4 32) (- 144 2 16))) (setf (sprite-name wpn-sprite) "weapon/dagger_icon.png") (setf p1 (cmd-path (list :fill-color-rgba 0 0 0 255 :tf-translate *scale* *scale*)) fs1 (cmd-font-style :size fsize) p2 (cmd-path (list :fill-color-rgba 255 255 255 255 :tf-identity)) fs2 (cmd-font-style :size fsize)) (appendf text-cmds (list (cmd-text "L" :x m :y (+ m (* fsize 0.5))) (cmd-text "M" :x m :y (+ (* 2.2 m) fsize)))))))) (defun hud-update (hud) (with-slots (health magic) hud (let* ((c (current-char)) (player-health (* *scale* (actor-life c))) (max-health (* *scale* (char-max-life c))) (player-magic (* *scale* (char-magic c))) (max-magic (* *scale* (char-max-magic c)))) (setf (cmd-path-elt health 4) player-health (cmd-path-elt health 16) max-health) (setf (cmd-path-elt magic 4) player-magic (cmd-path-elt magic 16) max-magic)))) (defmethod draw ((hud hud) lists m) (hud-update hud) (with-slots (ui-list sprite-list) lists (with-slots (health magic p1 fs1 p2 fs2 text-cmds wpn-box spell-box spell-sprite wpn-sprite) hud (cmd-list-append ui-list p1 fs1) (apply #'cmd-list-append ui-list text-cmds) (cmd-list-append ui-list p2 fs2) (apply #'cmd-list-append ui-list text-cmds) (cmd-list-append ui-list health magic wpn-box spell-box) (when (game-value :has-dagger) (draw wpn-sprite lists m)) (when (char-spell (current-char)) (draw spell-sprite lists m))))) (defun hud-set-spell (hud id) (when id (with-slots (spell-sprite) hud (setf (sprite-index spell-sprite) id))))
4,610
Common Lisp
.lisp
107
29.168224
76
0.492205
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
1d6051c68a4442d348965460398ccbc2ed97fa6406c771a049d97d365348ede4
13,815
[ -1 ]
13,816
game-over-screen.lisp
rpav_spell-and-dagger/src/ui/game-over-screen.lisp
(in-package :game) (defclass game-over-screen (screen) (text style)) (defmethod initialize-instance ((s game-over-screen) &key &allow-other-keys) (with-slots (text style) s (multiple-value-bind (w h) (window-size) (setf text (cmd-text "Game Over" :x (/ w 2.0) :y (/ h 2.0)) style (cmd-font-style :size (/ h 5.0) :align '(:middle :center)))))) (defmethod draw ((s game-over-screen) lists m) (with-slots (ui-list) lists (with-slots (text style) s (cmd-list-append ui-list style text)))) (defmethod key-event ((s game-over-screen) key state) (when (eq state :keydown) (case key (:scancode-z (ps-back)) (:scancode-a (ps-back)) (:scancode-x (ps-back)) (:scancode-s (ps-back))))) (defclass the-end-screen (game-over-screen) ()) (defmethod initialize-instance :after ((s the-end-screen) &key &allow-other-keys) (with-slots (text) s (setf (text-string text) "End...")))
1,030
Common Lisp
.lisp
26
32.153846
81
0.587174
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
be5be9ad331ae3c6c802ef3e1004d7b3ae46323a1749ba29263a4effcb43efcf
13,816
[ -1 ]
13,817
title-screen.lisp
rpav_spell-and-dagger/src/ui/title-screen.lisp
(in-package :game) (defclass title-screen (screen) (text style img (text-visible :initform t))) (defmethod initialize-instance ((s title-screen) &key &allow-other-keys) (call-next-method) (with-slots (text style img) s (multiple-value-bind (w h) (window-size) (declare (ignorable w)) (setf img (make-instance 'image :key 0 :tex (asset-title *assets*) :size (gk-vec3 256 144 1.0) :pos (gk-vec3 0 0 0) :anchor (gk-vec2 0 0))) (ui-add s img) (setf style (cmd-font-style :size (/ h 15.0) :align '(:center))) (setf text (cmd-text "Press Z" :x (/ w 2.0) :y (* 3 (/ h 4.0))))))) (defmethod key-event ((s title-screen) key state) (when (eq state :keydown) (case key (:scancode-z (title-start))))) (defmethod draw ((s title-screen) lists m) (call-next-method) (with-slots (ui-list) lists (with-slots (text style text-visible) s (when text-visible (cmd-list-append ui-list style text)))))
1,050
Common Lisp
.lisp
28
30.392857
73
0.586444
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
e7fd01751d13a6e5b9d5c45f8b8674340cc961161b1e466f3ecc78666f3c4fc6
13,817
[ -1 ]
13,818
map-screen.lisp
rpav_spell-and-dagger/src/ui/map-screen.lisp
(in-package :game) ;; MAP-SCREEN (defclass map-screen (screen) ((hud :initform (make-instance 'hud)))) (defmethod initialize-instance :after ((ms map-screen) &key &allow-other-keys) (with-slots (hud) ms (ui-add ms hud))) (defmethod draw :after ((s map-screen) lists m) (when-let (map (current-map)) (map-update map) (draw map lists m))) (defmethod key-event ((w map-screen) key state) (when-let (char (current-char)) (if (eq state :keydown) (progn (case key (:scancode-right (set-motion-bit char +motion-right+)) (:scancode-left (set-motion-bit char +motion-left+)) (:scancode-up (set-motion-bit char +motion-up+)) (:scancode-down (set-motion-bit char +motion-down+)) (:scancode-z (entity-action char :btn1)) (:scancode-a (entity-action char :btn2)) (:scancode-x (entity-action char :btn3)) (:scancode-s (entity-action char :btn4)))) (progn (case key (:scancode-right (clear-motion-bit char +motion-right+)) (:scancode-left (clear-motion-bit char +motion-left+)) (:scancode-up (clear-motion-bit char +motion-up+)) (:scancode-down (clear-motion-bit char +motion-down+))))))) ;; TEXT-SCREEN ;;; Note this is a different screen, but we still render--but not ;;; update--the map, because we don't want action happening while ;;; there's reading. But doing so would be easy. In fact, in that ;;; case, we'd probably just subclass MAP-SCREEN here. ;;; This could probably have been handled in MAP-SCREEN, but that ;;; would require special state handling, and we already *have* state ;;; handling. (defclass text-screen (screen) ((textbox :initform (make-instance 'textbox)) (draw-map-p :initarg :map :initform t))) (defmethod initialize-instance :after ((ts text-screen) &key text &allow-other-keys) (with-slots (textbox) ts (setf (textbox-text textbox) text) (ui-add ts textbox))) (defmethod draw :after ((s text-screen) lists m) ;; The textbox is a child, so it automatically gets rendered. (with-slots (draw-map-p) s (when draw-map-p (when-let (map (current-map)) (draw map lists m))))) (defmethod key-event ((w text-screen) key state) (when (eq state :keydown) (case key (:scancode-z (ps-back)) (:scancode-a (ps-back)) (:scancode-x (ps-back)) (:scancode-s (ps-back)))))
2,458
Common Lisp
.lisp
58
36.431034
84
0.64196
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
29804c15d2113ba5081487042b0a120ac6046cf5f8faba4eff73b91ce2791abb
13,818
[ -1 ]
13,819
spell-and-dagger.asd
rpav_spell-and-dagger/spell-and-dagger.asd
(defpackage :spell-and-dagger.asdf (:use #:cl #:asdf)) (in-package :spell-and-dagger.asdf) (defsystem :spell-and-dagger/pre :depends-on (:cffi) :serial t :pathname "src" :components ((:file "presetup"))) (defsystem :spell-and-dagger :description "Spell & Dagger: Lisp Game Jam 2016 Q2 entry" :author "Ryan Pavlik" :license "GPL2" :version "0.0" :depends-on (:spell-and-dagger/pre :alexandria :defpackage-plus :cl-json :cl-ppcre :sdl2kit :gamekernel) :serial t :components ((:module #:src :pathname "src" :components ((:file "util.rpav-1") (:file "package") (:file "startup") (:file "util") (:file "proto") (:file "entity") (:file "physics") (:file "anim") (:file "tilemap") (:file "game-map") (:module #:entities :pathname "entity" :components ((:file "actor") (:file "simple") (:file "move-manager") (:file "simple-mob") (:file "spawner") (:file "game-char") (:file "npc") (:file "powerup") (:file "spell") (:file "spell-interacts") (:file "more-interacts"))) (:file "phase") (:module #:phases :pathname "phases" :components ((:file "title") (:file "map-phase") (:file "text-phase") (:file "game-over") (:file "end-game"))) (:file "ui") (:module #:uis :pathname "ui" :components ((:file "textbox") (:file "title-screen") (:file "map-screen") (:file "hud") (:file "game-over-screen"))) (:file "sprite") (:file "image") (:file "assets") (:file "window") (:file "quadtree"))) (:module #:assets :pathname "assets" :components ((:module #:images :pathname "image" :components ((:static-file "spritesheet.json") (:static-file "spritesheet.png") (:static-file "title.png"))) (:module #:fonts :pathname "font" :components ((:static-file "hardpixel.ttf"))) (:module #:maps :pathname "map" :components ((:static-file "tm/town.json") (:static-file "tm/indoor.json") (:static-file "tm/floating.json") (:static-file "tm/dungeon.json") (:static-file "tm/forest.json") (:static-file "tm/cave.json") (:static-file "tm/objects.json") (:static-file "tm/misc.json") (:static-file "tm/tiny16basic.json") (:static-file "tm/town-old.json")))))))
2,538
Common Lisp
.asd
95
20.315789
60
0.553682
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
96ae4763b24eef656f1097fb39d011b4bb47013590134230804bbc3edcd6ed24
13,819
[ -1 ]
13,821
build.sh
rpav_spell-and-dagger/build.sh
#!/bin/sh sbcl \ --no-userinit \ --load build.lisp \ --name spell-and-dagger \ --startup "game:run" \ --non-interactive
141
Common Lisp
.l
7
16.142857
29
0.586466
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
de08b13396c884c05004374a7005209b6116e4af05315fd67fecd5435be4286a
13,821
[ -1 ]
13,863
hardpixel.txt
rpav_spell-and-dagger/assets/font/hardpixel.txt
Author: Jovanny Lemonad, Anton Kudin License: SIL OFL 1.1 (http://scripts.sil.org/OFL) or similar terms Source: http://www.typetype.ru/free-fonts/ Notes: This has been converted from OTF to TTF.
200
Common Lisp
.l
4
48.75
66
0.758974
rpav/spell-and-dagger
6
0
0
LGPL-2.1
9/19/2024, 11:27:13 AM (Europe/Amsterdam)
ab182cada2274c8ffbab5e65fd1dd2f722eb75ec406cac6271bccb1d20553a20
13,863
[ -1 ]