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
40,168
q19.lisp
goroda_advent_of_code_2020/q19.lisp
(in-package :q19) (defun parse-rules (rules) (cond ((cl-ppcre:all-matches "[a-z]" rules) (list (aref rules 1))) ((find "|" rules :test #'string=) (let* ((options (cl-ppcre:split "[|]" rules))) (mapcar #'(lambda (opts) (map 'list #'parse-integer (cl-ppcre:split " " (string-trim " " opts)))) options))) (t (map 'list #'parse-integer (cl-ppcre:split " " (string-trim " " rules)))))) (defun parse-line-into-rules (line rules) (let ((key-vals (cl-ppcre:split ": " line))) (setf (gethash (parse-integer (car key-vals)) rules) (parse-rules (cadr key-vals))))) (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop with rules = (make-hash-table) with part1 = t for line = (read-line in nil nil) while line if (string= "" line) do (setq part1 nil) (setq line (read-line in nil nil)) ;; do (format t "line = ~A~%" line) if part1 do (parse-line-into-rules line rules) else collect line into checks finally (return (values rules checks))))) (defun satisfies0 (all-rules str) (let ((len (length str)) (initial-rule (gethash 0 all-rules))) (labels ((check-rule (rule next-rule start) ;; (format t "~t Checking Rule ~A; Next Rule is ~A; str = ~A start = ~A~%" ;; rule next-rule str start) (if (null rule) (if (= start len) t nil) (unless (>= start len) (etypecase rule (character (if (char= (aref str start) rule) (check-rule (car next-rule) (cdr next-rule) (1+ start)) nil)) (integer (let ((to-check (gethash rule all-rules))) (if (listp (car to-check)) (check-rule to-check next-rule start) (check-rule (car to-check) (append (cdr to-check) next-rule) start)))) (cons (if (check-rule (caar rule) (append (cdar rule) next-rule) start) t (check-rule (cdr rule) next-rule start)))))))) (check-rule (car initial-rule) (cdr initial-rule) 0)))) (defun get-answer1 (&key (filename "p19")) (multiple-value-bind (rules strings) (read-file-as-lines-p1 filename) (loop for str in strings :when (satisfies0 rules str) count 1))) (defun get-answer2 (&key (filename "p19b")) (multiple-value-bind (rules strings) (read-file-as-lines-p1 filename) (loop for str in strings :when (satisfies0 rules str) count 1))) (defun get-answer () (format t "Answer 1: ~A~%" (get-answer1)) (format t "Answer 2: ~A" (get-answer2))) ;; Original version ;; Q19> (time (get-answer)) ;; Answer 1: 147 ;; Answer 2: 263 ;; Evaluation took: ;; 0.022 seconds of real time ;; 0.022165 seconds of total run time (0.021866 user, 0.000299 system) ;; 100.00% CPU ;; 48,689,070 processor cycles ;; 3,669,744 bytes consed ;; Cleaner version -- added labels for closure and typecase for matching ;; Q19> (time (get-answer)) ;; Answer 1: 147 ;; Answer 2: 263 ;; Evaluation took: ;; 0.017 seconds of real time ;; 0.017460 seconds of total run time (0.017266 user, 0.000194 system) ;; 100.00% CPU ;; 38,445,390 processor cycles ;; 3,669,504 bytes consed
3,717
Common Lisp
.lisp
84
33.77381
109
0.54169
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
cf4a6c0e24d8a42c5ea15273e92cf1a6ff13fe353ac172dc83b9765fbc7c8322
40,168
[ -1 ]
40,169
q7.lisp
goroda_advent_of_code_2020/q7.lisp
(in-package :q7) (defun parse-rule (line) (let* ((words (cl-ppcre:split " " line)) (name (concatenate 'string (first words) (second words))) (rest (cadr (cl-ppcre:split " contain " line))) (split (cl-ppcre:split ", " rest)) (out (list name))) (unless (string= "no other bags." (car split)) (loop for words in split for contains = (cl-ppcre:split " " words) do (let ((first-num (parse-integer (car contains))) (first-name (concatenate 'string (second contains) (third contains)))) (setq out (push (cons first-name first-num) out))))) (reverse out))) (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop for line = (read-line in nil nil) while line collect (parse-rule line)))) (defun form-tree (res) (let ((parents (make-hash-table :test 'equal)) (children (make-hash-table :test 'equal))) (loop for stuff in res do (setf (gethash (car stuff) parents) (list)) (setf (gethash (car stuff) children) (cdr stuff))) (loop for stuff in res do (loop for child in (cdr stuff) do (setf (gethash (car child) parents) (push (cons (car stuff) (cdr child)) (gethash (car child) parents))))) (values parents children))) (defun walk-tree-backward (tree name num visited) (let ((parents (gethash name tree))) (if (null parents) (list num visited) (loop for (parent . num) in parents unless (find parent visited :test #'string=) do (setq visited (push parent visited)) (let ((res (walk-tree-backward tree parent (1+ num) visited))) (setq num (car res)) (setq visited (cadr res))))) (list num visited))) (defun walk-tree-forward (tree name num mult) (let ((children (gethash name tree))) (if (null children) (list num mult) (loop for (child . num-bag) in children do (let ((res (walk-tree-forward tree child (+ num (* mult num-bag)) (* mult num-bag)))) (setq num (car res))))) (list num mult))) (defun get-answer (&key (filename "p7")) (multiple-value-bind (parents children) (form-tree (read-file-as-lines-p1 filename)) (format t "Answer 1 = ~A ~%" (length (second (walk-tree-backward parents "shinygold" 0 (list))))) (format t "Answer 2 = ~A ~%" (first (walk-tree-forward children "shinygold" 0 1))))) ;; Original ;; Q7> (time (get-answer)) ;; Answer 1 = 121 ;; Answer 2 = 3805 ;; Evaluation took: ;; 0.008 seconds of real time ;; 0.008380 seconds of total run time (0.007482 user, 0.000898 system) ;; 100.00% CPU ;; 18,453,650 processor cycles ;; 2,283,328 bytes consed
3,275
Common Lisp
.lisp
75
31.88
72
0.5279
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
e99cc35e3a0ed4c7beb0ba270f226265a38e95707e51fb4f77c412a2c8c4f180
40,169
[ -1 ]
40,170
q17.lisp
goroda_advent_of_code_2020/q17.lisp
(in-package :q17) (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop for line = (read-line in nil nil) for ii from 0 while line append (loop for jj from 0 to (1- (length line)) if (string= "#" (aref line jj)) collect (list ii jj 0))))) (defun is-active (check map) (position check map :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y)))))) (defun create-options (current) (let ((x (first current)) (y (second current)) (z (third current))) ;; (format t "~A~A~A~%" x y z) (loop for ii in (list -1 0 1) append (loop for jj in (list -1 0 1) append (loop for kk in (list -1 0 1) if (not (= 0 ii jj kk)) collect (list (+ x ii) (+ y jj) (+ z kk))))))) (defun num-active-neighbors (current map) (let ((x (first current)) (y (second current)) (z (third current))) ;; (format t "~A~A~A~%" x y z) (loop for ii in (list -1 0 1) sum (loop for jj in (list -1 0 1) sum (loop for kk in (list -1 0 1) if (and (not (= 0 ii jj kk)) (is-active (list (+ x ii) (+ y jj) (+ z kk)) map)) sum 1))))) (defun all-active-sites (current map) (remove-duplicates (loop for option in (create-options current) for num-active-neighbors = (num-active-neighbors option map) for active? = (is-active option map) if (and active? (or (= num-active-neighbors 2) (= num-active-neighbors 3))) collect option if (and (not active?) (= num-active-neighbors 3)) collect option) :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y)))))) (defun copy-map (map) (loop for term in map collect (copy-seq term))) (defun do-something (map num-trials) ;; (format t "map = ~A~% " map) (loop for ii from 1 to num-trials for new-map = (remove-duplicates (loop for active-site in map ;; do (format t "active-site = ~A; is active=~A ~%" ;; active-site (is-active active-site map)) append (all-active-sites active-site map)) :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y))))) do (setq map (copy-map new-map)) ;; do (format t "new-map = ~A~%" map ) finally (return new-map))) (defun is-active-two (check map) (position check map :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y)) (= (fourth x) (fourth y)))))) (defun create-options-two (current) (let ((x (first current)) (y (second current)) (z (third current)) (w (fourth current))) ;; (format t "~A~A~A~%" x y z) (loop for ii in (list -1 0 1) append (loop for jj in (list -1 0 1) append (loop for kk in (list -1 0 1) append (loop for zz in (list -1 0 1) if (not (= 0 ii jj kk zz)) collect (list (+ x ii) (+ y jj) (+ z kk) (+ w zz)))))))) (defun num-active-neighbors-two (current map) (let ((x (first current)) (y (second current)) (z (third current)) (w (fourth current))) ;; (format t "~A~A~A~%" x y z) (loop for ii in (list -1 0 1) sum (loop for jj in (list -1 0 1) sum (loop for kk in (list -1 0 1) sum (loop for zz in (list -1 0 1) if (and (not (= 0 ii jj kk zz)) (is-active-two (list (+ x ii) (+ y jj) (+ z kk) (+ w zz)) map)) sum 1)))))) (defun all-active-sites-two (current map) (remove-duplicates (loop for option in (create-options-two current) for num-active-neighbors = (num-active-neighbors-two option map) for active? = (is-active-two option map) if (and active? (or (= num-active-neighbors 2) (= num-active-neighbors 3))) collect option if (and (not active?) (= num-active-neighbors 3)) collect option) :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y)) (= (fourth x) (fourth y)))))) (defun do-something-two (map num-trials) ;; (format t "map = ~A~% " map) (loop for ii from 1 to num-trials for new-map = (remove-duplicates (loop for active-site in map append (all-active-sites-two active-site map)) :test #'(lambda (x y) (and (= (first x) (first y)) (= (second x) (second y)) (= (third x) (third y)) (= (fourth x) (fourth y))))) do (setq map (copy-map new-map)) ;; do (format t "new-map = ~A~%" map ) finally (return new-map))) (defun read-file-as-lines-p2 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop for line = (read-line in nil nil) for ii from 0 while line append (loop for jj from 0 to (1- (length line)) if (string= "#" (aref line jj)) collect (list ii jj 0 0))))) (defun get-answer (&key (filename "p17")) (let* ((code (read-file-as-lines-p1 filename)) (code2 (read-file-as-lines-p2 filename))) (format t "Answer 1 = ~A~%" (length (do-something code 6))) (format t "Answer 2 = ~A~%" (length (do-something-two code2 6))))) ;; Long run time -- beware ;; Long run time stems form the fact that I check whether a site is active (and count its neighbors) ;; more than once -- makes implementation wasteful
8,082
Common Lisp
.lisp
155
30.36129
100
0.392008
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
04b4425826631e7155e693234f8221301963b328bd9126abb8a4d1b08039822e
40,170
[ -1 ]
40,171
q18.lisp
goroda_advent_of_code_2020/q18.lisp
(in-package :q18) (defun evaluate-expression (line start) (loop with op = #'+ with val = 0 for ii from start to (1- (length line)) ;; do (format t "ii = ~A val = ~A start = ~A thing = ~A ~%" ii val start (aref line ii)) do (cond ((string= "(" (aref line ii)) (multiple-value-bind (v next) (evaluate-expression line (1+ ii)) (setq val (funcall op val v)) (setq ii next))) ((string= ")" (aref line ii)) (progn ;; (format t "return val = ~A~%" val) (return (values val ii)))) ((string= "*" (aref line ii)) (setq op #'*)) ((string= "+" (aref line ii)) (setq op #'+)) ((string/= " " (aref line ii)) (setq val (funcall op val (parse-integer (string (aref line ii))))) ) ; (t (format t "ok~%" )) ) finally (return (values val ii)))) ;; (evaluate-expression "1 + 2 * 3 + 4 * 5 + 6" 0) ;; => 71 ;; (evaluate-expression "(1 + (2 * 3) + (4 * (5 + 6))" 0) ;; => 51 ;; (evaluate-expression "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2" 0) ;; => 13632 (defun eval-clean (line) "Evaluate with no parenthesis" (loop while line for (fe . (se . (te . rest))) = line while (or fe se te) if (string= "+" se) collect (+ (parse-integer (string fe)) (parse-integer (string te))) into out and do (setq line rest) else if (string= "*" se) collect (parse-integer fe) into out and do (setq line (cons te rest)) else if (string= "+" fe) do (setf (car (last out)) (+ (parse-integer se) (car (last out)))) (setq line (cons te rest)) else if (string= "*" fe) do (setq line (cons se (cons te rest))) else do (setq line rest) and collect (parse-integer fe) into out end end finally (return (reduce #'* out)))) (defun pre-proc (line) (cl-ppcre:split " " (cl-ppcre:regex-replace-all "[)]" (cl-ppcre:regex-replace-all "[(]" line "( ") " )"))) (defun parse-two (line) (loop with temp = nil while line for (fe . rest) = line if (string= "(" fe) do (multiple-value-bind (v r) (parse-two rest) (setq rest r) (setq temp v)) and collect temp into out else if (string= ")" fe) do (return (values (format nil "~A" (eval-clean out)) rest)) else collect fe into out end end do (setq line rest) finally (return (values out nil)))) ;; (eval-clean (parse-two (pre-proc "1 + (2 * 3) + (4 * (5 + 6))"))) ;; => 51 ;; (eval-clean (parse-two (pre-proc "2 * 3 + (4 * 5)"))) ;; => 46 ;; (eval-clean (parse-two (pre-proc "5 + (8 * 3 + 9 + 3 * 4 * 3)"))) ;; => 1445 ;; (eval-clean (parse-two (pre-proc "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"))) ;; => 669060 ;; (eval-clean (parse-two (pre-proc "((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"))) ;; => 34440 (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop for line = (read-line in nil nil) for ii from 0 while line sum (evaluate-expression line 0) into out1 sum (eval-clean (parse-two (pre-proc line))) into out2 finally (return (values out1 out2))))) (defun get-answer (&key (filename "p18")) (multiple-value-bind (ans1 ans2) (read-file-as-lines-p1 filename) (format t "Answer 1 = ~A~%" ans1) (format t "Answer 2 = ~A~%" ans2))) ;; Original Version ;; Q18> (time (get-answer)) ;; Answer 1 = 9535936849815 ;; Answer 2 = 472171581333710 ;; Evaluation took: ;; 0.010 seconds of real time ;; 0.009414 seconds of total run time (0.009316 user, 0.000098 system) ;; 90.00% CPU ;; 20,686,478 processor cycles ;; 5,043,456 bytes consed
4,345
Common Lisp
.lisp
107
30.420561
117
0.482096
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
ed9b1bd9f5e9429b964635c16bde9bfc605ef928954741dc15d163dab2354d0d
40,171
[ -1 ]
40,172
q4.lisp
goroda_advent_of_code_2020/q4.lisp
(in-package :q4) (defstruct password byr iyr eyr hgt hcl ecl pid cid) (defun verify-password (pass) (if (or (null (password-byr pass)) (null (password-iyr pass)) (null (password-eyr pass)) (null (password-hgt pass)) (null (password-hcl pass)) (null (password-ecl pass)) (null (password-pid pass))) nil pass)) (defun parse-password (line) "Parse a password, return nil if not valid" ;; (format t "password = ~A~%" line) (loop with pass = (make-password) for text in (cl-ppcre:split " " line) for split = (cl-ppcre:split ":" text) for name = (car split) for val = (cadr split) do (cond ((string= name "byr") (let ((year (parse-number:parse-number val))) (if (or (< year 1920) (> year 2002)) (return nil) (setf (password-byr pass) year)))) ((string= name "iyr") (let ((year (parse-number:parse-number val))) (if (or (< year 2010) (> year 2020)) (return nil) (setf (password-iyr pass) year)))) ((string= name "eyr") (let ((year (parse-number:parse-number val))) (if (or (< year 2020) (> year 2030)) (return nil) (setf (password-eyr pass) year)))) ((string= name "hgt") (let ((hgt (parse-integer val :junk-allowed t)) (in (cl-ppcre:all-matches "in" val))) (if (> (length in) 0) (if (or (< hgt 59) (> hgt 76)) (return nil) (setf (password-hgt pass) (cons hgt "in"))) (if (or (< hgt 150) (> hgt 193)) (return nil) (setf (password-hgt pass) (cons hgt "cm")))))) ((string= name "pid") ;; doesnt check if its a number (if (not (= (length val) 9)) (return nil) (setf (password-pid pass) val))) ((string= name "ecl") (if (or (string= "amb" val) (string= "blu" val) (string= "brn" val) (string= "gry" val) (string= "grn" val) (string= "hzl" val) (string= "oth" val)) (setf (password-ecl pass) val) (return nil))) ((string= name "hcl") (if (not (string= "#" (aref val 0))) (return nil) (if (not (= (/ (length (cl-ppcre:all-matches "[0-9a-f]" val)) 2) 6)) (return nil) (setf (password-hcl pass) val))))) finally (return (verify-password pass)))) (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop with num-valid = 0 and bump = "" for line = (read-line in nil nil) while line if (string= "" line) do (unless (null (parse-password bump)) (setq num-valid (+ num-valid 1))) (setq bump "") else do (setq bump (concatenate 'string bump " " line)) finally (return num-valid)))) (defun get-answer (&key (filename "p4")) (let ((ans1 (read-file-as-lines-p1 filename))) (format t "answer = ~A~%" ans1))) ;; Original version ;; Q4> (time (get-answer)) ;; answer = 186 ;; Evaluation took: ;; 0.013 seconds of real time ;; 0.012878 seconds of total run time (0.011595 user, 0.001283 system) ;; 100.00% CPU ;; 28,318,942 processor cycles ;; 3,110,112 bytes consed ;; Second version with cleaner outer loop ;; Q4> (time (get-answer)) ;; answer = 186 ;; Evaluation took: ;; 0.011 seconds of real time ;; 0.010726 seconds of total run time (0.010606 user, 0.000120 system) ;; 100.00% CPU ;; 23,579,546 processor cycles ;; 3,110,640 bytes consed ;; Version with clear password parsing ;; Q4> (time (get-answer)) ;; answer = 186 ;; Evaluation took: ;; 0.004 seconds of real time ;; 0.003631 seconds of total run time (0.003507 user, 0.000124 system) ;; 100.00% CPU ;; 8,004,824 processor cycles ;; 916,832 bytes consed
4,592
Common Lisp
.lisp
111
28.900901
90
0.483893
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
6f3d6ee009dbb82b592a413bad8cfdbe0ef51dab87021aad0e75b15a86309509
40,172
[ -1 ]
40,173
q6.lisp
goroda_advent_of_code_2020/q6.lisp
(in-package :q6) (defun read-file-as-lines-p1 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop with num-valid = 0 and group = (list) for line = (read-line in nil nil) while line if (string= "" line) do (setq num-valid (+ num-valid (length group))) (setq group (list)) else do (setq group (nunion group (cl-ppcre:split "" line) :test #'string=)) finally (return num-valid)))) (defun read-file-as-lines-p2 (filename &key) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop with num-valid = 0 and group = nil and on-num = 0 for line = (read-line in nil nil) while line if (string= "" line) do (setq num-valid (+ num-valid (length group))) (setq group nil) (setq on-num 0) else if (= on-num 0) do (setq group (cl-ppcre:split "" line)) (setq on-num (incf on-num)) else unless (null group) do (setq group (nintersection group (cl-ppcre:split "" line) :test #'string=)) end end finally (return num-valid)))) (defun get-answer (&key (filename "p6")) (let ((ans1 (read-file-as-lines-p1 filename)) (ans2 (read-file-as-lines-p2 filename))) (format t "Answer 1 = ~A~%" ans1) (format t "Answer 2 = ~A~%" ans2))) ;; Original ;; Q6> (time (get-answer)) ;; Answer 1 = 6170 ;; Answer 2 = 2947 ;; Evaluation took: ;; 0.009 seconds of real time ;; 0.008701 seconds of total run time (0.008550 user, 0.000151 system) ;; 100.00% CPU ;; 19,137,006 processor cycles ;; 8,449,632 bytes consed ;; Cleaner version -- interesting much smaller consing but longer ;; Q6> (time (get-answer)) ;; Answer 1 = 6170 ;; Answer 2 = 2947 ;; Evaluation took: ;; 0.012 seconds of real time ;; 0.012557 seconds of total run time (0.012426 user, 0.000131 system) ;; 108.33% CPU ;; 27,634,588 processor cycles ;; 2,424,592 bytes consed
2,357
Common Lisp
.lisp
64
27.890625
72
0.546369
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
874ebdfb60601bc570d6ddc24510ffa3a51e6cc0a9b7e49fde5574b2747d573c
40,173
[ -1 ]
40,174
q1.lisp
goroda_advent_of_code_2020/q1.lisp
(in-package :q1) (defun read-file-as-lines (filename) "Read file into a list of lines." (with-open-file (in (advent_of_code_2020:get-file-pathname filename)) (loop for line = (read-line in nil nil) while line collect (parse-number:parse-number line)))) (defun get-answer (&key (filename "p1")) (let ((array (read-file-as-lines filename))) (format t "Answer for part 2 is: ~A~%" (loop named outer for val in array do (loop for val2 in array do (loop for val3 in array when (= 2020 (+ val val2 val3)) do (return-from outer (* val val2 val3))))))))
715
Common Lisp
.lisp
15
35.4
84
0.545845
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
056687667c7ab8067797f22165b6c46cf1471456c779cdb9f458b2de4e2075d7
40,174
[ -1 ]
40,175
advent_of_code_2020.lisp
goroda_advent_of_code_2020/advent_of_code_2020.lisp
;;;; advent_of_code_2020.lisp (in-package #:advent_of_code_2020) (defparameter *project-dir* (asdf:system-source-directory :advent_of_code_2020)) (defun get-file-pathname (problem-name) (merge-pathnames *project-dir* (make-pathname :name (format nil "data/~A" problem-name) :type "txt")))
385
Common Lisp
.lisp
7
40.285714
80
0.564171
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
fa320d15ea00d29dc6a5094ad9fdc63f28efe6278f3372e682df44dca4f60cf7
40,175
[ -1 ]
40,176
advent_of_code_2020.asd
goroda_advent_of_code_2020/advent_of_code_2020.asd
;;;; advent_of_code_2020.asd (asdf:defsystem #:advent_of_code_2020 :description "My advent of code 2020" :author "Alex Gorodetsky [email protected]" :license "GPL" :version "0.0.1" :serial t :depends-on (#:alexandria #:cl-ppcre #:parse-number #:uiop) :components ((:file "package") (:file "advent_of_code_2020") (:file "q1") (:file "q2") (:file "q3") (:file "q4") (:file "q5") (:file "q6") (:file "q7") (:file "q8") (:file "q9") (:file "q10") (:file "q11") (:file "q12") (:file "q13") (:file "q14") (:file "q15") (:file "q16") (:file "q17") (:file "q18") (:file "q19")))
940
Common Lisp
.asd
32
17.0625
51
0.38699
goroda/advent_of_code_2020
0
0
0
GPL-3.0
9/19/2024, 11:47:51 AM (Europe/Amsterdam)
8104805d1bbc086e4b3cd6a78b5993d61b61be5605588bf655de64744a07b106
40,176
[ -1 ]
40,213
sparql-cluster-transforms.cl
mdebellis_CODO-Lisp/sparql-cluster-transforms.cl
; to transform data from geographic cluster strings ; this function is typically run last although it should be ; independent of the others (in-package :db.agraph.user) (defun codo-cluster-transforms () (print "Entering Cluster transforms") (sparql:run-sparql "DELETE { ?p codo:clusterString ?cs.} INSERT { ?cl codo:hasMember ?p. ?p codo:isMemberOf ?cl. ?p codo:travelledFrom ?place. } WHERE { ?p codo:clusterString ?cs. BIND (IF (CONTAINS(?cs, 'From Middle East'), codo:MiddleEastCluster, (IF (CONTAINS(?cs, 'From USA'), codo:USACluster, (IF (CONTAINS(?cs, 'From South America'), codo:SouthAmericaCluster, (IF (CONTAINS(?cs, 'From the rest of Europe'), codo:RestOfEuropeCluster, (IF (CONTAINS(?cs, 'From the Southern States'), codo:SouthernStatesCluster, (IF (CONTAINS(?cs, 'TJ Congregation from 13th to 18th March in Delhi'), codo:TJCongregation13thTo18thCluster, (IF (CONTAINS(?cs, 'From Gujarat'), codo:GujaratCluster, (IF (CONTAINS(?cs, 'From Maharashtra'), codo:MaharashtraCluster, (IF (CONTAINS(?cs, 'From Rajasthan'), codo:RajasthanCluster, (IF (CONTAINS(?cs, 'Domestic Travel History Absent'), codo:DomesticTravelHistoryAbsentCluster, (IF (CONTAINS(?cs, 'International Travel History Absent'), codo:InternationalTravelHistoryAbsentCluster, (IF (CONTAINS(?cs, 'From United Kingdom'), codo:UnitedKingdomCluster, owl:Nothing))))))))))))))))))))))) AS ?cl). ?cl codo:hasLocation ?place. FILTER(?cl != owl:Nothing) } ") (sparql:run-sparql "DELETE { ?p codo:clusterString ?cs.} INSERT { ?cl codo:hasMember ?p. ?p codo:isMemberOf ?cl. } WHERE { ?p codo:clusterString ?cs. BIND (IF (CONTAINS(?cs, 'Others'), codo:OthersCluster, (IF (CONTAINS(?cs, 'Unknown'), codo:UnknownCluster, (IF (CONTAINS(?cs, 'Severe Acute Respiratory Infection'), codo:SevereAcuteRespiratoryInfectionCluster, (IF (CONTAINS(?cs, 'Influenza like illness'), codo:InfluenzaLikeIllnessCluster, (IF (CONTAINS(?cs, 'Containment Zones'), codo:ContainmentZonesCluster, (IF (CONTAINS(?cs, '27-June Trace History Absent'), codo:June-27TraceHistoryAbsentCluster, (IF (CONTAINS(?cs, '28-June Trace History Absent'), codo:June-28TraceHistoryAbsentCluster, (IF (CONTAINS(?cs, '29-June Trace History Absent'), codo:June-29TraceHistoryAbsentCluster, (IF (CONTAINS(?cs, 'Second Generation Contact Absent'), codo:SecondGenerationContactAbsentCluster, (IF (CONTAINS(?cs, 'Second Generation Contact'), codo:SecondGenerationContactCluster, owl:Nothing))))))))))))))))))) AS ?cl). FILTER(?cl != owl:Nothing) } ") (sparql:run-sparql "DELETE { ?p codo:clusterString ?cs.} INSERT { ?cl codo:hasMember ?p. ?p codo:isMemberOf ?cl. ?p codo:co-worker ?sh. ?sh codo:co-worker ?p. } WHERE { ?p codo:clusterString ?cs. ?p codo:contractedVirusFrom ?sh. BIND (IF (CONTAINS(?cs, 'Pharmaceutical Company in Nanjangud'), codo:PharmaceuticalCompanyInNanjangudCluster, owl:Nothing) AS ?cl). FILTER(?cl != owl:Nothing) }") (sparql:run-sparql "DELETE { ?p codo:clusterString ?cs.} INSERT { ?cl codo:hasMember ?p. ?p codo:isMemberOf ?cl. } WHERE { ?p codo:clusterString ?cs. BIND (IF (CONTAINS(?cs, 'Pharmaceutical Company in Nanjangud'), codo:PharmaceuticalCompanyInNanjangudCluster, owl:Nothing) AS ?cl). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER(?cl != owl:Nothing && !bound(?sh)) }") (commit-triple-store) )
3,455
Common Lisp
.cl
91
34.758242
115
0.717223
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
e833edcd1f3d876976bec6ea1d3b0919602fed5aeb9c44cbb145bbcca0a6a1ee
40,213
[ -1 ]
40,214
sparql-transforms.cl
mdebellis_CODO-Lisp/sparql-transforms.cl
#| Before running the following functions, make sure you follow the setup instructions in the document "Running Lisp to Access Allegrograph.pdf" Make sure that the CODO knowledge graph is open and that the codo package is registered: (open-triple-store "CODORealData" :triple-store-class 'remote-triple-store :server "localhost" :port 10035 :user "mdebellis" :password "df1559") (register-namespace "codo" "http://www.isibang.ac.in/ns/codo#") (register-namespace "schema" "https://schema.org/") All functions assume that the codo triplestore is open and bound to *db* Also, make sure that an index is created for the property codo:statePatientID. This can be done in Gruff or in the listener: (create-freetext-index "PatientIDs" :predicates (list !codo:statePatientID !codo:districtPatientID) :minimum-word-size 1) (create-freetext-index "PlaceNames" :predicates (list !codo:geoName)) Note: order is important. Run the functions in this file first and then those in sparql-regex-transforms. The earlier transforms remove data that may be problematic for later transforms. The function at the bottom of this file (and sparql-regex-transforms) runs all the functions for you. They were divided up into smaller functions to aid debugging. |# (in-package :db.agraph.user) (defvar *test-modep* nil) (defun enable-test-mode () ;Set *test-modep* to t and run SPARQL query ;to create test property if it doesn't already exist (setq *test-modep* t) (sparql:run-sparql "INSERT DATA { codo:reasonStringTD a owl:DatatypeProperty; rdfs:range xsd:string ; rdfs:label 'reason string TD' . codo:cityStringTD a owl:DatatypeProperty; rdfs:range xsd:string ; rdfs:label 'city string TD' . }") (commit-triple-store)) (defun disable-test-mode () (setq *test-modep* nil) (sparql:run-sparql "DELETE {?p codo:reasonStringTD ?rstd} WHERE {?p codo:reasonStringTD ?rstd.}") (sparql:run-sparql "DELETE {?p codo:cityStringTD ?cstd} WHERE {?p codo:cityStringTD ?cstd.}") (sparql:run-sparql "DELETE DATA { codo:reasonStringTD a owl:DatatypeProperty ; rdfs:subPropertyOf owl:topDataProperty ; rdfs:range xsd:string ; rdfs:label 'reason string TD' . codo:cityStringTD a owl:DatatypeProperty; rdfs:range xsd:string ; rdfs:label 'city string TD' . }") ;Delete any remaining outdateString (sparql:run-sparql "DELETE {?p codo:outdateString ?outstr.} WHERE {?p codo:outdateString ?outstr.}") (commit-triple-store)) (defun run-initial-codo-sparql-transforms () (print "Entering initial transforms") ; First transform deletes test data (sparql:run-sparql "DELETE {?td ?p ?o. } WHERE {?td a codo:TestData. ?td ?p ?o.}") ;Check for pStrings with non-zero value and process accordingly (sparql:run-sparql "DELETE {?p codo:pString ?ps.} INSERT {?p codo:contractedVirusFrom ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:pString ?ps. ?sh codo:statePatientID ?ps. FILTER (?ps != '0')}") ;Delete all the 0 pString (sparql:run-sparql "DELETE {?p codo:pString ?ps.} WHERE {?p codo:pString ?ps. FILTER (?ps = '0')}") ;Add a hasSpouse value to the patient (sparql:run-sparql "DELETE {?p codo:relationString ?rs.} INSERT {?p codo:hasSpouse ?sh.} WHERE {?p codo:relationString ?rs. ?p codo:statePatientID ?pid. BIND (SUBSTR(?rs, 1,1) AS ?rt). BIND (SUBSTR(?rs, 2) AS ?rid). ?sh codo:statePatientID ?rid. FILTER (?rt = 'S')}") ;Add a hasCloseRelationship value to the patient (sparql:run-sparql "DELETE {?p codo:relationString ?rs.} INSERT {?p codo:hasCloseRelationship ?sh.} WHERE {?p codo:relationString ?rs. ?p codo:statePatientID ?pid. BIND (SUBSTR(?rs, 1,1) AS ?rt). BIND (SUBSTR(?rs, 2) AS ?rid). ?sh codo:statePatientID ?rid. FILTER (?rt = 'C')}") ;Add a hasFamilyRelationship value to the patient (sparql:run-sparql "DELETE {?p codo:relationString ?rs.} INSERT {?p codo:hasFamilyMember ?sh.} WHERE {?p codo:relationString ?rs. ?p codo:statePatientID ?pid. BIND (SUBSTR(?rs, 1,1) AS ?rt). BIND (SUBSTR(?rs, 2) AS ?rid). ?sh codo:statePatientID ?rid. FILTER (?rt = 'F')}") ;Add a hasDaughter value to the patient (sparql:run-sparql "DELETE {?p codo:relationString ?rs.} INSERT {?p codo:hasDaughter ?sh.} WHERE {?p codo:relationString ?rs. ?p codo:statePatientID ?pid. BIND (SUBSTR(?rs, 1,1) AS ?rt). BIND (SUBSTR(?rs, 2) AS ?rid). ?sh codo:statePatientID ?rid. FILTER (?rt = 'D')}") ;Add a hasTravelCompanion value to the patient (sparql:run-sparql "DELETE {?p codo:relationString ?rs.} INSERT {?p codo:hasTravelCompanion ?sh.} WHERE {?p codo:relationString ?rs.?p codo:statePatientID ?pid. BIND (SUBSTR(?rs, 1,1) AS ?rt). BIND (SUBSTR(?rs, 2) AS ?rid). ?sh codo:statePatientID ?rid. FILTER (?rt = 'T')}") ;Commit the changes (commit-triple-store) ) #| Run the following queries after initial transformations function. Both should return no triples: SELECT ?p ?rs WHERE { ?p codo:relationString ?rs. } SELECT ?p ?ps WHERE { ?p codo:pString ?ps. } |# (defun run-second-codo-sparql-transforms () (print "Entering second transforms") ; First transform deletes reason strings with unknown value (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} WHERE {?p codo:reasonString ?rs. FILTER(LCASE(?rs) = 'unknown')}") ;First transform checks for strings with two place names. Need to check these first because ;If we run the later transforms they will match the first place name and neglect to process the second (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT { ?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh. ?p codo:travelledFrom ?place1. ?nexp codo:travelledFrom ?place1. ?p codo:travelledFrom ?place2. ?nexp codo:travelledFrom ?place2. ?sh codo:travelledFrom ?place1. ?sh codo:travelledFrom ?place2. } WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IF (CONTAINS(?rs, 'Jammu and Kashmir'), codo:Jamu, (IF (CONTAINS(?rs, 'Daman and Diu'), codo:Daman, (IF (CONTAINS(?rs, 'Hassan and Kodagu'), codo:Hassan, (IF (CONTAINS(?rs, 'Hindupur and Anantpur'), codo:Hindupur, owl:Nothing))))))) AS ?place1). BIND (IF (CONTAINS(?rs, 'Jammu and Kashmir'), codo:Kashmir, (IF (CONTAINS(?rs, 'Daman and Diu'), codo:Diu, (IF (CONTAINS(?rs, 'Hassan and Kodagu'), codo:Kodagu, (IF (CONTAINS(?rs, 'Hindupur and Anantpur'), codo:Anantpur, owl:Nothing))))))) AS ?place2). BIND (IRI(CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCo-Passenger-', ?pid)) AS ?nexp). FILTER(?place1 != owl:Nothing)}") ;Same as transform above except for patients where suspected host is unknown (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:travelledFrom ?place1. ?nexp codo:travelledFrom ?place1. ?p codo:travelledFrom ?place2. ?nexp codo:travelledFrom ?place2.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND #Wards of Cities (IF (CONTAINS(?rs, 'Jammu and Kashmir'), codo:Jamu, (IF (CONTAINS(?rs, 'Daman and Diu'), codo:Daman, (IF (CONTAINS(?rs, 'Hassan and Kodagu'), codo:Hassan, (IF (CONTAINS(?rs, 'Hindupur and Anantpur'), codo:Hindupur, owl:Nothing))))))) AS ?place1). BIND (IF (CONTAINS(?rs, 'Jammu and Kashmir'), codo:Kashmir, (IF (CONTAINS(?rs, 'Daman and Diu'), codo:Diu, (IF (CONTAINS(?rs, 'Hassan and Kodagu'), codo:Kodagu, (IF (CONTAINS(?rs, 'Hindupur and Anantpur'), codo:Anantpur, owl:Nothing))))))) AS ?place2). BIND (IRI(CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCo-Passenger-', ?pid)) AS ?nexp). FILTER(?place1 != owl:Nothing)}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh. ?p codo:travelledFrom ?place. ?nexp codo:travelledFrom ?place. ?sh codo:travelledFrom ?place.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IF (CONTAINS(?rs, 'Ward 135'), codo:Ward135, # Cities # Start with cities because if the city is there the additional info (state, country) # is in the ontology and we can ignore that data in the string (IF (CONTAINS(?rs, 'Abu Dhabi'), codo:AbuDhabi, (IF (CONTAINS(?rs, 'Ahmedabad'), codo:Ahmedabad, (IF (CONTAINS(?rs, 'Ajmer'), codo:Ajmer, (IF (CONTAINS(?rs, 'Amsterdam'), codo:Amsterdam, (IF (CONTAINS(?rs, 'Athens'), codo:Athens, (IF (CONTAINS(?rs, 'Bagalkote'), codo:Bagalkote, (IF (CONTAINS(?rs, 'Baroda'), codo:Baroda, (IF (CONTAINS(?rs, 'Bangalore'), codo:Bangalore, (IF (CONTAINS(?rs, 'Bangalore-Urban'), codo:Bangalore, (IF (CONTAINS(?rs, 'Belgavi'), codo:Belgavi, (IF (CONTAINS(?rs, 'Bellary'), codo:Bellary, (IF (CONTAINS(?rs, 'Bidar'), codo:Bidar, (IF (CONTAINS(?rs, 'Channagiri'), codo:Channagiri,(IF (CONTAINS(?rs, 'Chamarajanagar'), codo:Chamarajanagar,(IF (CONTAINS(?rs, 'Chennai'), codo:Chennai, (IF (CONTAINS(?rs, 'Chikballarpur'), codo:Chikballarpur, (IF (CONTAINS(?rs, 'Chikkamagalur'), codo:Chikmagalur, (IF (CONTAINS(?rs, 'Chitradurga'), codo:Chitradurga, (IF (CONTAINS(?rs, 'Colombo'), codo:Colombo,(IF (CONTAINS(?rs, 'Dammam'), codo:Dammam, (IF (CONTAINS(?rs, 'Davangere'), codo:Davangere, (IF (CONTAINS(?rs, 'Dharwad'), codo:Dharwad,(IF (CONTAINS(?rs, 'Debaspete'), codo:Debaspete, (IF (CONTAINS(?rs, 'Delhi'), codo:Delhi, (IF (CONTAINS(?rs, 'Doha'), codo:Doha, (IF (CONTAINS(?rs, 'Dubai'), codo:Dubai, (IF (CONTAINS(?rs, 'Edinburgh'), codo:Edinburgh, (IF (CONTAINS(?rs, 'Gadag'), codo:Gadag, (IF (CONTAINS(?rs, 'Goa'), codo:Goa, (IF (CONTAINS(?rs, 'Gunturu'), codo:Gunturu, (IF (CONTAINS(?rs, 'Hassan'), codo:Hassan, (IF (CONTAINS(?rs, 'Haveri'), codo:Haveri,(IF (CONTAINS(?rs, 'Hindupur'), codo:Hindupur, (IF (CONTAINS(?rs, 'Hubbali'), codo:Hubli, (IF (CONTAINS(?rs, 'Humnabad'), codo:Humnabad, (IF (CONTAINS(?rs, 'Hyderabad'), codo:Hyderabad, (IF (CONTAINS(?rs, 'Jalgaon'), codo:Jalgaon,(IF (CONTAINS(?rs, 'Jeddah'), codo:Jeddah,(IF (CONTAINS(?rs, 'Kalburgi'), codo:Kalaburagi, (IF (CONTAINS(?rs, 'Jammu'), codo:Jammu, (IF (CONTAINS(?rs, 'Kolar'), codo:Kolar, (IF (CONTAINS(?rs, 'Kolkata'), codo:Kolkata, (IF (CONTAINS(?rs, 'Kolhapur'), codo:Kolhapur, (IF (CONTAINS(?rs, 'Koppal'), codo:Koppal, (IF (CONTAINS(?rs, 'London'), codo:London, (IF (CONTAINS(?rs, 'Madikeri'), codo:Madikeri, (IF (CONTAINS(?rs, 'Madrid'), codo:Madrid, (IF (CONTAINS(?rs, 'Madurai'), codo:Madurai, (IF (CONTAINS(?rs, 'Mandya'), codo:Mandya, (IF (CONTAINS(?rs, 'Mangalore'), codo:Mangalore, (IF (CONTAINS(?rs, 'Mecca'), codo:Mecca, (IF (CONTAINS(?rs, 'Mumbai'), codo:Mumbai, (IF (CONTAINS(?rs, 'Muscat'), codo:Muscat, (IF (CONTAINS(?rs, 'Nandurbar'), codo:Nandurbar,(IF (CONTAINS(?rs, 'Nelamangala'), codo:Nelamangala, (IF (CONTAINS(?rs, 'New York'), codo:NewYorkCity, (IF (CONTAINS(?rs, 'Palghar'), codo:Palghar, (IF (CONTAINS(?rs, 'Panvel'), codo:Panvel, (IF (CONTAINS(?rs, 'Paris'), codo:Paris, (IF (CONTAINS(?rs, 'Pune'), codo:Pune, (IF (CONTAINS(?rs, 'Raichur'), codo:Raichur, (IF (CONTAINS(?rs, 'Rayachuru'), codo:Raichur, (IF (CONTAINS(?rs, 'Ratnagiri'), codo:Ratnagiri, (IF (CONTAINS(?rs, 'Ratnagiri'), codo:Ratnagiri, (IF (CONTAINS(?rs, 'Ramanagar'), codo:Ramnagar, (IF (CONTAINS(?rs, 'Ramnagar'), codo:Ramnagar, (IF (CONTAINS(?rs, 'Riyadh'), codo:Riyadh, (IF (CONTAINS(?rs, 'Sharjah'), codo:Sharjah, (IF (CONTAINS(?rs, 'Shivamogga'), codo:Shivamogga,(IF (CONTAINS(?rs, 'Shikharaji'), codo:Shikharaji, (IF (CONTAINS(?rs, 'Shivamogga'), codo:Shivamogga, (IF (CONTAINS(?rs, 'Singapore'), codo:Singapore, (IF (CONTAINS(?rs, 'Solapur'), codo:Solapur,(IF (CONTAINS(?rs, 'Surat'), codo:Surat, (IF (CONTAINS(?rs, 'Thane'), codo:Thane, (IF (CONTAINS(?rs, 'Tumkur'), codo:Tumkur, (IF (CONTAINS(?rs, 'Udupi'), codo:Udupi,(IF (CONTAINS(?rs, 'Vellore'), codo:Vellore, (IF (CONTAINS(?rs, 'Vijayapur'), codo:Vijayapura, (IF (CONTAINS(?rs, 'Vishakapatnam'), codo:Vishakapatnam,(IF (CONTAINS(?rs, 'Yadgir'), codo:Yadgir, owl:Nothing))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) AS ?place). BIND (IRI(CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCo-Passenger-', ?pid)) AS ?nexp). FILTER(?place != owl:Nothing)}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh. ?p codo:travelledFrom ?place. ?nexp codo:travelledFrom ?place. ?sh codo:travelledFrom ?place.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND # States (IF (CONTAINS(?rs, 'Andhra Pradesh'), codo:AndhraPradesh, (IF (CONTAINS(?rs, 'Assam'), codo:Assam, (IF (CONTAINS(?rs, 'Bihar'), codo:Bihar, (IF (CONTAINS(?rs, 'Chattisgadh'), codo:Chattisgadh, (IF (CONTAINS(?rs, 'Haryana'), codo:Haryana, (IF (CONTAINS(?rs, 'Himachal Pradesh'), codo:HimachalPradesh, (IF (CONTAINS(?rs, 'Jharkhand'), codo:Jharkhand, (IF (CONTAINS(?rs, 'Kerala'), codo:Kerala, (IF (CONTAINS(?rs, 'Madhya Pradesh'), codo:MadhyaPradesh, (IF (CONTAINS(?rs, 'Manipur'), codo:Manipur, (IF (CONTAINS(?rs, 'Nagaland'), codo:Nagaland, (IF (CONTAINS(?rs, 'Orissa'), codo:Orissa, (IF (CONTAINS(?rs, 'Tamil Nadu'), codo:TamilNadu, (IF (CONTAINS(?rs, 'Telengana'), codo:Telengana, (IF (CONTAINS(?rs, 'Texas'), codo:Texas, (IF (CONTAINS(?rs, 'Uttar Pradesh'), codo:UttarPradesh, (IF (CONTAINS(?rs, 'West Bengal'), codo:WestBengal, (IF (CONTAINS(?rs, 'West Bangal'), codo:WestBengal, #Districts (IF (CONTAINS(LCASE(?rs), 'andaman and nicobar'), codo:AndamanAndNicobarIslands, (IF (CONTAINS(LCASE(?rs), 'dakshin kannada'), codo:DakshinKannadaDistrict, (IF (CONTAINS(?rs, 'Kodagu'), codo:KodaguDistrict, (IF (CONTAINS(?rs, 'Mysore'), codo:Mysore, (IF (CONTAINS(?rs, 'Raigadh'), codo:Raigadh, (IF (CONTAINS(?rs, 'Uttarakhand'), codo:Uttarakhand, (IF (CONTAINS(?rs, 'Uttar Kannada'), codo:UttarKannada,(IF (CONTAINS(?rs, 'Uttara Kannada'), codo:UttarKannada, # Countries (IF (CONTAINS(?rs, 'Argentina'), codo:Argentina,(IF (CONTAINS(?rs, 'Bangladesh'), codo:Bangladesh,(IF (CONTAINS(?rs, 'Bahrain'), codo:Bahrain, (IF (CONTAINS(?rs, 'Brazil'), codo:Brazil, (IF (CONTAINS(?rs, 'Domestic travel'), codo:India,(IF (CONTAINS(?rs, 'Interdistrict travel'), codo:India,(IF (CONTAINS(?rs, 'France'), codo:France, (IF (CONTAINS(?rs, 'Germany'), codo:Germany, (IF (CONTAINS(?rs, 'Greece'), codo:Greece, (IF (CONTAINS(?rs, 'Guyana'), codo:Guyana, (IF (CONTAINS(?rs, 'Indonesia'), codo:Indonesia, (IF (CONTAINS(?rs, 'Iraq'), codo:Iraq, (IF (CONTAINS(?rs, 'Ireland'), codo:Ireland, (IF (CONTAINS(?rs, 'Italy'), codo:Italy, (IF (CONTAINS(?rs, 'Kuwait'), codo:Kuwait, (IF (CONTAINS(?rs, 'Malaysia'), codo:Malaysia,(IF (CONTAINS(?rs, 'Nepal'), codo:Nepal, (IF (CONTAINS(?rs, 'Philippines'), codo:Philippines,(IF (CONTAINS(?rs, 'Saudi Arabia'), codo:SaudiArabia,(IF (CONTAINS(?rs, 'South Africa'), codo:SouthAfrica, (IF (CONTAINS(?rs, 'Qatar'), codo:Qatar, (IF (CONTAINS(?rs, 'Spain'), codo:Spain, (IF (CONTAINS(?rs, 'Switzerland'), codo:Switzerland, (IF (CONTAINS(?rs, 'Turkey'), codo:Turkey, (IF (CONTAINS(?rs, 'UAE'), codo:UnitedArabEmirates, (IF (CONTAINS(?rs, 'UK'), codo:UK, (IF (CONTAINS(?rs, 'United States'), codo:UnitedStates, # Regions (IF (CONTAINS(?rs, 'Punjab'), codo:Punjab, owl:Nothing))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) AS ?place). BIND (IRI(CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCo-Passenger-', ?pid)) AS ?nexp). FILTER(?place != owl:Nothing)}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasSpouse ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). FILTER(?rs = 'Spouse')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasWife ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). FILTER(?rs = 'Wife')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasHusband ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). FILTER(?rs = 'Husband') }") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedDaughter. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasDaughter ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDaughter-', ?pid))) AS ?nexp). FILTER(?rs = 'Daughter') }") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSister. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasSister ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSister-', ?pid))) AS ?nexp). FILTER(?rs = 'Sister') }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedMother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasMother ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedMother-', ?pid))) AS ?nexp). FILTER(?rs = 'Mother') }") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedMother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?ps codo:hasMother ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. ?p codo:hasSpouse ?ps. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedMother-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Mother in law'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedMother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedMother-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Mother in law'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedFather. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasFather ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedFather-', ?pid))) AS ?nexp). FILTER(?rs = 'Father') }") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSon. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasSon ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSon-', ?pid))) AS ?nexp). FILTER(?rs = 'Son')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedBrother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasBrother ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedBrother-', ?pid))) AS ?nexp). FILTER(?rs = 'Brother')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCousin. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasCousin ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCousin-', ?pid))) AS ?nexp). FILTER(?rs = 'Cousin')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedNiece. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasNiece ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedNiece-', ?pid))) AS ?nexp). FILTER(?rs = 'Daughter of Brother')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedDomesticHelp. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasDomesticHelp ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDomesticHelp-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'Domestic help'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDomesticHelp-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'Co passenger'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:ContactWithHealthWorkers. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?sh a codo:HealthCareProfessional.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#ContactWithHealthWorkers-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'Contact with Health Workers'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:ContactWithHealthWorkers. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?sh a codo:HealthCareProfessional.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#ContactWithHealthWorkers-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'Contact with Health Workers'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:ContactWithHealthWorkers. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#ContactWithHealthWorkers-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'Contact with Health Workers'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:ExposureViaCongregation. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#ExposureViaCongregation-', ?pid))) AS ?nexp). FILTER(CONTAINS(LCASE(?rs), 'attended congregation') || CONTAINS(LCASE(?rs), 'attended the congregation'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact' || ?rs = 'Contact of AP patient')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedRoomMate. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasRoommate ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedRoomMate-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Roommate'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedViaPoliceWork. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p a codo:PolicePerson.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedViaPoliceWork-', ?pid))) AS ?nexp). FILTER(CONTAINS(LCASE(?rs),'police'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedViaHealthcareWork. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p a codo:HealthCareProfessional.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedViaHealthcareWorkb-', ?pid))) AS ?nexp). FILTER(CONTAINS(LCASE(?rs),'healthcare worker') || CONTAINS(LCASE(?rs),'hospital staff') || CONTAINS(LCASE(?rs),'health care worker') || CONTAINS(LCASE(?rs),'doctor'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedViaJob. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedViaJob-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Pharma Company Worker') || CONTAINS(LCASE(?rs),'ictc counselor') || CONTAINS(LCASE(?rs),'anganwadi worker'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedNephew. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasNephew ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedNephew-', ?pid))) AS ?nexp). FILTER(?rs = 'Son of sister')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedFamilyMember. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:kinswomen ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedFamilyMember-', ?pid))) AS ?nexp). FILTER(?rs = 'Daughter of Brother in law' || ?rs = 'Daughter in law' || ?rs = 'Wife of brother')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedFamilyMember. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:kinsman ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedFamilyMember-', ?pid))) AS ?nexp). FILTER(?rs = 'Son of Brother in law')}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedNeighbor. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasNeighbor ?sh.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. ?p codo:contractedVirusFrom ?sh. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedNeighbor-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Neighbor'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedNeighbor. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedNeighbor-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Neighbor'))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedViaJob. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p a codo:SecurityGuard.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedNeighbor-', ?pid))) AS ?nexp). FILTER(?rs = 'Security Guard')}") ;Commit the changes (commit-triple-store) ) (defun run-third-codo-sparql-transforms () (print "Entering third transforms") ; This is different order than in SPARQL files. Need to handle the strings ; with "Ward 135" first because otherwise they will match the regex for numeric strings (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh. ?p codo:travelledFrom ?place. ?nexp codo:travelledFrom ?place.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND #Wards of Cities (IF (CONTAINS(?rs, 'Ward 135'), codo:Ward135, # Cities # Start with cities because if the city is there the additional info (state, country) # is in the ontology and we can ignore that data in the string (IF (CONTAINS(?rs, 'Abu Dhabi'), codo:AbuDhabi, (IF (CONTAINS(?rs, 'Ahmedabad'), codo:Ahmedabad, (IF (CONTAINS(?rs, 'Ajmer'), codo:Ajmer, (IF (CONTAINS(?rs, 'Amsterdam'), codo:Amsterdam, (IF (CONTAINS(?rs, 'Athens'), codo:Athens, (IF (CONTAINS(?rs, 'Bagalkote'), codo:Bagalkote, (IF (CONTAINS(?rs, 'Baroda'), codo:Baroda, (IF (CONTAINS(?rs, 'Bangalore'), codo:Bangalore, (IF (CONTAINS(?rs, 'Bangalore-Urban'), codo:Bangalore, (IF (CONTAINS(?rs, 'Belgavi'), codo:Belgavi, (IF (CONTAINS(?rs, 'Bellary'), codo:Bellary, (IF (CONTAINS(?rs, 'Bidar'), codo:Bidar, (IF (CONTAINS(?rs, 'Channagiri'), codo:Channagiri,(IF (CONTAINS(?rs, 'Chamarajanagar'), codo:Chamarajanagar,(IF (CONTAINS(?rs, 'Chennai'), codo:Chennai, (IF (CONTAINS(?rs, 'Chikballarpur'), codo:Chikballarpur, (IF (CONTAINS(?rs, 'Chikkamagalur'), codo:Chikmagalur, (IF (CONTAINS(?rs, 'Chitradurga'), codo:Chitradurga, (IF (CONTAINS(?rs, 'Colombo'), codo:Colombo,(IF (CONTAINS(?rs, 'Dammam'), codo:Dammam, (IF (CONTAINS(?rs, 'Davangere'), codo:Davangere, (IF (CONTAINS(?rs, 'Dharwad'), codo:Dharwad,(IF (CONTAINS(?rs, 'Debaspete'), codo:Debaspete, (IF (CONTAINS(?rs, 'Delhi'), codo:Delhi, (IF (CONTAINS(?rs, 'Doha'), codo:Doha, (IF (CONTAINS(?rs, 'Dubai'), codo:Dubai, (IF (CONTAINS(?rs, 'Edinburgh'), codo:Edinburgh, (IF (CONTAINS(?rs, 'Gadag'), codo:Gadag, (IF (CONTAINS(?rs, 'Goa'), codo:Goa, (IF (CONTAINS(?rs, 'Gunturu'), codo:Gunturu, (IF (CONTAINS(?rs, 'Hassan'), codo:Hassan, (IF (CONTAINS(?rs, 'Haveri'), codo:Haveri,(IF (CONTAINS(?rs, 'Hindupur'), codo:Hindupur, (IF (CONTAINS(?rs, 'Hubbali'), codo:Hubli, (IF (CONTAINS(?rs, 'Humnabad'), codo:Humnabad, (IF (CONTAINS(?rs, 'Hyderabad'), codo:Hyderabad, (IF (CONTAINS(?rs, 'Jalgaon'), codo:Jalgaon,(IF (CONTAINS(?rs, 'Jeddah'), codo:Jeddah,(IF (CONTAINS(?rs, 'Kalburgi'), codo:Kalaburagi, (IF (CONTAINS(?rs, 'Jammu'), codo:Jammu, (IF (CONTAINS(?rs, 'Kolar'), codo:Kolar, (IF (CONTAINS(?rs, 'Kolkata'), codo:Kolkata, (IF (CONTAINS(?rs, 'Kolhapur'), codo:Kolhapur, (IF (CONTAINS(?rs, 'Koppal'), codo:Koppal, (IF (CONTAINS(?rs, 'London'), codo:London, (IF (CONTAINS(?rs, 'Madikeri'), codo:Madikeri, (IF (CONTAINS(?rs, 'Madrid'), codo:Madrid, (IF (CONTAINS(?rs, 'Madurai'), codo:Madurai, (IF (CONTAINS(?rs, 'Mandya'), codo:Mandya, (IF (CONTAINS(?rs, 'Mangalore'), codo:Mangalore, (IF (CONTAINS(?rs, 'Mecca'), codo:Mecca, (IF (CONTAINS(?rs, 'Mumbai'), codo:Mumbai, (IF (CONTAINS(?rs, 'Muscat'), codo:Muscat, (IF (CONTAINS(?rs, 'Nandurbar'), codo:Nandurbar,(IF (CONTAINS(?rs, 'Nelamangala'), codo:Nelamangala, (IF (CONTAINS(?rs, 'New York'), codo:NewYorkCity, (IF (CONTAINS(?rs, 'Palghar'), codo:Palghar, (IF (CONTAINS(?rs, 'Panvel'), codo:Panvel, (IF (CONTAINS(?rs, 'Paris'), codo:Paris, (IF (CONTAINS(?rs, 'Pune'), codo:Pune, (IF (CONTAINS(?rs, 'Raichur'), codo:Raichur, (IF (CONTAINS(?rs, 'Rayachuru'), codo:Raichur, (IF (CONTAINS(?rs, 'Ratnagiri'), codo:Ratnagiri, (IF (CONTAINS(?rs, 'Ratnagiri'), codo:Ratnagiri, (IF (CONTAINS(?rs, 'Ramanagar'), codo:Ramnagar, (IF (CONTAINS(?rs, 'Ramnagar'), codo:Ramnagar, (IF (CONTAINS(?rs, 'Riyadh'), codo:Riyadh, (IF (CONTAINS(?rs, 'Sharjah'), codo:Sharjah, (IF (CONTAINS(?rs, 'Shivamogga'), codo:Shivamogga,(IF (CONTAINS(?rs, 'Shikharaji'), codo:Shikharaji, (IF (CONTAINS(?rs, 'Shivamogga'), codo:Shivamogga, (IF (CONTAINS(?rs, 'Singapore'), codo:Singapore, (IF (CONTAINS(?rs, 'Solapur'), codo:Solapur,(IF (CONTAINS(?rs, 'Surat'), codo:Surat, (IF (CONTAINS(?rs, 'Thane'), codo:Thane, (IF (CONTAINS(?rs, 'Tumkur'), codo:Tumkur, (IF (CONTAINS(?rs, 'Udupi'), codo:Udupi,(IF (CONTAINS(?rs, 'Vellore'), codo:Vellore, (IF (CONTAINS(?rs, 'Vijayapur'), codo:Vijayapura, (IF (CONTAINS(?rs, 'Vishakapatnam'), codo:Vishakapatnam,(IF (CONTAINS(?rs, 'Yadgir'), codo:Yadgir, owl:Nothing))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) AS ?place). BIND (IRI(CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCo-Passenger-', ?pid)) AS ?nexp). FILTER(?place != owl:Nothing)}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:hasTravelCompanion ?sh. ?p codo:travelledFrom ?place. ?nexp codo:travelledFrom ?place.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND # States (IF (CONTAINS(?rs, 'Andhra Pradesh'), codo:AndhraPradesh, (IF (CONTAINS(?rs, 'Assam'), codo:Assam, (IF (CONTAINS(?rs, 'Bihar'), codo:Bihar, (IF (CONTAINS(?rs, 'Chattisgadh'), codo:Chattisgadh, (IF (CONTAINS(?rs, 'Haryana'), codo:Haryana, (IF (CONTAINS(?rs, 'Himachal Pradesh'), codo:HimachalPradesh, (IF (CONTAINS(?rs, 'Jharkhand'), codo:Jharkhand, (IF (CONTAINS(?rs, 'Kerala'), codo:Kerala, (IF (CONTAINS(?rs, 'Madhya Pradesh'), codo:MadhyaPradesh, (IF (CONTAINS(?rs, 'Manipur'), codo:Manipur, (IF (CONTAINS(?rs, 'Nagaland'), codo:Nagaland, (IF (CONTAINS(?rs, 'Orissa'), codo:Orissa, (IF (CONTAINS(?rs, 'Tamil Nadu'), codo:TamilNadu, (IF (CONTAINS(?rs, 'Telengana'), codo:Telengana, (IF (CONTAINS(?rs, 'Texas'), codo:Texas, (IF (CONTAINS(?rs, 'Uttar Pradesh'), codo:UttarPradesh, (IF (CONTAINS(?rs, 'West Bengal'), codo:WestBengal, (IF (CONTAINS(?rs, 'West Bangal'), codo:WestBengal, #Districts (IF (CONTAINS(LCASE(?rs), 'andaman and nicobar'), codo:AndamanAndNicobarIslands, (IF (CONTAINS(LCASE(?rs), 'dakshin kannada'), codo:DakshinKannadaDistrict, (IF (CONTAINS(?rs, 'Kodagu'), codo:KodaguDistrict, (IF (CONTAINS(?rs, 'Mysore'), codo:Mysore, (IF (CONTAINS(?rs, 'Raigadh'), codo:Raigadh, (IF (CONTAINS(?rs, 'Uttarakhand'), codo:Uttarakhand, (IF (CONTAINS(?rs, 'Uttar Kannada'), codo:UttarKannada,(IF (CONTAINS(?rs, 'Uttara Kannada'), codo:UttarKannada, # Countries (IF (CONTAINS(?rs, 'Argentina'), codo:Argentina,(IF (CONTAINS(?rs, 'Bangladesh'), codo:Bangladesh,(IF (CONTAINS(?rs, 'Bahrain'), codo:Bahrain, (IF (CONTAINS(?rs, 'Brazil'), codo:Brazil, (IF (CONTAINS(?rs, 'Domestic travel'), codo:India,(IF (CONTAINS(?rs, 'Interdistrict travel'), codo:India,(IF (CONTAINS(?rs, 'France'), codo:France, (IF (CONTAINS(?rs, 'Germany'), codo:Germany, (IF (CONTAINS(?rs, 'Greece'), codo:Greece, (IF (CONTAINS(?rs, 'Guyana'), codo:Guyana, (IF (CONTAINS(?rs, 'Indonesia'), codo:Indonesia, (IF (CONTAINS(?rs, 'Iraq'), codo:Iraq, (IF (CONTAINS(?rs, 'Ireland'), codo:Ireland, (IF (CONTAINS(?rs, 'Italy'), codo:Italy, (IF (CONTAINS(?rs, 'Kuwait'), codo:Kuwait, (IF (CONTAINS(?rs, 'Malaysia'), codo:Malaysia,(IF (CONTAINS(?rs, 'Nepal'), codo:Nepal, (IF (CONTAINS(?rs, 'Philippines'), codo:Philippines,(IF (CONTAINS(?rs, 'Saudi Arabia'), codo:SaudiArabia,(IF (CONTAINS(?rs, 'South Africa'), codo:SouthAfrica, (IF (CONTAINS(?rs, 'Qatar'), codo:Qatar, (IF (CONTAINS(?rs, 'Spain'), codo:Spain, (IF (CONTAINS(?rs, 'Switzerland'), codo:Switzerland, (IF (CONTAINS(?rs, 'Turkey'), codo:Turkey, (IF (CONTAINS(?rs, 'UAE'), codo:UnitedArabEmirates, (IF (CONTAINS(?rs, 'UK'), codo:UK, (IF (CONTAINS(?rs, 'United States'), codo:UnitedStates, # Regions (IF (CONTAINS(?rs, 'Punjab'), codo:Punjab, owl:Nothing))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) AS ?place). FILTER(?place != owl:Nothing)}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Spouse') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Wife') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSpouse. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSpouse-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Husband') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedDaughter. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDaughter-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Daughter') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSister. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSister-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Sister') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedMother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedMother-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Mother') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedFather. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedFather-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Father') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedSon. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedSon-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Son') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedBrother. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedBrother-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Brother') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCousin. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedCousin-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER((?rs = 'Cousin') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedDomesticHelp. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDomesticHelp-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER(CONTAINS(?rs, 'Domestic help') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:InfectedCo-Passenger. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#InfectedDomesticHelp-', ?pid))) AS ?nexp). OPTIONAL{?p codo:contractedVirusFrom ?sh.} FILTER(CONTAINS(?rs, 'Co passenger') && !bound(?sh))}") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} INSERT {?nexp a codo:SecondaryContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#SecondaryContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(LCASE(?rs), 'secondary contact'))}") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?dg a codo:COVID-19Diagnosis. ?dg a codo:UnderTracing. ?p codo:hasDiagnosis ?dg.} WHERE { ?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#UnderTracingDiagnosis-', ?pid))) AS ?dg). FILTER(CONTAINS(LCASE(?rs), 'under tracing')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?dg a codo:COVID-19Diagnosis. ?dg a codo:PreSurgeryTest. ?p codo:hasDiagnosis ?dg.} WHERE { ?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#PreSurgeryTestDiagnosis-', ?pid))) AS ?dg). FILTER(CONTAINS(LCASE(?rs), 'pre -op') || CONTAINS(LCASE(?rs), 'pre-surgery')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?dg a codo:COVID-19Diagnosis. ?dg a codo:PregnancyScreening. ?p codo:hasDiagnosis ?dg.} WHERE { ?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#PregnancyScreeningDiagnosis-', ?pid))) AS ?dg). FILTER(CONTAINS(LCASE(?rs), 'pregnant')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p1 a schema:Patient. ?p1 codo:districtPatientID ?rs. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?p1. ?p codo:hasRelationship ?p1. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#Patient-', ?rs))) AS ?p1). BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs, 'CKB-')) }") (sparql:run-sparql "DELETE {?p codo:reasonString ?rs.} WHERE {?p codo:statePatientID ?pid. ?p codo:reasonString ?rs. FILTER(CONTAINS(?rs, 'No details') || ?rs = ''|| ?rs = ' ')}") ;Commit the changes (commit-triple-store)) (defun run-codo-sparql-transforms () (run-initial-codo-sparql-transforms) (run-second-codo-sparql-transforms) (run-third-codo-sparql-transforms))
44,460
Common Lisp
.cl
679
60.97349
221
0.679817
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
63b8d7f5a709cf6ae1e4d62d6725a11596d8a09d3fcf7af280c0eaba67c597d4
40,214
[ -1 ]
40,215
city-and-admission-transforms.cl
mdebellis_CODO-Lisp/city-and-admission-transforms.cl
;File to deal with City strings and admission dates (in-package :db.agraph.user) (defun codo-city-transforms () (print "Entering City transforms") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf codo:Bangalore-Urban; codo:isPermanentResidentOf codo:Anantapura.} WHERE {?p codo:cityString ?cstring. filter(?cstring = 'Bangalore-Urban although from Ananthpura in AP' || CONTAINS(?cstring,'Bangalore-Urban although resident of Ananthpur'))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf codo:Bidar; codo:isPermanentResidentOf codo:PaheliChouki.} WHERE {?p codo:cityString ?cstring. filter(?cstring = 'Bidar although resident of Paheli Chouki in Hyderabad')}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf codo:Bidar; codo:isPermanentResidentOf codo:Hyderabad.} WHERE {?p codo:cityString ?cstring. filter(CONTAINS(?cstring, 'Bidar and resident of Hyderabad'))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf codo:Bidar; codo:isPermanentResidentOf codo:PaheliChouki.} WHERE {?p codo:cityString ?cstring. filter(?cstring = 'Bidar although resident of Paheli Chouki in Hyderabad')}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf ?crcity; codo:isPermanentResidentOf ?prcity.} WHERE {?p codo:cityString ?cstring. BIND(STRBEFORE(?cstring, ' although resident of ') AS ?crstring). BIND(STRAFTER(?cstring, ' although resident of ') AS ?prstring). BIND(IF(CONTAINS(?crstring, ' '), STRBEFORE(?crstring, ' '), ?crstring) AS ?crstr). BIND(IF(CONTAINS(?prstring, ' '), STRBEFORE(?prstring, ' '), ?prstring) AS ?prstr). ?crcity codo:geoName ?crstr. ?prcity codo:geoName ?prstr. filter(contains(?cstring, ' although resident of '))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf ?crcity; codo:isPermanentResidentOf ?prcity.} WHERE {?p codo:cityString ?cstring. BIND(STRBEFORE(?cstring, ' but resident of ') AS ?crstring). BIND(STRAFTER(?cstring, ' but resident of ') AS ?prstring). BIND(IF(CONTAINS(?crstring, ' '), STRBEFORE(?crstring, ' '), ?crstring) AS ?crstr). BIND(IF(CONTAINS(?prstring, ' '), STRBEFORE(?prstring, ' '), ?prstring) AS ?prstr). ?crcity codo:geoName ?crstr. ?prcity codo:geoName ?prstr. filter(contains(?cstring, ' but resident of '))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf ?crcity; codo:isPermanentResidentOf ?crcity.} WHERE {?p codo:cityString ?cstring. BIND(STRBEFORE(?cstring, ' ') AS ?crstring). ?crcity codo:geoName ?crstring. filter(regex(?cstring, '\\\\D+ \\\\D+'))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf ?crcity; codo:isPermanentResidentOf ?crcity.} WHERE {?p codo:cityString ?cstring. BIND(STRBEFORE(?cstring, ' in ') AS ?crstring). ?crcity codo:geoName ?crstring. filter(contains(?cstring, ' in '))}") (sparql:run-sparql "DELETE {?p codo:cityString ?cstring.} INSERT {?p codo:isCurrentResidentOf ?city; codo:isPermanentResidentOf ?city.} WHERE {?p codo:cityString ?cstring. BIND(IF(STRENDS(?cstring, ' '), STRBEFORE(?cstring, ' '), ?cstring) AS ?trmdcstring). ?city codo:geoName ?trmdcstring.}") (commit-triple-store)) (defun codo-outdate-transforms () (print "Entering Out Date transforms") ;Transform all properly formatted outdateString (sparql:run-sparql "DELETE {?p codo:outdateString ?outstr.} INSERT {?p codo:releasedOn ?outdt.} WHERE {?p codo:outdateString ?outstr. BIND(SUBSTR(?outstr, 1, 2) AS ?dstr). BIND(SUBSTR(?outstr, 4, 2) AS ?mstr). BIND(SUBSTR(?outstr, 7, 4) AS ?ystr). BIND(CONCAT(?ystr,'-',?mstr,'-',?dstr,'T00:00:00') AS ?dtstr). BIND(xsd:dateTime(?dtstr) AS ?outdt). FILTER(STRLEN(?outstr) = 10)}") ;If not in test mode delete all remaining cityString If in test mode ;keep them to examine in case some strings that should have been processed weren't (if (not *test-modep*) (sparql:run-sparql "DELETE {?p codo:outdateString ?outstr.} WHERE {?p codo:outdateString ?outstr.}")) (commit-triple-store)) (defun city-outdate-transforms () (codo-city-transforms) (codo-outdate-transforms))
4,648
Common Lisp
.cl
87
47.609195
150
0.690271
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
9739469e9c86e0f0baa411f3513649c5c90e4d4782ebc54024f683b1e1f9c601
40,215
[ -1 ]
40,216
sparql-regex-transforms.cl
mdebellis_CODO-Lisp/sparql-regex-transforms.cl
;All functions assume that the codo triplestore is open and bound to *db* ;Also, there must be a Text Index set up with the Object being the value ;of the codo:statePatientID property. This enables fast lookups for patients based on their hasID ;Note: when compiling this file or individual functions you will get warnings that variable ;matched-p is not used. These are not serious. One function returns multiple values and we ;need the second value but not the first but to get a handle on the second value we need to ;provide a variable that binds to both. Matched-p is that variable. (in-package :db.agraph.user) (defun analyze-ad-hoc-pid-strings1 () (print "Entering ad hoc transforms 1") ;Father of P154 not in model so using 154 (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '104'. ?pc2 codo:statePatientID '154'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact with P104 and father of P154') }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '159'. ?pc2 codo:statePatientID '103'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact of P159 and son of P103')}") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '19'. ?pc2 codo:statePatientID '94'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact with P19 and sister of P94') }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '1243'. ?pc2 codo:statePatientID '1244'. ?pc3 codo:statePatientID '1245'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact of P1243 to P1245') }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. ?p codo:contractedVirusFrom ?pc4. ?p codo:hasRelationship ?pc4. ?p codo:contractedVirusFrom ?pc5. ?p codo:hasRelationship ?pc5. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '134'. ?pc2 codo:statePatientID '135'. ?pc3 codo:statePatientID '136'. ?pc4 codo:statePatientID '137'. ?pc5 codo:statePatientID '138'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Contact with P134-P135-P136-P137 and P138') || CONTAINS(?rs,'Contact with P134- P135- P136- P137 and P138')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. ?p codo:contractedVirusFrom ?pc4. ?p codo:hasRelationship ?pc4. ?p codo:contractedVirusFrom ?pc5. ?p codo:hasRelationship ?pc5. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '134'. ?pc2 codo:statePatientID '135'. ?pc3 codo:statePatientID '136'. ?pc4 codo:statePatientID '137'. ?pc5 codo:statePatientID '139'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Contact with P134-P135-P136-P137 and P139')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. ?p codo:contractedVirusFrom ?pc4. ?p codo:hasRelationship ?pc4. ?p codo:contractedVirusFrom ?pc5. ?p codo:hasRelationship ?pc5. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '134'. ?pc2 codo:statePatientID '135'. ?pc3 codo:statePatientID '136'. ?pc4 codo:statePatientID '137'. ?pc5 codo:statePatientID '140'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Contact with P134-P135-P136-P137 and P140')) }") ) (defun analyze-ad-hoc-pid-strings2 () (print "Entering ad hoc transforms 2") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. ?p codo:contractedVirusFrom ?pc4. ?p codo:hasRelationship ?pc4. ?p codo:contractedVirusFrom ?pc5. ?p codo:hasRelationship ?pc5. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '89'. ?pc2 codo:statePatientID '90'. ?pc3 codo:statePatientID '91'. ?pc4 codo:statePatientID '141'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Contact of P89-P90-P91 and P141'))}") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '16752'. ?pc2 codo:statePatientID '16753'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(CONTAINS(?rs,'Contact of P- 16752 and P-16753')) }") (sparql:run-sparql "DELETE { ?p codo:reasonString ?rs.} INSERT { ?nexp a codo:CloseContact. ?p codo:suspectedReasonOfCatchingCovid-19 ?nexp. ?p codo:contractedVirusFrom ?pc1. ?p codo:hasRelationship ?pc1. ?p codo:contractedVirusFrom ?pc2. ?p codo:hasRelationship ?pc2. ?p codo:contractedVirusFrom ?pc3. ?p codo:hasRelationship ?pc3. ?p codo:contractedVirusFrom ?pc4. ?p codo:hasRelationship ?pc4. ?p codo:contractedVirusFrom ?pc5. ?p codo:hasRelationship ?pc5. } WHERE { ?p codo:reasonString ?rs. ?p codo:statePatientID ?pid. ?pc1 codo:statePatientID '23238'. ?pc2 codo:statePatientID '23239'. ?pc3 codo:statePatientID '23240'. ?pc4 codo:statePatientID '23241'. ?pc5 codo:statePatientID '23231'. BIND (IRI((CONCAT('http://www.isibang.ac.in/ns/codo#CloseContact-', ?pid))) AS ?nexp). FILTER(?rs = 'Contact of P23238 to P23241 and P23231') }")) (defun make-close-contact-object (patient-upi rs-upi) ;A utility function for all the functions that process ;reasonString properties with patient ID's in them ;Creates an instance of the codo:CloseContact object and makes it the value of the ;suspectedReasonOfCatchingCovid-19 property ;upi->value gets the string representation of the name of the object (let* ((pid-upi (object (get-triple :s patient-upi :p !codo:statePatientID))) (pid-string (upi->value pid-upi)) (nexp-uri-string (concatenate 'string "http://www.isibang.ac.in/ns/codo#CloseContact-" pid-string)) (nexp-upi (intern-resource nexp-uri-string))) (add-triple nexp-upi !rdf:type !codo:CloseContact) (add-triple patient-upi !codo:suspectedReasonOfCatchingCovid-19 nexp-upi) (if *test-modep* (add-triple patient-upi !codo:reasonStringTD rs-upi)) (delete-triples :s patient-upi :p !codo:reasonString :o rs-upi) ) ) (defun analyze-pid-strings1 () (print "Entering pattern matching transforms 1") ; For strings of the form: "Contact of P1606-1608" (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(REGEX(?rs, 'Contact of P\\\\d+-\\\\d+'))}" :results-format :lists))) ; Don't really need to loop for current data since only one string matches this pattern but best to do this ; in case new data has more strings like this (loop for result in results do ;Each result has two bindings, each in a list. First binding is the patient-upi ?p second is the reasonString-upi ?rs ;Following Let gets the bindings and gets the reasonString from its UPI (let* ((patient-upi (first result)) (patient-value (part->terse patient-upi)) (rs-upi (second result)) (rs (upi->value rs-upi)) ) ;Need multiple-value-bind because match-re returns a boolean if it succeeds and then the actual matched string ;Don't need the boolean but need to bind to it anyway to get the string. This results in a compilation warning ;because the variable matched-p is not used (multiple-value-bind (matched-p ids) (match-re "\\d+-\\d+" rs) ;Split-re returns a list with the two integers between the dash (let* ((id-string-list (split-re "-" ids)) (first-id-num (parse-integer (first id-string-list))) (last-id-num (parse-integer (second id-string-list)))) ;Use freetext index to efficiently retrieve the patient from its ID number (loop for id-index from first-id-num to last-id-num do ;String+ converts the integer back to a string so it can be used to find the patient (let* ((id-string (string+ id-index)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string) :index "PatientIDs"))) ) (print (list patient-value id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) )))) (make-close-contact-object patient-upi rs-upi) ))) (commit-triple-store) ) (defun analyze-pid-strings2 () ; For strings of the form: "Contact of P6137 to P6139" (print "Entering pattern matching transforms 2") (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(REGEX(?rs, 'Contact of P\\\\d+ to P\\\\d+'))}" :results-format :lists))) ; Don't really need to loop for current data since only one string matches this pattern but best to do this ; in case new data has more strings like this (loop for result in results do ;Each result has two bindings, each in a list. First binding is the patient-upi ?p second is the reasonString-upi ?rs ;Following Let gets the bindings and gets the reasonString from its UPI (let* ((patient-upi (first result)) (patient-value (part->terse patient-upi)) (rs-upi (second result)) (rs (upi->value rs-upi)) ) ;Need multiple-value-bind because match-re returns a boolean if it succeeds and then the actual matched string ;Don't need the boolean but need to bind to it anyway to get the string. This results in a compilation warning ;because the variable matched-p is not used (multiple-value-bind (matched-p ids) (match-re "\\d+ to P\\d+" rs) ;Split-re returns a list with the two integers between the dash (let* ((id-string-list (split-re " to P" ids)) (first-id-num (parse-integer (first id-string-list))) (last-id-num (parse-integer (second id-string-list)))) ;Use freetext index to efficiently retrieve the patient from its ID number (loop for id-index from first-id-num to last-id-num do ;String+ converts the integer back to a string so it can be used to find the patient (let* ((id-string (string+ id-index)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string)))) ) (print (list patient-value id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) )))) (make-close-contact-object patient-upi rs-upi) ))) (commit-triple-store) ) (defun analyze-pid-strings3 () ; For strings of the form: "Contact of P1942-P1944 and P1947" ; See analyze-pid-strings1 for more detailed comments (print "Entering pattern matching transforms 3") (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(REGEX(?rs, ' P\\\\d+-P\\\\d+ and P\\\\d+'))}" :results-format :lists))) ;As in previous function, each result contains a list of the patient UPI and the reasonString UPI ;Everything else works as in analyze-seq-reason-strings1 except this checks for a different pattern and has to match ;for an additional patient ID that comes after the "and" (loop for result in results do (let* ((patient-upi (first result)) (rs-upi (second result)) (rs (upi->value rs-upi)) ) (multiple-value-bind (matched-p ids) (match-re "\\d+-P\\d+" rs) (let* ((id-string-list (split-re "-P" ids)) (first-id-num (parse-integer (first id-string-list))) (last-id-num (parse-integer (second id-string-list))) ) (loop for id-index from first-id-num to last-id-num do (let* ((id-string (string+ id-index)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string)))) ) (print (list patient-upi id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) )))) (multiple-value-bind (matched-p and-id-string) (match-re "and P\\d+" rs) (let* ((id-string (subseq and-id-string 5)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string))))) (print (list patient-upi id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) ) ) (make-close-contact-object patient-upi rs-upi)))) (commit-triple-store) ) (defun analyze-pid-strings8 () ; For strings of the form: "Contact of P1942-P1945" (print "Entering pattern matching transforms 8") (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(REGEX(?rs, 'Contact of P\\\\d+-P\\\\d+'))}" :results-format :lists))) ; Don't really need to loop for current data since only one string matches this pattern but best to do this ; in case new data has more strings like this (loop for result in results do ;Each result has two bindings, each in a list. First binding is the patient-upi ?p second is the reasonString-upi ?rs ;Following Let gets the bindings and gets the reasonString from its UPI (let* ((patient-upi (first result)) (patient-value (part->terse patient-upi)) (rs-upi (second result)) (rs (upi->value rs-upi)) ) ;Need multiple-value-bind because match-re returns a boolean if it succeeds and then the actual matched string ;Don't need the boolean but need to bind to it anyway to get the string. This results in a compilation warning ;because the variable matched-p is not used (multiple-value-bind (matched-p ids) (match-re "\\d+-P\\d+" rs) ;Split-re returns a list with the two integers between the dash (let* ((id-string-list (split-re "-P" ids)) (first-id-num (parse-integer (first id-string-list))) (last-id-num (parse-integer (second id-string-list)))) ;Use freetext index to efficiently retrieve the patient from its ID number (loop for id-index from first-id-num to last-id-num do ;String+ converts the integer back to a string so it can be used to find the patient (let* ((id-string (string+ id-index)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string)))) ) (print (list rs patient-value id-string host-upi)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) )))) (make-close-contact-object patient-upi rs-upi) ))) (commit-triple-store) ) (defun analyze-pid-strings9 () ; For strings of the form: "Contact of P28441 to 28443" (print "Entering pattern matching transforms 9") (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(REGEX(?rs, 'Contact of P\\\\d+ to \\\\d+'))}" :results-format :lists))) ; Don't really need to loop for current data since only one string matches this pattern but best to do this ; in case new data has more strings like this (loop for result in results do ;Each result has two bindings, each in a list. First binding is the patient-upi ?p second is the reasonString-upi ?rs ;Following Let gets the bindings and gets the reasonString from its UPI (let* ((patient-upi (first result)) (patient-value (part->terse patient-upi)) (rs-upi (second result)) (rs (upi->value rs-upi)) ) ;Need multiple-value-bind because match-re returns a boolean if it succeeds and then the actual matched string ;Don't need the boolean but need to bind to it anyway to get the string. This results in a compilation warning ;because the variable matched-p is not used (multiple-value-bind (matched-p ids) (match-re "\\d+ to \\d+" rs) ;Split-re returns a list with the two integers between the dash (let* ((id-string-list (split-re " to " ids)) (first-id-num (parse-integer (first id-string-list))) (last-id-num (parse-integer (second id-string-list)))) ;Use freetext index to efficiently retrieve the patient from its ID number (loop for id-index from first-id-num to last-id-num do ;String+ converts the integer back to a string so it can be used to find the patient (let* ((id-string (string+ id-index)) (host-upi (first (freetext-get-unique-subjects (list 'match id-string)))) ) (print (list patient-value id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) )))) (make-close-contact-object patient-upi rs-upi) ))) (commit-triple-store) ) (defun analyze-pid-stringsG () ; For strings of the form: "Contact of 16752 and 16753 and 19794" ; This is a general function that will replace many of the functions previously above ; It should match any string that starts with "Contact of" and will find each of the patient Ids. ; This should work for any string with patient Ids in it however, it will not process intervals of Ids. ; E.g. "P123-P125" would get processed by this function by just using the ids 123 and 125 and would not include 123 ; Hence, the functions that process intervals must run before this function ; See analyze-pid-strings1 for more detailed comments (print "Entering pattern matching transforms G") (let ((results (sparql:run-sparql "SELECT ?p ?rs WHERE {?p codo:reasonString ?rs. FILTER(STRSTARTS(?rs, 'Contact'))}" :results-format :lists))) (loop for result in results do (let* ( (patient-upi (first result)) (patient-value (part->terse patient-upi)) (rs-upi (second result)) (rs (upi->value rs-upi)) (ids (split-re "\\D+" rs)) ) ;Need multiple-value-bind because match-re returns a boolean if it succeeds and then the actual matched string ;Don't need the boolean but need to bind to it anyway to get the string. This results in a compilation warning ;because the variable matched-p is not used (print rs) (print ids) (loop for id-string in ids do (if (string= id-string "") (print "Ignoring blank id string") (let ((host-upi (first (freetext-get-unique-subjects (list 'match id-string))))) (print (list patient-value id-string)) (add-triple patient-upi !codo:contractedVirusFrom host-upi) (make-close-contact-object patient-upi rs-upi))))))) (commit-triple-store) ) (defun codo-regex-transforms () (analyze-ad-hoc-pid-strings1) (analyze-ad-hoc-pid-strings2) (analyze-pid-strings1) (analyze-pid-strings2) (analyze-pid-strings3) (analyze-pid-strings8) (analyze-pid-strings9) (analyze-pid-stringsG))
23,467
Common Lisp
.cl
493
38.914807
156
0.637275
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
27ed1a2bcf4ea67b6b64884080c8d04a02c7825589cecfd420d00f7bc5823b33
40,216
[ -1 ]
40,222
CODO Vocabulary SPARQL Queries.txt
mdebellis_CODO-Lisp/CODO Vocabulary SPARQL Queries.txt
#SPARQL queries for the CODO ontology #These are all just queries and will not change the #knowledge graph. See the Lisp files #for the SPARQL queries that transform the data #These are generic queries that are independent of any data set #All queries should begin with the following namespaces: PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> PREFIX codo: <http://www.isibang.ac.in/ns/codo#> PREFIX schema: <https://schema.org/> PREFIX t: <http://franz.com/ns/allegrograph/3.0/temporal/> #Find all instance of the class ExposureToCOVID-19 SELECT ?e WHERE {?e a codo:ExposureToCOVID-19} #Find all instance of the class Patient #Note: usually best to use limits as this will be large SELECT ?p WHERE {?p rdf:type schema:Patient} #Find all people diagnosed with Covid SELECT ?p WHERE {?p a codo:DiagnosedWithCovid.} #Find all people diagnosed with Covid who are in family relations SELECT ?p WHERE {?p a codo:DiagnosedWithCovid. ?p codo:hasFamilyRelationship ?r.} #Find people with family relations 2 or more levels deep SELECT DISTINCT ?p ?p1 ?p2 WHERE {?p codo:hasFamilyRelationship ?p1. ?p1 codo:hasFamilyRelationship ?p2.} #Find all patients where it is known who they contracted the #virus from and find the patient the contracted from SELECT ?p ?h WHERE {?p codo:contractedVirusFrom ?h.} #Find all instances of Person and Patient SELECT * WHERE {{?pt a schema:Patient.} UNION {?p a foaf:Person.}} #Give the travel history of a patient #Note: this will give the travel history for all patients #To get the history for one patient, simply replace #the wildcard ?p with the name of a patient (e.g., codo:P000001) SELECT ?p ?tf ?tt WHERE {?p rdf:type schema:Patient. ?p codo:travelledFrom ?tf. ?p codo:travelledTo ?tt.} #Gives all the patients who have contracted the virus from another SELECT ?p ?sh WHERE {?p codo:contractedVirusFrom ?sh.} #Gives all the patients who have contracted the virus from 2 (or more) possible patients SELECT ?p ?sh1 ?sh2 WHERE {?p codo:contractedVirusFrom ?sh1. ?p codo:contractedVirusFrom ?sh2. FILTER(?sh1 != ?sh2)} #Gives all the patients who have passed the virus to 2 (or more) possible patients SELECT ?sh ?p1 ?p2 WHERE {?sh codo:passedVirusTo ?p1. ?sh codo:passedVirusTo ?p2. FILTER(?p1 != ?p2)} #Find chains of patients with length 3 SELECT DISTINCT ?p ?sh1 ?sh2 ?sh3 WHERE {?p codo:contractedVirusFrom ?sh1. ?sh1 codo:contractedVirusFrom ?sh2. ?sh2 codo:contractedVirusFrom ?sh3.} #Find chains of patients with length 5 SELECT DISTINCT ?p ?sh1 ?sh2 ?sh3 ?sh4 ?sh5 WHERE {?p codo:contractedVirusFrom ?sh1. ?sh1 codo:contractedVirusFrom ?sh2. ?sh2 codo:contractedVirusFrom ?sh3. ?sh3 codo:contractedVirusFrom ?sh4. ?sh4 codo:contractedVirusFrom ?sh5.} #Find chains of patients with length 5 #As well as any cities they have travelled to SELECT * WHERE {?p codo:contractedVirusFrom ?sh1. ?sh1 codo:contractedVirusFrom ?sh2. ?sh2 codo:contractedVirusFrom ?sh3. ?sh3 codo:contractedVirusFrom ?sh4. ?sh4 codo:contractedVirusFrom ?sh5. ?p codo:travelledTo ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom?pl5. ?sh5 codo:travelledFrom ?pl6. OPTIONAL {?p codo:travelledFrom ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom ?pl5. ?sh5 codo:travelledFrom ?pl6.} } SELECT * WHERE {?p codo:contractedVirusFrom ?sh1. ?sh1 codo:contractedVirusFrom ?sh2. ?sh2 codo:contractedVirusFrom ?sh3. ?sh3 codo:contractedVirusFrom ?sh4. ?sh4 codo:contractedVirusFrom ?sh5. ?p codo:hasDisease ?d1. ?sh1 codo:hasDisease ?d2. ?sh2 codo:hasDisease ?d3. ?sh3 codo:hasDisease ?d4. ?sh4 codo:hasDisease ?d5. ?sh5 codo:hasDisease ?d6. OPTIONAL {?p codo:hasDisease ?d1. ?sh1 codo:hasDisease ?d2. ?sh2 codo:hasDisease ?d3. ?sh3 codo:hasDisease ?d4. ?sh4 codo:hasDisease ?d5. ?sh5 codo:hasDisease ?d6.} } #Find chains of patients with length 5 #As well as any cities they have travelled to SELECT DISTINCT * WHERE { ?p codo:travelledFrom ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom?pl5. ?sh5 codo:travelledFrom ?pl6. OPTIONAL {?p codo:travelledFrom ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom ?pl5. ?sh5 codo:travelledFrom ?pl6.} } #Find chains of patients with length 5 #As well as their disease objects SELECT DISTINCT * WHERE { ?p codo:travelledFrom ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom?pl5. ?sh5 codo:travelledFrom ?pl6. OPTIONAL {?p codo:travelledFrom ?pl1. ?sh1 codo:travelledFrom ?pl2. ?sh2 codo:travelledFrom ?pl3. ?sh3 codo:travelledFrom ?pl4. ?sh4 codo:travelledFrom ?pl5. ?sh5 codo:travelledFrom ?pl6.} } #Give all patients where we know the reason they caught the virus SELECT ?p ?r WHERE {?p codo:suspectedReasonOfCatchingCovid-19 ?r.} #Find all clusters and the patients in them SELECT ?cl ?p WHERE{?cl codo:hasMember ?p} #Find patients that are not assigned to a cluster SELECT ?p WHERE{?p a schema:Patient. OPTIONAL{?p codo:isMemberOf ?cl.} FILTER(!bound(?cl)) } #Find all triples that are test data SELECT ?td ?p ?o WHERE {?td a codo:TestData. ?td ?p ?o.} #Check for patients with the same hasID SELECT ?p1 ?p2 ?id1 WHERE {?p1 codo:hasID ?id1. ?p2 codo:hasID ?id2. FILTER(?p1 != ?p2 && ?id1 = ?id2)} #List the number of values for each property SELECT ?p (COUNT(?p) AS ?pCount) WHERE {?s ?p ?o .} GROUP BY ?p #Count all the patients SELECT (COUNT(?p) AS ?pCount) WHERE {?p a schema:Patient.} #List all the patients where we know their city SELECT ?p ?city WHERE {?p codo:hasCity ?city.} ORDER BY ?city #List all the cities SELECT ?city WHERE {?city a codo:City.} ORDER BY ?city #List all cities where we know the state and country SELECT DISTINCT ?city ?state ?country WHERE {?city a codo:City. ?city codo:hasState ?state. ?state codo:hasCountry ?country.} ORDER BY ?city #List all cities where we know the country SELECT DISTINCT ?city ?country WHERE {?city a codo:City. ?city codo:hasCountry ?country.} ORDER BY ?city #Count number of towns SELECT ?tcount WHERE {{SELECT (COUNT(?town) AS ?tcount) WHERE {?town a codo:town.}}} #List all the patients under 10 years of age #This can of course be modified for any age range SELECT ?p WHERE {?p a schema:Patient; codo:age ?age. FILTER(?age < 10)} #List all the patients between 18 and 30 #To find different range just change numbers in FILTER SELECT ?p ?age WHERE {?p a schema:Patient; codo:age ?age. FILTER(30 <= ?age && ?age >= 18)} #Count the number of patients in age groups SELECT ?p10count ?p20count ?p30count ?p40count ?p50count ?p60count ?p70count WHERE { {SELECT (COUNT(?p) AS ?p10count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(?age <= 10)}} {SELECT (COUNT(?p) AS ?p20count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(20 >= ?age && ?age > 10)}} {SELECT (COUNT(?p) AS ?p30count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(30 >= ?age && ?age > 20)}} {SELECT (COUNT(?p) AS ?p40count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(40 >= ?age && ?age > 30)}} {SELECT (COUNT(?p) AS ?p50count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(50 >= ?age && ?age > 40)}} {SELECT (COUNT(?p) AS ?p60count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(60 >= ?age && ?age > 50)}} {SELECT (COUNT(?p) AS ?p70count) WHERE {?p a schema:Patient; codo:age ?age. FILTER(?age > 60)}} } #List all patients who have a diagnosis SELECT ?p ?d WHERE {?p codo:hasDiagnosis ?d.} #Competency questions from ontology: #How many people recovered from COVId-19 in place p until date t? #In this example data is June 1 2020 and place is Bangalore-Urban SELECT ?pcount WHERE { {SELECT (COUNT(?p) AS ?pcount) WHERE {?p codo:status codo:Cured; codo:isPermanentResidentOf codo:Bangalore-Urban; codo:releasedOn ?rd. FILTER(?rd <= "2020-06-01T00:00:00"^^xsd:dateTime)}}} #The same query only list the patient and the date ordered by date: SELECT ?p ?rd WHERE {?p codo:status codo:Cured; codo:isPermanentResidentOf codo:Bangalore-Urban; codo:releasedOn ?rd. FILTER(?rd <= "2020-06-01T00:00:00"^^xsd:dateTime)} ORDER BY ?rd #How many people died in country c? Using India as example. SELECT ?pcount WHERE { {SELECT (COUNT(?p) AS ?pcount) WHERE {?p codo:status codo:Deceased; codo:isPermanentResidentOf ?prp. ?prp codo:containedIn codo:India.}}} #Give me the travel history of patient p? #Note: used example of patient with state ID 100 #to get other patients just substitute different ID. SELECT ?p ?tfp WHERE {?p codo:statePatientID "100"; codo:travelledFrom ?tfp.} #Give me the COVID-19 patients and their relationship, if any. SELECT ?p ?pr WHERE {?p codo:hasRelationship ?pr.} #Give me the COVID-19 patients who are in family relationships. #Note: Need to run the Materializer on properties to get the proper results SELECT ?p ?pr WHERE {?p codo:hasFamilyMember ?pr.} #Give me the primary reasons for the maximum number of COVID-19 patients. #Give me the most prevalent symtopms of Severe COVID-19.
9,837
Common Lisp
.l
278
31.960432
90
0.723007
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
fa824986bd81918f80d69685f8958ed479757c0920ab940e1b68dbed30ce3733
40,222
[ -1 ]
40,223
SWRL to SPARQL Rules.txt
mdebellis_CODO-Lisp/SWRL to SPARQL Rules.txt
#This file has SWRL rules that were rewritten in SPARQL because Allegro doesn't support SWRL #Mild and Very Mild Diagnosis: #covid19:hasSymptom(?p, covid19:URTI) ^ covid19:hasSymptom(?p, covid19:Fever) ^ covid19:hasDiagnosis(?p, ?d) -> covid19:MildAndVeryMildCovid19(?d) #Moderate: #covid19:hasSymptom(?p, covid19:Pneumonia) ^ covid19:mostRecentTestResult(?p, ?tr) ^ covid19:respiratoryRate(?tr, ?r) ^ #swrlb:greaterThanOrEqual(?r, 15) ^ covid19:hasDiagnosis(?p, ?d) -> covid19:ModerateCovid19(?d) #Severe: #covid19:hasSymptom(?p, covid19:SeverePneumonia) ^ covid19:mostRecentTestResult(?p, ?tr) ^ covid19:SpO2(?tr, ?sp) ^ #covid19:respiratoryRate(?tr, ?r) ^ foaf:Person(?p) ^ covid19:hasDiagnosis(?p, ?d) ^ #swrlb:greaterThanOrEqual(?r, 30) ^ swrlb:greaterThanOrEqual(?sp, 90) -> covid19:SevereCovid19(?d) INSERT {?d a codo:MildAndVeryMildCovid19.} WHERE {?p a schema:Patient; codo:hasSymptom codo:URTI; codo:hasSymptom codo:Fever; codo:hasDiagnosis ?d.} INSERT {?d a codo:ModerateCovid19.} WHERE {?p a schema:Patient; codo:hasSymptom codo:Pneumonia; codo:mostRecentTestResult ?tr; codo:hasDiagnosis ?d. ?tr codo:respiratoryRate ?r. FILTER(?r >= 15) } INSERT {?d a codo:SevereCovid19.} WHERE {?p a schema:Patient; codo:hasSymptom codo:SeverePneumonia; codo:mostRecentTestResult ?tr; codo:hasDiagnosis ?d. ?tr codo:respiratoryRate ?r; codo:SpO2 ?sp. FILTER(?r >= 30 && ?sp >= 90) } #List all patients who have a diagnosis and mostRecentTestResult SELECT ?p ?d ?tr WHERE {?p codo:hasDiagnosis ?d; codo:mostRecentTestResult ?tr.}
1,601
Common Lisp
.l
36
41.444444
147
0.738372
mdebellis/CODO-Lisp
0
0
0
GPL-3.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
cae00df51b14afdab54fa4f5e8258729e8725a4c0222d85b003241c2701abe6b
40,223
[ -1 ]
40,238
level.lisp
foggynight_tomb/src/level.lisp
(in-package #:tomb) (defstruct level "Level structure representing a level in a world. Levels contain a grid of tiles which compose the space contained within the level, and a list of entities which occupy tiles in the level." tiles entities) (defun read-level-from-file (filename) "Make a level using the contents of the named file." (make-level :tiles (read-tiles-from-file filename))) (defun get-tile (level y x) (aref (level-tiles level) y x)) (defun add-entity (entity level) "Add an entity to the front of the entity list of a level." (setf (level-entities level) (cons entity (level-entities level)))) (defun remove-entity (entity level) "Remove the first entity from the list of entities of a level which is equal to the entity argument." (setf (level-entities level) (remove entity (level-entities level) :count 1))) (defun get-entity (level y x) "Get the entity located at the y-x position in the tile grid of a level, returns nil if no entity is found." (car (member-if (lambda (e) (and (= (entity-y e) y) (= (entity-x e) x))) (level-entities level)))) (defun position-out-of-bounds-p (level y x) "Determine if a position is out of bounds of a level's tile grid." (or (< y 0) (< x 0) (>= y (array-dimension (level-tiles level) 0)) (>= x (array-dimension (level-tiles level) 1)))) (defun level-tile-is-stairs-p (level y x) "Determine if the tile at the y-x position in the tile grid of a level is of the type stairs." (tile-is-stairs-p (get-tile level y x))) (defun level-tile-can-contain-entity-p (level y x) "Determine if the tile at the y-x position in the tile grid of a level can contain an entity. This function does not check if there is already an entity on the tile, only if it is a valid tile for an entity to be on." (let ((tile (get-tile level y x))) (or (tile-is-floor-p tile) (tile-is-stairs-p tile))))
1,956
Common Lisp
.lisp
42
42.5
80
0.695378
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
233980a0f12e2e2fba8fb434c9ba2970364cdfb33b0f591a1ec88b6f184c519a
40,238
[ -1 ]
40,239
main.lisp
foggynight_tomb/src/main.lisp
(in-package #:tomb) (defun main () (let* ((world (generate-world '("res/test-0.lvl" "res/test-1.lvl"))) (player (make-player :y 1 :x 1)) (level (move-to-first-level world player))) (add-entity (make-instance 'entity :pos '(3 . 5) :symbol #\Z) level) (crt:with-screen (scr :cursor-visible nil :enable-function-keys t :input-echoing nil :process-control-chars nil) (crt:with-windows ((note-win :background (make-instance 'crt:complex-char :simple-char #\N) :dimensions '(1 80) :position '(0 0)) (game-win :dimensions '(22 80) :position '(1 0)) (stat-win :dimensions '(1 71) :position '(23 0)) (depth-win :dimensions '(1 8) :position '(23 72))) (let ((window-stack (make-instance 'crt:stack))) (dolist (win (list scr note-win game-win stat-win depth-win)) (crt:stack-push win window-stack)) (crt:bind scr #\ 'crt:exit-event-loop) (macrolet ((bind (keys direction) `(crt:bind scr ,keys (lambda (w e) (declare (ignore w e)) (attempt-move player level ,direction) (draw-game-view game-win level) (crt:refresh window-stack))))) (bind '(#\h :left) :left) (bind '(#\j :down) :down) (bind '(#\k :up) :up) (bind '(#\l :right) :right)) (crt:bind scr #\> (lambda (w e) (declare (ignore w e)) (when (level-tile-is-stairs-p level (entity-y player) (entity-x player)) (setq level (move-to-next-level world player)) (draw-depth-indicator depth-win (world-current-level-index world)) (draw-game-view game-win level) (crt:refresh window-stack)))) (draw-initial-ui scr player world note-win stat-win depth-win) (draw-game-view game-win level) (crt:refresh window-stack) (crt:run-event-loop scr))))))
2,703
Common Lisp
.lisp
54
28.277778
90
0.409366
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
e91d5c683b1b29a2333e21fa04090b5c88763bafc82b69909bbce30cd44a545e
40,239
[ -1 ]
40,240
screen.lisp
foggynight_tomb/src/screen.lisp
(in-package #:tomb) (defun draw-player-stats (stat-win player) "Draw the player stats in the stat window." (crt:clear stat-win) (dolist (stat (entity-stats player)) (dolist (string (list (symbol-name (stat-name stat)) ":" (write-to-string (stat-current stat)) "/" (write-to-string (stat-base stat)) " ")) (crt:add stat-win string)))) (defun draw-depth-indicator-label (depth-win) "Draw the 'Depth:' label of the depth indicator window." (crt:add depth-win "Depth:" :y 0 :x 0)) (defun draw-depth-indicator (depth-win current-level-index) "Draw the player depth in the depth indicator window." (crt:add depth-win (write-to-string current-level-index) :y 0 :x 7)) (defun draw-initial-ui (scr player world note-win stat-win depth-win) "Draw the initial UI, not including the game view." (draw-player-stats stat-win player) (draw-depth-indicator-label depth-win) (draw-depth-indicator depth-win (world-current-level-index world))) (defun draw-game-view (game-win level) "Draw the game view, that is, the tiles and entities composing a given level, in the game view window." (crt:clear game-win) ;; Draw tiles (let* ((tiles (level-tiles level)) (row-width (array-dimension tiles 1))) (dotimes (row-index (array-dimension tiles 0)) (dotimes (cell-index row-width) (crt:add game-win (tile-symbol (aref tiles row-index cell-index))) (crt:move game-win 1 (- row-width) :relative t)))) ;; Draw entities (let ((entities (level-entities level))) (dolist (entity entities) (crt:add game-win (entity-symbol entity) :y (entity-y entity) :x (entity-x entity)))))
1,819
Common Lisp
.lisp
39
38.641026
79
0.631134
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
7be429cca6f6c10739470ffb3725b1b41ac1d0b103d254cc27b3233be3c2d516
40,240
[ -1 ]
40,241
entity.lisp
foggynight_tomb/src/entity.lisp
(in-package #:tomb) (defparameter *entity-max-level* 99 "Maximum level an entity can attain.") (defparameter *entity-level-experience-alist* (let ((experience 0)) (loop for level from 0 to *entity-max-level* do (setq experience (+ experience level)) collect (cons level experience))) "Alist containing pairs of entity levels and the experience thresholds to attain those levels.") (defclass entity () ((pos :accessor entity-pos :initarg :pos :initform '(0 . 0) :type cons :documentation "Position of this entity represented by a cons pair.") (symbol :accessor entity-symbol :initarg :symbol :initform #\? :type standard-char :documentation "Symbol used to represent this entity on-screen.") (stats :accessor entity-stats :initarg :stats :initform nil :type list :documentation "Alist of this entity's stats.") (experience :accessor entity-experience :initarg :experience :initform 0 :type integer :documentation "This entity's experience, represents the amount of combat experience they have, and is obtained by killing enemies. Experience is used to determine the level of this entity.") (level :accessor entity-level :initarg :level :initform 0 :type integer :documentation "This entity's level, represents their level of experience in combat, increasing level gives bonuses to stats. Level is determined by the amount of experience this entity has.")) (:documentation "Entity class representing a being that can move through the world. This is the base class for the various entity types in the game.")) (defmethod entity-y ((obj entity)) (car (entity-pos obj))) (defmethod entity-x ((obj entity)) (cdr (entity-pos obj))) ;; TODO Define setf methods for entity-y and entity-x (defmethod move ((obj entity) direction) "Direct an entity to move in the direction specified by the direction keyword." (let* ((dir (crt:get-direction direction))) (setf (entity-pos obj) (cons (+ (entity-y obj) (car dir)) (+ (entity-x obj) (cadr dir)))))) (defmethod attack ((obj entity) (target entity)) "Direct an entity to attack another entity." (setf (entity-symbol target) #\X)) (defmethod attempt-move ((obj entity) level direction) "Direct an entity to attempt to move using the following logic: if the target position can contain an entity, check if it contains another entity and attack the entity if so, otherwise move to the target position." (let* ((dir (crt:get-direction direction)) (target-y (+ (entity-y obj) (car dir))) (target-x (+ (entity-x obj) (cadr dir)))) (unless (or (position-out-of-bounds-p level target-y target-x) (not (level-tile-can-contain-entity-p level target-y target-x))) (let ((target-entity (get-entity level target-y target-x))) (if target-entity (attack obj target-entity) (move obj direction)))))) (defclass player (entity) () (:documentation "Player class representing the player's character in the game, player is a child class of entity.")) (defun make-player (&key (y nil) (x nil) (pos '(0 . 0)) (symbol #\@)) "Make a new player object." (flet ((make-initial-player-stats () (make-stat-alist '(str 10) '(dex 10) '(int 10)))) (let ((pos-arg (if (and y x) (cons y x) pos))) (make-instance 'player :pos pos-arg :stats (make-initial-player-stats) :symbol symbol)))) (defclass enemy (entity) () (:documentation "Enemy class representing each of the enemies in the game, enemy is a child class of entity."))
3,834
Common Lisp
.lisp
100
32.27
80
0.662097
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
ac0c040f09360dd6613eafa36aaf5b631180471dd8b3c08b44eed17c33078ea6
40,241
[ -1 ]
40,242
world.lisp
foggynight_tomb/src/world.lisp
(in-package #:tomb) (defstruct world "World structure representing a game world divided into levels. Worlds contain a list of levels, as well the index of the level currently containing the player." levels current-level-index) (defun generate-world (filenames) "Generate a world containing levels which are each constructed using a file named in the list of filenames passed as an argument to this function." (let ((world (make-world)) (level-list (loop for filename in filenames collect (read-level-from-file filename)))) (setf (world-levels world) level-list) world)) (defun world-level-count (world) "Get the number of levels contained within a world." (length (world-levels world))) (defun world-level-n (world n) "Get the nth level of a world." (car (nthcdr n (world-levels world)))) (defun world-current-level (world) "Get the current level of a world." (world-level-n world (world-current-level-index world))) (defun move-to-first-level (world player) "Move a player to the first level contained within a world, returns the new current level. This function does not remove the player from the current level before switching levels, thus it should only be called at the start of the program." (setf (world-current-level-index world) 0) (add-entity player (world-current-level world)) (world-current-level world)) (defun move-to-next-level (world player) "Move a player to the next level contained within a world, wraps around the end of the list of worlds, returns the new current level." (remove-entity player (world-current-level world)) (setf (world-current-level-index world) (mod (1+ (world-current-level-index world)) (world-level-count world))) (add-entity player (world-current-level world)) (world-current-level world)) (defun move-to-previous-level (world player) "Move a player to the previous level contained within a world, wraps around the beginning of the list of worlds, returns the new current level." (remove-entity player (world-current-level world)) (setf (world-current-level-index world) (mod (1- (world-current-level-index world)) (world-level-count world))) (add-entity player (world-current-level world)) (world-current-level world))
2,309
Common Lisp
.lisp
50
42.3
80
0.73944
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
914bc8ba455262880e5f4b4d4e3a3f8f269885ab590df01d10338798fe9f5768
40,242
[ -1 ]
40,243
stat.lisp
foggynight_tomb/src/stat.lisp
;;;; Stat Data Structure ;; ;; Stats are represented using lists containing the following members: ;; - NAME: Atomic symbol - Name of the stat ;; - BASE: Integer - Base level of the stat ;; - CURRENT: Integer - Level to be used in calculations involving the stat ;; ;; Lists are used instead of objects to allow stats to be stored in an alist, ;; with their names as the keys and a list containing their base and current ;; levels as the datums, by simply filling a list with stats. (in-package #:tomb) (defun make-stat (name base &optional (current base)) "Make a new stat with the name NAME, base level BASE, and optionally, current level CURRENT, with CURRENT defaulting to the value of BASE." (list name base current)) (defmacro stat-name (stat) "Access the NAME member of a stat." `(car ,stat)) (defmacro stat-base (stat) "Access the BASE member of a stat." `(cadr ,stat)) (defmacro stat-current (stat) "Access the CURRENT member of a stat." `(caddr ,stat)) (defun make-stat-alist (&rest rest) "Make an alist of stats. This function takes any number of lists as arguments, each representing a stat to make and containing the arguments to be passed to the MAKE-STAT function. e.g. (MAKE-STAT-ALIST '(STR 10) '(DEX 10) '(INT 10)) => ((STR 10 10) (DEX 10 10) (INT 10 10))" (mapcar (lambda (e) (apply #'make-stat e)) rest))
1,411
Common Lisp
.lisp
37
34.810811
79
0.700586
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
7aef2cf5f9cea03d41be09f495264ec4ca50f1df8cec9d4c9a5c6911f97c23f9
40,243
[ -1 ]
40,244
tile.lisp
foggynight_tomb/src/tile.lisp
(in-package #:tomb) (defparameter *tile-symbol-type-alist* '((#\. . floor) (#\% . stairs) (#\space . void) (#\# . wall)) "Alist of tile symbol and type pairs.") (defstruct tile "Tile structure representing a tile in a world; tiles are a single cell of space in a world, and are the smallest amount of space which an entity can occupy. Tiles have a position which is inferred from their position in their containing data structure, a symbol used to represent the tile on-screen, and a type which is inferred from the symbol that determines how the tile interacts with objects in a world." symbol) (defun string-to-tile-vector (string) "Convert a string into a vector of tiles." (let ((tile-list (loop for char across string collect (make-tile :symbol char)))) (make-array (length tile-list) :initial-contents tile-list))) ;; TODO Remove constraint: strings must be of same length. I think I will go ;; about this by padding the ends of shorter strings with spaces to the length ;; of the longest string before converting the list of strings to an array. (defun string-list-to-tile-array2 (string-list) "Convert a list of strings into a 2D array of tiles, strings must all be the same length, returns nil when string-list is empty." (if (endp string-list) nil (let ((vector-list nil)) (dolist (string string-list) (setq vector-list (cons (string-to-tile-vector string) vector-list))) (make-array (list (length vector-list) (length (car vector-list))) :initial-contents (reverse vector-list))))) (defun read-tiles-from-file (filename) "Convert the contents of a file into a 2D array of tiles." (with-open-file (stream filename :if-does-not-exist nil) (let ((string-list (loop for line = (read-line stream nil) while line collect line))) (string-list-to-tile-array2 string-list)))) (defun tile-type (tile) "Get the type of a tile based on its symbol, the type is represented by an atomic symbol naming the type." (cdr (assoc (tile-symbol tile) *tile-symbol-type-alist*))) ;; TODO Use macro to define predicate functions for each tile type (defun tile-is-floor-p (tile) (eq (tile-type tile) 'floor)) (defun tile-is-stairs-p (tile) (eq (tile-type tile) 'stairs))
2,434
Common Lisp
.lisp
52
40.711538
79
0.674958
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
467211f3e26a4bca94c570c755a3dc79bc6cbf3ef2e5ef4de957c40bb2eeadfa
40,244
[ -1 ]
40,245
tomb.asd
foggynight_tomb/tomb.asd
(asdf:defsystem #:tomb :author "Robert Coffey" :license "GPLv2" :version "0.1.0" :build-operation "asdf:program-op" :build-pathname "../tomb" :depends-on (#:croatoan) :entry-point "tomb:main" :pathname "src/" :serial t :components ((:file "package") (:file "stat") (:file "entity") (:file "tile") (:file "level") (:file "world") (:file "screen") (:file "main")))
494
Common Lisp
.asd
18
19.166667
36
0.504255
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
fb201dee484f435a12d029b12d9e69500c02717a0abaabc4087bfaee00541e87
40,245
[ -1 ]
40,254
test-0.lvl
foggynight_tomb/res/test-0.lvl
############ ############ #..........# #..........# #.%........#####..........# #.........................# #..........#####..........# #..........# #..........# ############ ############
196
Common Lisp
.l
7
27
27
0
foggynight/tomb
0
0
0
GPL-2.0
9/19/2024, 11:47:59 AM (Europe/Amsterdam)
e3cccff2f2b74196308f65b6cb5d3667e730094de8710d1f2eac87deff2df154
40,254
[ -1 ]
40,269
heap.lisp
toma63_heap-cl/heap.lisp
(defclass heap () ((store :initform (make-array 1000 :adjustable T :fill-pointer 0) :accessor store) (comparison :initform #'> :initarg :comparison :accessor comparison)) (:documentation "a class representation of the heap data structure")) (defgeneric shove (obj value) (:documentation "add one value to the provided heap, maintining the heap property")) (defmethod shove ((obj heap) value) (with-slots (store comparison) obj (let ((new-position (fill-pointer store))) ;; this points to the new value (vector-push-extend value store) ;; increments fill-pointer (when (= new-position 0) (return-from shove T)) (loop (let ((parent-position (- (floor (+ 1 new-position) 2) 1))) (if (funcall comparison (aref store new-position) (aref store parent-position)) (progn (swap-vector-values store new-position parent-position) (setq new-position parent-position) (when (= new-position 0) (return-from shove T))) (return T))))))) (defgeneric yank (obj) (:documentation "remove the next in order element from the heap and rebalance")) (defmethod yank ((obj heap)) (with-slots (store comparison) obj (when (= (fill-pointer store) 0) (return-from yank NIL)) ;; empty (let ((new-fill-pointer (- (fill-pointer store) 1)) (parent-pointer 0) (popped-element (aref store 0))) (setf (fill-pointer store) new-fill-pointer) (when (= new-fill-pointer 0) (return-from yank popped-element)) (setf (aref store parent-pointer) (aref store new-fill-pointer)) ;; last element to top (loop (let* ((first-child-pointer (- (* 2 (+ 1 parent-pointer)) 1)) (second-child-pointer (+ 1 first-child-pointer)) (single-child-p (= second-child-pointer new-fill-pointer))) (when (>= first-child-pointer new-fill-pointer) (return-from yank popped-element)) (when (and single-child-p (funcall comparison (aref store first-child-pointer) (aref store parent-pointer))) (progn (swap-vector-values store parent-pointer first-child-pointer) (return-from yank popped-element))) (let* ((parent-element (aref store parent-pointer)) (first-child-element (aref store first-child-pointer)) (second-child-element (aref store second-child-pointer)) (first>p (funcall comparison first-child-element second-child-element))) (if first>p (if (funcall comparison first-child-element parent-element) (progn (swap-vector-values store parent-pointer first-child-pointer) (setq parent-pointer first-child-pointer)) (return-from yank popped-element)) (if (funcall comparison second-child-element parent-element) (progn (swap-vector-values store parent-pointer second-child-pointer) (setq parent-pointer second-child-pointer)) (return-from yank popped-element))))))))) (defmacro swap-vector-values (v pos1 pos2) "swap the values at the two positions in vector v" `(rotatef (aref ,v ,pos1) (aref ,v ,pos2)))
3,048
Common Lisp
.lisp
66
40.530303
86
0.68691
toma63/heap-cl
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
7c1baf3a4a877a80d72cc0a454c4463784207db4d6457c881a26d9c403a80d78
40,269
[ -1 ]
40,286
levenschtein.lisp
toma63_levenschtein/levenschtein.lisp
(load "../heap-cl/heap.lisp") (defclass partial () ((moves :initform '() :accessor moves :initarg :moves) (cost :initform 0 :accessor cost :initarg :cost) (txt-pos :initform 0 :accessor txt-pos :initarg :txt-pos) (max-txt :initform 0 :accessor max-txt :initarg :max-txt) (pat-pos :initform 0 :accessor pat-pos :initarg :pat-pos) (max-pat :initform 0 :accessor max-pat :initarg :max-pat) (matched :initform 0 :accessor matched :initarg :matched) ; number of matched positions (distance :initform 0 :accessor distance :initarg :distance) (delta :initform 0 :accessor delta :initarg :delta)) (:documentation "a partial solution to a string edit distance")) (defmethod print-object ((obj partial) stream) (print-unreadable-object (obj stream :type t) (with-accessors ((moves moves) (cost cost) (txt-pos txt-pos) (pat-pos pat-pos) (matched matched) (distance distance) (delta delta)) obj (format stream "moves: ~a~% cost: ~a~% matched: ~a~% txt-pos: ~a~% pat-pos: ~a~% distance: ~a~% delta: ~a~%" moves cost matched txt-pos pat-pos distance delta)))) ;; simple test data (defvar txt "abcdefghij") (defvar pat "abdqfghijk") (defvar thou "thou shalt not") (defvar you "you should not") ;; related DNA sequences (defvar tseq "ATCGTATCAGAGCTTTCGTCTGATGCTCGATTGTAA") (defvar tal1 "GTATCAGAGCTTTCGTCTGATGCTCGATTGTAA") (defvar tal2 "ATCGTATCTTTCGTCTGATGCTCGATTGTAA") (defvar tal3 "ATCGTAGAGCTTTCGTCTGATGCTCGATTGTAA") (defvar tal4 "ATCGTATCAGAGCGTCTGATGCATTGTAA") (defvar tal5 "ATCGTAGAGCCGTCTGCTCGATTGTAA") (defvar tal6 "GCTTTCGTCTGATGCTCGATTGTAACAGCAGCAGCAG") (defgeneric compare (obj1 obj2) (:documentation "comparison function for use by a heap")) ;; sorting compare function sums cost, distance, delta less match distance (defmethod compare ((obj1 partial) (obj2 partial)) (with-slots ((cost1 cost) (matched1 matched) (delta1 delta) (distance1 distance)) obj1 (with-slots ((cost2 cost) (matched2 matched) (delta2 delta) (distance2 distance)) obj2 (let ((ext-cost1 (- (+ cost1 distance1 (abs delta1)) matched1)) (ext-cost2 (- (+ cost2 distance2 (abs delta2)) matched2))) (< ext-cost1 ext-cost2))))) (defmacro gap-match-runner (pat pat-ptr txt txt-ptr gap-type) "Given two strings each with a comparison pointer, return the number of consecutive matching characters. if gap-type is non-nil, looks across ins, del, sub edits." (let ((pat-delta (if (member gap-type '(:sub :del)) 1 0)) (txt-delta (if (member gap-type '(:sub :ins)) 1 0))) `(loop for count from 0 by 1 for pp from (+ ,pat-ptr ,pat-delta) to (1- (length ,pat)) for tp from (+ ,txt-ptr ,txt-delta) to (1- (length ,txt)) while (char= (char ,pat pp) (char ,txt tp)) finally (return count)))) (defun last-char (string) "return the last character of a string" (char string (1- (length string)))) (defun gap-char-run (pat pat-pos &optional (gap-char #\N)) "Return a pointer to the last character of a run of gap-chars, or nil if pat-pos does not point to a gap-char." (if (char= gap-char (char pat pat-pos)) (1- (or (position-if-not (lambda (c) (char= c gap-char)) pat :start pat-pos) (length pat))) nil)) ;; create a new partial extended by an insertion (defmethod extend-insert ((part partial) txt) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (make-instance 'partial :moves (cons (cons :i (char txt txt-pos)) (copy-seq moves)) :cost (1+ cost) :pat-pos pat-pos :txt-pos (1+ txt-pos) :max-pat max-pat :max-txt max-txt :matched matched :distance (1- distance) :delta (1+ delta)))) ;; create a new partial extended by a deletion (defmethod extend-delete ((part partial) pat) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (make-instance 'partial :moves (cons (cons :d (char pat pat-pos )) (copy-seq moves)) :cost (1+ cost) :pat-pos (1+ pat-pos) :txt-pos txt-pos :max-pat max-pat :max-txt max-txt :matched matched :distance distance :delta (1- delta)))) ;; create a new partial extended by an insertion (defmethod extend-insert-tail ((part partial) txt) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((tail-length (- (length txt) txt-pos))) (make-instance 'partial :moves (cons (cons :i (subseq txt txt-pos)) (copy-seq moves)) :cost (+ cost tail-length) :pat-pos pat-pos :txt-pos (+ txt-pos tail-length) :max-pat max-pat :max-txt max-txt :matched matched :distance (- distance tail-length) :delta (+ delta tail-length))))) ;; create a new partial extended by deleting the entire tail (defmethod extend-delete-tail ((part partial) pat) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((tail-length (- (length pat) pat-pos))) (make-instance 'partial :moves (cons (cons :d (subseq pat pat-pos)) (copy-seq moves)) :cost (+ cost tail-length) :pat-pos (+ pat-pos tail-length) :txt-pos txt-pos :max-pat max-pat :max-txt max-txt :matched matched :distance distance :delta (- delta tail-length))))) ;; create a new partial extended by a run of matches (defmethod extend-matches ((part partial) match-run) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (make-instance 'partial :moves (cons (cons :m match-run) (copy-seq moves)) :cost cost :pat-pos (+ pat-pos match-run) :txt-pos (+ txt-pos match-run) :max-pat max-pat :max-txt max-txt :matched (+ matched match-run) :distance (- distance match-run) :delta delta))) ;; extend by a deletion, including any subsequent match run (defmethod extend-delete-matches ((part partial) pat txt) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((match-run (gap-match-runner pat pat-pos txt txt-pos :del)) (new-partial (extend-delete part pat))) (if (> match-run 0) (extend-matches new-partial match-run) new-partial)))) ;; extend by an insertion, including any subsequent match run (defmethod extend-insert-matches ((part partial) pat txt) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((match-run (gap-match-runner pat pat-pos txt txt-pos :ins)) (new-partial (extend-insert part txt))) (if (> match-run 0) (extend-matches new-partial match-run) new-partial)))) ;; extend by a substitution, including any subsequent match run (defmethod extend-substitute-matches ((part partial) pat txt) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((match-run (gap-match-runner pat pat-pos txt txt-pos :sub)) (new-partial (make-instance 'partial :moves (cons (cons :s (char txt txt-pos)) (copy-seq moves)) :cost (1+ cost) :pat-pos (1+ pat-pos) :txt-pos (1+ txt-pos) :max-pat max-pat :max-txt max-txt :matched matched :distance (1- distance) :delta delta))) (if (> match-run 0) (extend-matches new-partial match-run) new-partial)))) ;; extend by a pattern gap (defmethod extend-pat-gap ((part partial) txt last-gap-ptr) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((gap-length (1+ (- last-gap-ptr pat-pos)))) (make-instance 'partial :moves (cons (cons :g (subseq txt txt-pos (+ txt-pos gap-length))) (copy-seq moves)) :cost (+ cost gap-length) :pat-pos (+ pat-pos gap-length) :txt-pos (+ txt-pos gap-length) :max-pat max-pat :max-txt max-txt :matched matched :distance (- distance gap-length) :delta delta)))) ;; extend by a text gap (defmethod extend-txt-gap ((part partial) pat last-gap-ptr) (with-slots (moves cost pat-pos txt-pos max-pat max-txt matched distance delta) part (let ((gap-length (1+ (- last-gap-ptr txt-pos)))) (make-instance 'partial :moves (cons (cons :g (subseq pat pat-pos (+ pat-pos gap-length))) (copy-seq moves)) :cost (+ cost gap-length) :pat-pos (+ pat-pos gap-length) :txt-pos (+ txt-pos gap-length) :max-pat max-pat :max-txt max-txt :matched matched :distance (- distance gap-length) :delta delta)))) (defmethod extend ((part partial) pat txt) (with-slots (moves cost matched txt-pos max-txt pat-pos max-pat distance delta) part (cond ((> txt-pos max-txt) ; at the end of the txt, only deletions (list (extend-delete-tail part pat))) ((> pat-pos max-pat) ; at the end of the pattern, only insertions (list (extend-insert-tail part txt))) (t (let* ((last-pat-gap-char (gap-char-run pat pat-pos)) (last-txt-gap-char (gap-char-run txt txt-pos)) (match-run (gap-match-runner pat pat-pos txt txt-pos nil)) (match-or-sub (if (> match-run 0) (extend-matches part match-run) (extend-substitute-matches part pat txt))) (insert (extend-insert-matches part pat txt)) (delete (extend-delete-matches part pat txt))) (cond (last-pat-gap-char ;; always take gap-char runs (list (extend-pat-gap part txt last-pat-gap-char))) (last-txt-gap-char (list (extend-txt-gap part pat last-txt-gap-char))) (t (list delete insert match-or-sub)))))))) (defun trim-identical-tail (string last-n) "trim the last-n characters from string if they are identical" (let* ((trim-point (- (length string) last-n)) (first-char (char string trim-point))) (if (not (find-if (lambda (c) (char-not-equal c first-char)) string :start trim-point)) (subseq string 0 trim-point) string))) (defun trim-longest-tail (pat txt) "when length doesn't match, remove tail of identical chars on the longer. return both." (let* ((pat-length (length pat)) (txt-length (length txt)) (length-diff (abs (- pat-length txt-length)))) (when (or (= pat-length txt-length) (< length-diff 2)) (return-from trim-longest-tail (values pat txt))) (if (< pat-length txt-length) (values pat (trim-identical-tail txt length-diff)) (values (trim-identical-tail pat length-diff) txt)))) (defun align (pat txt &optional (match-length 10)) "Walk alignment of the first match-length character of pat in text until a match run of match-length is seen." (let* ((pat-length (length pat)) (final-match-length (if (< pat-length match-length) pat-length match-length)) (pat-prefix (subseq pat 0 final-match-length))) (search pat-prefix txt))) (defun make-initial-partial (pat txt) "Given a pattern and reference text, create an initial partial solution" (make-instance 'partial :moves '() :cost 0 :matched 0 :pat-pos 0 :max-pat (1- (length pat)) :txt-pos 0 :max-txt (1- (length txt)) :distance (length txt) :delta (- (length pat) (length txt)))) (defun shift-partial (partial shift-distance longer-string ins-or-del) "adjust the initial partial if the pat and text are offset (:ins or :del)" (let ((excess (subseq longer-string 0 shift-distance))) (cond ((eq ins-or-del :ins) (setf (moves partial) (list (cons :i excess))) (setf (cost partial) shift-distance) (setf (txt-pos partial) shift-distance) (setf (distance partial) (- (distance partial) shift-distance)) (setf (delta partial) (+ (delta partial) shift-distance)) partial) ((eq ins-or-del :del) (setf (moves partial) '((cons :d excess))) (setf (cost partial) shift-distance) (setf (pat-pos partial) shift-distance) (setf (delta partial) (- (delta partial) shift-distance)) partial) (t (error "~S is not a valid argument (:ins or :del)" ins-or-del))))) (defun initialize-search (pat txt) "trim sequences and find initial alignment, return trimmed-pat trimmed-txt initial-partial" (multiple-value-bind (trimmed-pat trimmed-txt) (trim-longest-tail pat txt) (let ((pat-align-point (align trimmed-pat trimmed-txt)) (txt-align-point (align trimmed-txt trimmed-pat)) (initial-partial (make-initial-partial trimmed-pat trimmed-txt))) (unless (or pat-align-point txt-align-point) (return-from initialize-search (values trimmed-pat trimmed-txt initial-partial))) (if pat-align-point (values trimmed-pat trimmed-txt (shift-partial initial-partial pat-align-point trimmed-txt :ins)) (values trimmed-pat trimmed-txt (shift-partial initial-partial txt-align-point trimmed-pat :del)))))) (defun lev (pat txt &key debug verbose) "compute the levenschtein or edit distance between two strings" (multiple-value-bind (trimmed-pat trimmed-txt initial-partial) (initialize-search pat txt) (let ((pq (make-instance 'heap :comparison #'compare))) ;; initialize the heap with an empty partial (shove pq initial-partial) (do ((best (yank pq) (yank pq)) (i 0 (+ i 1))) ((zerop (+ (distance best) (abs (delta best)))) best) (when debug (break)) (when verbose (format t "iteration: ~s~%best: ~s~%" i best)) (dolist (partial (extend best trimmed-pat trimmed-txt) nil) (shove pq partial)))))) (defun rfasta (fasta-file) "read a fasta file and returns the header and sequence as separate string values" (with-open-file (fasta-stream fasta-file :direction :input) (let ((header (read-line fasta-stream)) (sequence "")) (loop for line = (read-line fasta-stream nil 'eof) until (eq line 'eof) do (setf sequence (concatenate 'string sequence line))) (values header sequence)))) ;; read in some sequences for test data (defmacro snarfasta (header-var sequence-var filename) "defvar and assign variables to the results of a parsed fast file" `(progn (defvar ,header-var) (defvar ,sequence-var) (multiple-value-setq (,header-var ,sequence-var) (rfasta ,filename)))) (snarfasta ma-h ma-seq "./test_data/nc2mass.fasta") (snarfasta ca-h ca-seq "./test_data/ncov2ca.fasta") (snarfasta ref-h ref-seq "./test_data/ncov2ref.fasta") ;; for benchmarking (defun levenshtein-distance (str1 str2) "Calculates the Levenshtein distance between str1 and str2, returns an editing distance (int)." (let ((n (length str1)) (m (length str2))) ;; Check trivial cases (cond ((= 0 n) (return-from levenshtein-distance m)) ((= 0 m) (return-from levenshtein-distance n))) (let ((col (make-array (1+ m) :element-type 'integer)) (prev-col (make-array (1+ m) :element-type 'integer))) ;; We need to store only two columns---the current one that ;; is being built and the previous one (dotimes (i (1+ m)) (setf (svref prev-col i) i)) ;; Loop across all chars of each string (dotimes (i n) (setf (svref col 0) (1+ i)) (dotimes (j m) (setf (svref col (1+ j)) (min (1+ (svref col j)) (1+ (svref prev-col (1+ j))) (+ (svref prev-col j) (if (char-equal (schar str1 i) (schar str2 j)) 0 1))))) (rotatef col prev-col)) (svref prev-col m))))
15,392
Common Lisp
.lisp
340
39.920588
118
0.666511
toma63/levenschtein
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
f21ef170ada3ae2481910f1878f14c75a914079c87364a92b86b770e26046d7b
40,286
[ -1 ]
40,303
package.lisp
hu-dwim_hu_dwim_reader/test/package.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package :hu.dwim.def) (def package :hu.dwim.reader.test (:use :hu.dwim.common :hu.dwim.def :hu.dwim.stefil :hu.dwim.util) (:readtable-setup (hu.dwim.util:enable-standard-hu.dwim-syntaxes)))
345
Common Lisp
.lisp
12
25.25
69
0.640483
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
9d59701d23bce9145c21cc4ffd5a487e314ef78c042087a952a20619a8200a91
40,303
[ -1 ]
40,304
suite.lisp
hu-dwim_hu_dwim_reader/test/suite.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package :hu.dwim.reader.test) (def suite* (test :in root-suite))
192
Common Lisp
.lisp
7
26.142857
44
0.644809
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
6f058f9bd2eca18071ce66e9e17d7c7909b67763533ba18bed01f8e176873180
40,304
[ -1 ]
40,305
syntax-sugar.lisp
hu-dwim_hu_dwim_reader/integration/syntax-sugar.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT") (defclass source-boolean (source-object) ((value :accessor source-boolean-value :initarg :value))) (export 'source-boolean) (defun enable-sharp-boolean-syntax (&optional (readtable source-text:*source-readtable*)) (reader:set-dispatch-macro-character #\# #\t (lambda (&rest args) (declare (ignore args)) (building-source-object *stream* *start* 'source-boolean :value t)) readtable) (reader:set-dispatch-macro-character #\# #\f (lambda (&rest args) (declare (ignore args)) (building-source-object *stream* *start* 'source-boolean :value nil)) readtable) readtable) (defmethod %source-form ((instance source-boolean)) (source-boolean-value instance)) ;; TODO: depends on walker #+nil (defmethod describe-source-form ((form constant-form) (instance source-boolean)) (if (source-boolean-value instance) "boolean constant true" "boolean constant false"))
1,396
Common Lisp
.lisp
30
33.433333
110
0.554739
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
635d91a9efad1728d7ecc2b9e9bbc5580191872652b842b341df19adcba547d9
40,305
[ -1 ]
40,306
sbcl+swank.lisp
hu-dwim_hu_dwim_reader/integration/sbcl+swank.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT") (defun enable-shebang-syntax (&optional (readtable source-text:*source-readtable*)) (reader:set-dispatch-macro-character #\# #\! (lambda (s c n) (declare (ignore n)) (swank/sbcl::shebang-reader s c nil)) readtable))
558
Common Lisp
.lisp
12
31.833333
83
0.498162
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
36d50ad7140f09426c604b2d261e26f0a8da15b91e37df91a9b30755727095c8
40,306
[ -1 ]
40,307
walker.lisp
hu-dwim_hu_dwim_reader/integration/walker.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT") (eval-when (:compile-toplevel :load-toplevel :execute) (import '(metabang-bind:bind hu.dwim.def:def hu.dwim.def:generic hu.dwim.def:layered-method hu.dwim.def:layered-methods hu.dwim.def::-self- hu.dwim.walker:walk-form hu.dwim.walker::find-walker-handler hu.dwim.walker::coerce-to-form hu.dwim.walker:free-application-form hu.dwim.walker:lambda-function-form hu.dwim.walker:constant-form hu.dwim.walker:variable-reference-form hu.dwim.walker:lexical-variable-reference-form hu.dwim.walker:special-variable-reference-form hu.dwim.walker:free-variable-reference-form hu.dwim.walker:let-form hu.dwim.walker:let*-form hu.dwim.walker:if-form hu.dwim.walker::operator-of hu.dwim.walker::walk-form hu.dwim.walker::walker-macroexpand-1))) #+nil (def layer source-walker () ()) (def layered-method walk-form :around ((instance source-object) &key parent environment) (setf (source-object-form instance) (contextl:call-next-layered-method (source-object-form instance) :parent parent :environment environment))) (def layered-methods coerce-to-form (:method ((instance source-symbol)) (source-symbol-value instance)) (:method ((instance source-number)) (source-number-value instance)) (:method ((instance source-quote)) (list 'quote (source-object-subform instance))) (:method ((instance source-list)) (remove-if (lambda (element) (typep element 'source-whitespace)) (source-sequence-elements instance)))) (def layered-method walker-macroexpand-1 (form &optional env) (bind ((macro-name (coerce-to-form (first form)))) (if (member macro-name '(when unless)) ;; TODO: other macros interface to define such macro names (macroexpand-1 (cons macro-name (cdr form)) env) (bind ((ht (make-hash-table)) (coerced-form (labels ((recurse (form) (bind ((coerced-form (coerce-to-form form)) (result-form (if (consp coerced-form) (cons (recurse (car coerced-form)) (recurse (cdr coerced-form))) coerced-form))) (setf (gethash result-form ht) form) result-form))) (recurse form)))) (labels ((recurse (form) (bind ((original-form (gethash form ht))) (or original-form (if (consp form) (cons (recurse (car form)) (recurse (cdr form))) form))))) (bind (((:values expansion expanded?) (macroexpand-1 coerced-form env))) (values (recurse expansion) expanded?))))))) (def function source-walk (source) (source-form source) (walk-form source) source) (def class source-description () ((start :initarg :start :accessor start-of :type integer) (end :initarg :end :accessor end-of :type integer) (source :initarg :source :accessor source-of :type source-object) (description :initarg :description :accessor description-of :type string))) (def method print-object ((self source-description) stream) (if (= (start-of self) (end-of self)) (format stream "[~A] ~A" (start-of self) (description-of self)) (format stream "[~A..~A] ~A" (start-of self) (end-of self) (description-of self)))) (def class source-description-list () ((descriptions :initarg :descriptions :accessor descriptions-of :type list))) (def method print-object ((self source-description-list) stream) (pprint-logical-block (stream (descriptions-of self)) (loop :for index :from 0 :for description :in (descriptions-of self) :unless (zerop index) :do (princ " IN " stream) :do (princ description stream)))) (def generic source-describe-form (source form) (:method ((form null) source) (format nil "whitespace ~S" (source-object-text source))) (:method ((form free-application-form) source) (format nil "function call to ~A" (source-object-form (operator-of form)))) (:method ((form lambda-function-form) source) "lambda function definition") (:method ((form symbol) source) (format nil "symbol name ~S" form)) (:method ((form constant-form) (source source-quote)) (format nil "quoted constant ~S" (source-object-form (source-object-subform source)))) (:method ((form constant-form) (source source-symbol)) (format nil "symbol constant ~S" (source-symbol-value source))) (:method ((form constant-form) (source source-number)) (format nil "number constant ~S" (source-number-value source))) (:method ((form constant-form) (source source-string)) (format nil "string constant ~S" (source-string-value source))) (:method ((form constant-form) (source source-function)) (format nil "function constant ~S" (source-object-form (source-object-subform source)))) (:method ((form variable-reference-form) (source source-symbol)) (format nil "variable reference ~S" (source-symbol-value source))) (:method ((form lexical-variable-reference-form) (source source-symbol)) (format nil "lexical variable reference ~S" (source-symbol-value source))) (:method ((form special-variable-reference-form) (source source-symbol)) (format nil "special variable reference ~S" (source-symbol-value source))) (:method ((form free-variable-reference-form) (source source-symbol)) (format nil "free variable reference ~S" (source-symbol-value source))) (:method ((form let-form) (source source-list)) "parallel lexical variable binding") (:method ((form let*-form) (source source-list)) "sequential lexical variable binding") (:method ((form if-form) (source source-list)) "conditional branch") (:method ((form list) (source source-list)) ;; KLUDGE: for variable binding parameter list "parameter list")) (def function source-describe-position (source position) (bind ((result ())) (map-subforms (lambda (ast) (let* ((start (source-object-position ast)) (end (1- (+ start (length (source-object-text ast)))))) (when (<= start position end) (push (make-instance 'source-description :start start :end end :source ast :description (bind ((*package* (find-package :keyword))) (source-describe-form (source-object-form ast) ast))) result)))) source) (make-instance 'source-description-list :descriptions result))) (def function source-describe (source) (sort (remove-duplicates (loop :for position :from 0 :below (length (source-object-text source)) :collect (source-describe-position source position)) :test (lambda (description-list-1 description-list-2) (every (lambda (description-1 description-2) (eq (source-of description-1) (source-of description-2))) (descriptions-of description-list-1) (descriptions-of description-list-2)))) (lambda (description-list-1 description-list-2) (< (start-of (first (descriptions-of description-list-1))) (start-of (first (descriptions-of description-list-2))))))) (def method source-parent-relative-indent ((parent-form if-form) (parent-source source-list) form source form-index) (ecase form-index (0 1) (1 1) (2 4) (3 4))) (def method source-parent-relative-indent ((parent-form free-application-form) (parent-source source-list) form source form-index) (+ 2 (length (symbol-name (source-symbol-value (operator-of parent-form)))))) (def method source-insert-newline ((parent-form if-form) (parent-source source-list) form source form-index) (when (<= 2 form-index) t)) (def method source-insert-newline ((parent-form let-form) (parent-source source-list) form source form-index) (unless (= form-index 1) t)) ;; KLUDGE: for variable binding parameter list (def method source-insert-newline ((parent-form list) (parent-source source-list) (form list) (source source-list) form-index) t) (def method source-insert-newline ((parent-form free-application-form) (parent-source source-list) (form constant-form) (source source-symbol) form-index) (when (and (keywordp (source-symbol-value source)) (eq (source-object-form (operator-of parent-form)) 'make-instance)) t))
9,339
Common Lisp
.lisp
174
42.551724
154
0.615182
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
bdbb6cd0d12a33be69b73a70dcd3d7de0161a1c0bea0c6f82c8b3f59a0b4196d
40,307
[ -1 ]
40,308
sbcl.lisp
hu-dwim_hu_dwim_reader/integration/sbcl.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT") (eval-when (:compile-toplevel :load-toplevel :execute) (defun if-symbol-exists (package name) "Can be used to conditionalize at read-time like this: #+#.(hu.dwim.util:if-symbol-exists \"PKG\" \"FOO\")(pkg::foo ...)" (if (and (find-package (string package)) (find-symbol (string name) (string package))) '(:and) '(:or)))) (eval-when (:compile-toplevel :load-toplevel :execute) (defun sbcl-version>= (&rest subversions) (declare (ignorable subversions)) (or #+#.(source-text::if-symbol-exists '#:sb-ext '#:assert-version->=) (values (ignore-errors (apply #'sb-ext:assert-version->= subversions) '(:and))) '(:or)))) ;; FTR, the incompatible change that was released with 1.2.2: ;; https://github.com/sbcl/sbcl/commit/d7265bc05d7c3ba83194cb80b3371a54d3c136e4 (defmethod %source-form ((instance source-backquote)) ;; damn, a simple readtime conditional is painful without FEATURE-COND (from hu.dwim.syntax-sugar) #+#.(source-text::sbcl-version>= 1 2 2) (cons 'sb-int:quasiquote (%source-form (source-object-subform instance))) #-#.(source-text::sbcl-version>= 1 2 2) (cons 'sb-impl::backq-list (mapcar (lambda (form) (if (and (consp form) (eq 'sb-impl::backq-comma (first form))) (cdr form) (list 'quote form))) (%source-form (source-object-subform instance))))) (defmethod %source-form ((instance source-unquote)) #+#.(source-text::sbcl-version>= 1 2 2) (sb-int:unquote (%source-form (source-object-subform instance))) #-#.(source-text::sbcl-version>= 1 2 2) (cons 'sb-impl::backq-comma (%source-form (source-object-subform instance))))
2,009
Common Lisp
.lisp
37
45.243243
125
0.609558
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
8a20af46b4beece2d1c330071a6397a669c6a6d2f5970f2b69f16ab51a4eb65e
40,308
[ -1 ]
40,309
package.lisp
hu-dwim_hu_dwim_reader/documentation/package.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package :hu.dwim.def) (def package :hu.dwim.reader.documentation (:use :hu.dwim.asdf :hu.dwim.common :hu.dwim.def :hu.dwim.defclass-star :hu.dwim.presentation :hu.dwim.syntax-sugar :hu.dwim.util) (:readtable-setup (setup-readtable/same-as-package :hu.dwim.presentation)))
451
Common Lisp
.lisp
15
25.466667
77
0.642857
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
7748cff618fc67d92227034bae70b92a152182031e1dbaeb4651302a7e24add3
40,309
[ -1 ]
40,310
reader.lisp
hu-dwim_hu_dwim_reader/documentation/reader.lisp
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (in-package :hu.dwim.reader.documentation) (def project :hu.dwim.reader) (def book user-guide (:title "User guide") (chapter (:title "Introduction") (paragraph () "TODO")) (chapter (:title "Supported Common Lisp Implementations") (paragraph () "SBCL")) (chapter (:title "Supported Operating Systems") (paragraph () "Linux")) (chapter (:title "Tutorial") (paragraph () "TODO")))
550
Common Lisp
.lisp
20
23.95
59
0.637571
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
2fa5772ad340260e58194fc9a6595255a5fa67e03a46e2247abbb9e7c19747fe
40,310
[ -1 ]
40,311
source-form.lisp
hu-dwim_hu_dwim_reader/source/source-form.lisp
;;;;************************************************************************** ;;;;FILE: source-form.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports functions to parse and manipulate ;;;; Common Lisp sources as lisp forms (such as in macros). ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2006-05-25 <PJB> Created ;;;;BUGS ;;;;LEGAL ;;;; GPL ;;;; ;;;; Copyright Pascal Bourguignon 2006 - 2007 ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU General Public License ;;;; as published by the Free Software Foundation; either version ;;;; 2 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be ;;;; useful, but WITHOUT ANY WARRANTY; without even the implied ;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;;;; PURPOSE. See the GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public ;;;; License along with this program; if not, write to the Free ;;;; Software Foundation, Inc., 59 Temple Place, Suite 330, ;;;; Boston, MA 02111-1307 USA ;;;;************************************************************************** (in-package "COMMON-LISP-USER") (defpackage "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-FORM" (:nicknames "SOURCE-FORM") (:use "COMMON-LISP") (:export ;; Parameter Classes: "PARAMETER" "ENVIRONMENT-PARAMETER" "WHOLE-PARAMETER" "REST-PARAMETER" "BODY-PARAMETER" "SPECIALIZED-PARAMETER" "AUXILIARY-PARAMETER" "OPTIONAL-PARAMETER" "GENERIC-OPTIONAL-PARAMETER" "KEYWORD-PARAMETER" "GENERIC-KEYWORD-PARAMETER" ;; Parameter Methods: "PARAMETER-NAME" "PARAMETER-LABEL" #|"PARAMETER-HELP-LABEL"|# "PARAMETER-LAMBDA-LIST-KEYWORD" "PARAMETER-SPECIFIER" "PARAMETER-INDICATOR" "PARAMETER-INDICATOR-P" "PARAMETER-INITFORM" "PARAMETER-INITFORM-P" "PARAMETER-KEYWORD" "PARAMETER-KEYWORD-P" "ENSURE-PARAMETER-KEYWORD" "PARAMETER-SPECIALIZER" "PARAMETER-SPECIALIZER-P" ;; Lambda-List Classes: "LAMBDA-LIST" "ORDINARY-LAMBDA-LIST" "BOA-LAMBDA-LIST" "SPECIALIZED-LAMBDA-LIST" "MODIFY-MACRO-LAMBDA-LIST" "GENERIC-LAMBDA-LIST" "MACRO-LAMBDA-LIST" "TYPE-LAMBDA-LIST" "DESTRUCTURING-LAMBDA-LIST" "SETF-LAMBDA-LIST" "METHOD-COMBINATION-LAMBDA-LIST" ;; Lambda-List Methods: "ORIGINAL-LAMBDA-LIST" #|"LAMBDA-LIST-PARAMETERS"|# "LAMBDA-LIST-MANDATORY-PARAMETERS" "LAMBDA-LIST-OPTIONAL-PARAMETERS" "LAMBDA-LIST-REST-PARAMETER" "LAMBDA-LIST-ALLOW-OTHER-KEYS-P" "LAMBDA-LIST-KEY-P" "LAMBDA-LIST-KEYWORD-PARAMETERS" "LAMBDA-LIST-ENVIRONMENT-PARAMETER" "LAMBDA-LIST-AUXILIARY-PARAMETERS" "LAMBDA-LIST-WHOLE-PARAMETER" "LAMBDA-LIST-ENVIRONMENT-PARAMETER" "LAMBDA-LIST-BODY-PARAMETER" "LAMBDA-LIST-KIND" "LAMBDA-LIST-ALLOWED-KEYWORDS" "LAMBDA-LIST-MANDATORY-PARAMETER-COUNT" "LAMBDA-LIST-OPTIONAL-PARAMETER-COUNT" "LAMBDA-LIST-REST-P" "LAMBDA-LIST-MANDATORY-PARAMETERS-P" "LAMBDA-LIST-OPTIONAL-PARAMETERS-P" "LAMBDA-LIST-REST-PARAMETER-P" "LAMBDA-LIST-AUXILIARY-PARAMETERS-P" "LAMBDA-LIST-WHOLE-PARAMETER-P" "LAMBDA-LIST-BODY-PARAMETER-P" "LAMBDA-LIST-ENVIRONMENT-PARAMETER-P" ;; Parsing lambda-lists: "PARSE-LAMBDA-LIST" "PARSE-ORIGINAL-LAMBDA-LIST" ;; Generating information from a lambda-list instance: "MAKE-HELP" "MAKE-ARGUMENT-LIST" "MAKE-ARGUMENT-LIST-FORM" "MAKE-LAMBDA-LIST" ;; Parsing sources: "EXTRACT-DOCUMENTATION" "EXTRACT-DECLARATIONS" "EXTRACT-BODY" "DECLARATIONS-HASH-TABLE" "EXTRACT-METHOD-QUALIFIERS" "EXTRACT-METHOD-LAMBDA-LIST" "EXTRACT-METHOD-DDL" "EXTRACT-METHOD-DOCUMENTATION" "EXTRACT-METHOD-DECLARATIONS" "EXTRACT-METHOD-BODY" ;; "DEFUN""DEFGENERIC""DEFMETHOD" ;; *CALL-STACK*" ;; not yet ) (:shadow "READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*") (:documentation " This package exports functions to parse and manipulate Common Lisp sources as lisp forms (such as in macros). Copyright Pascal J. Bourguignon 2003 - 2007 This package is provided under the GNU General Public License. See the source file for details.")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-FORM") ;; Not prudent: ;; #+clisp (eval-when (:compile-toplevel :load-toplevel :execute) ;; (import '(system::splice system::unquote system::backquote))) ;;;---------------------------------------- ;;; Parameter specifications in lambda-lists ;;;---------------------------------------- ;; Syntax of parameter specifications: ;; ;; name ;; | (name [ specializer ]) ; for specialized lambda-lists ;; | (name [ init-form [ indicator ]]) ; for &key &optional ;; | ((name keyword) [ init-form [ indicator ]]) ; for &key (defmacro define-default-generic (name class default-value) `(defgeneric ,name (self) (:method ((self ,class)) (declare (ignore self)) ,default-value))) ;;;-------------------- (defgeneric parameter-name-p (self)) (defgeneric parse-parameter (self form)) (defgeneric parse-parameter-name (self form)) (defgeneric ensure-parameter-keyword (self)) (defgeneric lambda-list-mandatory-parameter-count (self)) (defgeneric lambda-list-optional-parameter-count (self)) (defgeneric parse-optvars (self current slot lambda-list-keyword class)) (defgeneric auxvars (self current)) (defgeneric optvars (self current)) (defgeneric goptvars (self current)) (defgeneric parse-keyvars (self current class)) (defgeneric keyvars (self current)) (defgeneric gkeyvars (self current)) (defgeneric parse-reqvars (self current class)) (defgeneric reqvars (self current)) (defgeneric sreqvars (self current)) (defgeneric preqvars (self current)) (defgeneric parse-original-lambda-list (self)) (defgeneric make-help (self)) (defgeneric make-argument-list (self)) (defgeneric make-lambda-list (self)) ;;;-------------------- (defclass parameter () ((name :accessor parameter-name :initarg :name :type symbol :documentation "The name of the parameter.")) (:documentation "A generic parameter.")) (defmethod parameter-name-p ((self parameter)) (slot-boundp self 'name)) (define-default-generic parameter-indicator parameter nil) (define-default-generic parameter-indicator-p parameter nil) (define-default-generic parameter-initform parameter nil) (define-default-generic parameter-initform-p parameter nil) (define-default-generic parameter-keyword parameter nil) (define-default-generic parameter-keyword-p parameter nil) (define-default-generic parameter-specializer parameter nil) (define-default-generic parameter-specializer-p parameter nil) (defmethod parse-parameter-name ((self parameter) form) (if (symbolp form) (setf (parameter-name self) form) (error "Invalid parameter name: ~S" form)) self) (defmethod parse-parameter ((self parameter) form) (parse-parameter-name self form)) (defmethod print-object ((self parameter) stream) (print-unreadable-object (self stream :identity t) (format stream "~A ~S" (parameter-lambda-list-keyword self) (parameter-specifier self)))) ;;;-------------------- (defclass environment-parameter (parameter) () (:documentation "An &ENVIRONMENT parameter.")) (defclass whole-parameter (parameter) () (:documentation "A &WHOLE parameter.")) (defclass rest-parameter (parameter) () (:documentation "A &REST parameter.")) (defclass body-parameter (parameter) () (:documentation "A &BODY parameter.")) ;;;-------------------- (defclass specialized-parameter (parameter) ((specializer :accessor parameter-specializer :initarg :specializer :type (or symbol cons) :documentation " A specializer can be either NIL (no specializer),p a symbol denoting a class, or a cons (eql object) denoting an EQL specializer.")) (:documentation "A specialized parameter.")) (defmethod parameter-specializer-p ((self specialized-parameter)) (slot-boundp self 'specializer)) (defmethod parse-parameter ((self specialized-parameter) form) (etypecase form (symbol (call-next-method)) (cons (call-next-method self (first form)) (when (cdr form) (setf (parameter-specializer self) (second form)) (when (cddr form) (error "~A specification must be a ~ list of two elements at most, not ~S" (parameter-label self) form))))) self) ;;;-------------------- (defclass parameter-with-initform () ((initform :accessor parameter-initform :initarg :initform :documentation "The initial form for the parameter.")) (:documentation "A mixin for a parameter that may have an initform.")) (defmethod parameter-initform-p ((self parameter-with-initform)) (slot-boundp self 'initform)) (defmethod parse-parameter ((self parameter-with-initform) form) (etypecase form (symbol (call-next-method)) (cons (call-next-method self (first form)) (when (cdr form) (setf (parameter-initform self) (second form))))) self) ;;;-------------------- (defclass auxiliary-parameter (parameter-with-initform parameter) ;; The order of the superclasses is important ;; to find the methods in the right order! () (:documentation "An auxiliary parameter.")) (defmethod parse-parameter ((self auxiliary-parameter) form) (etypecase form (symbol (call-next-method)) (cons (call-next-method) (when (cddr form) (error "~A specification must be a ~ list of two elements at most, not ~S" (parameter-label self) form)))) self) ;;;-------------------- (defclass optional-parameter (parameter-with-initform parameter) ;; The order of the superclasses is important ;; to find the methods in the right order! ((indicator :accessor parameter-indicator :initarg :indicator :type symbol :documentation "NIL, or the name of the indicator parameter.")) (:documentation "An optional parameter. Note that while auxiliary-parameter and optional-parameter have the same initform attribute, an optional-parameter is a different kind from an auxiliary-parameter, semantically.")) (defmethod parameter-initform-p ((self optional-parameter)) (slot-boundp self 'initform)) (defmethod parameter-indicator-p ((self optional-parameter)) (slot-boundp self 'indicator)) (defmethod parse-parameter ((self optional-parameter) form) (etypecase form (symbol (call-next-method)) (cons (call-next-method) (when (cddr form) (setf (parameter-indicator self) (third form)) (when (cdddr form) (error "~A specification must be a ~ list of three elements at most, not ~S" (parameter-label self) form))))) self) ;;;-------------------- (defclass generic-optional-parameter (parameter) () (:documentation "An optional parameter in generic lambda-lists.")) (defmethod parse-parameter ((self generic-optional-parameter) form) (etypecase form (symbol (call-next-method)) (cons (call-next-method self (first form)) (when (cdr form) (error "~A specification must be a ~ list of one element at most, not ~S" (parameter-label self) form))))) ;;;-------------------- (defclass parameter-with-keyword () ((keyword :accessor parameter-keyword :initarg :keyword :type symbol :documentation "NIL, or the keyword specified for the parameter.")) (:documentation "A mixin for keyword parameters.")) (defmethod parameter-keyword-p ((self parameter-with-keyword)) (slot-boundp self 'keyword)) (defmethod parse-parameter-name ((self parameter-with-keyword) form) (etypecase form (symbol (call-next-method)) (cons (if (= 2 (length form)) (progn (call-next-method self (second form)) (setf (parameter-keyword self) (first form))) (error "~A specification must be a ~ list of two elements, not ~S" (parameter-label self) form)))) self) (defmethod ensure-parameter-keyword ((self parameter-with-keyword)) (if (parameter-keyword-p self) (parameter-keyword self) (INTERN (STRING (parameter-name self)) "KEYWORD"))) ;;;-------------------- (defclass keyword-parameter (parameter-with-keyword optional-parameter) ;; The order of the superclasses is important ;; to find the methods in the right order! () (:documentation "A keyword parameter.")) ;;;-------------------- (defclass generic-keyword-parameter (parameter-with-keyword generic-optional-parameter) ;; The order of the superclasses is important ;; to find the methods in the right order! () (:documentation "A generic keyword parameter.")) ;;;-------------------- (defgeneric parameter-label (parameter) (:method ((self parameter)) "A mandatory parameter") (:method ((self environment-parameter)) "An environment parameter") (:method ((self whole-parameter)) "A whole parameter") (:method ((self rest-parameter)) "A rest parameter") (:method ((self body-parameter)) "A body parameter") (:method ((self specialized-parameter)) "A specialized parameter") (:method ((self auxiliary-parameter)) "An auxiliary parameter") (:method ((self optional-parameter)) "An optional parameter") (:method ((self generic-optional-parameter)) "A generic optional parameter") (:method ((self keyword-parameter)) "A keyword parameter") (:method ((self generic-keyword-parameter)) "A generic keyword parameter")) (defgeneric parameter-lambda-list-keyword (parameter) (:method ((self parameter)) '&mandatory) (:method ((self environment-parameter)) '&environment) (:method ((self whole-parameter)) '&whole) (:method ((self rest-parameter)) '&rest) (:method ((self body-parameter)) '&body) (:method ((self specialized-parameter)) '&specialized) (:method ((self auxiliary-parameter)) '&aux) (:method ((self optional-parameter)) '&optional) (:method ((self generic-optional-parameter)) '&generic-optional) (:method ((self keyword-parameter)) '&key) (:method ((self generic-keyword-parameter)) '&generic-key)) (defgeneric parameter-specifier (parameter) (:method ((self parameter)) (parameter-name self)) (:method ((self specialized-parameter)) (cons (parameter-name self) (when (parameter-specializer-p self) (list (parameter-specializer self))))) (:method ((self auxiliary-parameter)) (if (parameter-initform-p self) (list (parameter-name self) (parameter-initform self)) (parameter-name self))) (:method ((self parameter-with-initform)) (if (parameter-initform-p self) (cons (parameter-name self) (cons (parameter-initform self) (when (parameter-indicator-p self) (list (parameter-indicator self))))) (parameter-name self))) (:method ((self parameter-with-keyword)) (if (or (parameter-keyword-p self) (parameter-initform-p self)) (cons (if (parameter-keyword-p self) (list (parameter-keyword self) (parameter-name self)) (parameter-name self)) (when (parameter-initform-p self) (cons (parameter-initform self) (when (parameter-indicator-p self) (list (parameter-indicator self)))))) (parameter-name self))) (:method ((self generic-keyword-parameter)) (if (parameter-keyword-p self) (list (list (parameter-keyword self) (parameter-name self))) (parameter-name self)))) ;;;-------------------- (defclass or-ll () ((mandatories :accessor lambda-list-mandatory-parameters :initarg :mandatory-parameters :initform '() :type list) (optionals :accessor lambda-list-optional-parameters :initarg :optional-parameters :initform '() :type list) (rest :accessor lambda-list-rest-parameter :initarg :rest-parameter :type (or null rest-parameter))) (:documentation "This class and its subclasses are mixin declaring formally the attributes for the various lambda-list classes. Semantically, some constraints may be different from one lambda-list to the other.")) (defgeneric lambda-list-mandatory-parameters-p (self) (:method ((self or-ll)) (not (not (lambda-list-mandatory-parameters self)))) (:method ((self t)) nil)) (defgeneric lambda-list-optional-parameters-p (self) (:method ((self or-ll)) (not (not (lambda-list-optional-parameters self)))) (:method ((self t)) nil)) (defgeneric lambda-list-rest-parameter-p (self) (:method ((self or-ll)) (slot-boundp self 'rest)) (:method ((self t)) nil)) (define-default-generic lambda-list-allow-other-keys-p or-ll nil) (define-default-generic lambda-list-key-p or-ll nil) (define-default-generic lambda-list-keyword-parameters or-ll nil) (define-default-generic lambda-list-environment-parameter or-ll nil) (define-default-generic lambda-list-auxiliary-parameters or-ll nil) (define-default-generic lambda-list-whole-parameter or-ll nil) (define-default-generic lambda-list-body-parameter or-ll nil) (defclass orak-ll (or-ll) ((allow-other-keys-p :accessor lambda-list-allow-other-keys-p :initarg :allow-other-keys-p :initform nil :type boolean :documentation "Whether &ALLOW-OTHER-KEYS is present.") (key-p :accessor lambda-list-key-p :initarg :key-p :initform nil :type boolean :documentation "Whether &KEY is present.") ;; We can have &KEY &ALLOW-OTHER-KEYS without any keyword. (keys :accessor lambda-list-keyword-parameters :initarg :keyword-parameters :initform '() :type list))) (defgeneric lambda-list-keyword-parameters-p (self) (:method ((self or-ll)) (not (not (lambda-list-keyword-parameters self))))) (defclass orake-ll (orak-ll) ((environment :accessor lambda-list-environment-parameter :initarg :environment-parameter :type environment-parameter))) (defclass oraka-ll (orak-ll) ((aux :accessor lambda-list-auxiliary-parameters :initarg :auxiliary-parameters :initform '() :type list))) (defclass orakawb-ll (oraka-ll) ((whole :accessor lambda-list-whole-parameter :initarg :whole-parameter :type whole-parameter) (body :accessor lambda-list-body-parameter :initarg :body-parameter :type body-parameter))) (defclass orakawbe-ll (oraka-ll) ((environment :accessor lambda-list-environment-parameter :initarg :environment-parameter :type environment-parameter))) (defgeneric lambda-list-auxiliary-parameters-p (self) (:method ((self oraka-ll)) (not (not (lambda-list-auxiliary-parameters self)))) (:method ((self t)) nil)) (defgeneric lambda-list-whole-parameter-p (self) (:method ((self orakawb-ll)) (slot-boundp self 'whole)) (:method ((self t)) nil)) (defgeneric lambda-list-body-parameter-p (self) (:method ((self orakawb-ll)) (slot-boundp self 'body)) (:method ((self t)) nil)) (defgeneric lambda-list-environment-parameter-p (self) (:method ((self orakawbe-ll)) (slot-boundp self 'environment)) (:method ((self orake-ll)) (slot-boundp self 'environment)) (:method ((self t)) nil)) ;;;---------------------------------------- (defclass lambda-list () ((original :accessor original-lambda-list :initarg :lambda-list :type list) (parameters :accessor lambda-list-parameters :initarg :parameters :type list :documentation "An ordered list of the parameters or destructuring-lambda-list instances.")) (:documentation "An abstract lambda-list.")) (defclass ordinary-lambda-list (lambda-list oraka-ll) ()) (defclass boa-lambda-list (lambda-list oraka-ll) ()) (defclass specialized-lambda-list (lambda-list oraka-ll) ()) (defclass modify-macro-lambda-list (lambda-list or-ll) ()) (defclass generic-lambda-list (lambda-list orak-ll) ()) (defclass macro-lambda-list (lambda-list orakawbe-ll) ()) (defclass type-lambda-list (lambda-list orakawbe-ll) ()) (defclass destructuring-lambda-list (lambda-list orakawb-ll) ()) (defclass setf-lambda-list (lambda-list orake-ll) ()) (defclass method-combination-lambda-list (lambda-list orakaw-ll) ()) (defgeneric lambda-list-kind (lambda-list) (:method ((self ordinary-lambda-list)) :ordinary) (:method ((self boa-lambda-list)) :boa) (:method ((self specialized-lambda-list)) :specialized) (:method ((self modify-macro-lambda-list)) :modify-macro) (:method ((self generic-lambda-list)) :generic) (:method ((self macro-lambda-list)) :macro) (:method ((self type-lambda-list)) :type) (:method ((self destructuring-lambda-list)) :destructuring) (:method ((self setf-lambda-list)) :setf) (:method ((self method-combination-lambda-list)) :method-combination)) (defgeneric lambda-list-allowed-keywords (lambda-list) (:method ((self ordinary-lambda-list)) '(&optional &rest &allow-other-keys &key &aux)) (:method ((self boa-lambda-list)) '(&optional &rest &allow-other-keys &key &aux)) (:method ((self specialized-lambda-list)) '(&optional &rest &allow-other-keys &key &aux)) (:method ((self modify-macro-lambda-list)) '(&optional &rest)) (:method ((self generic-lambda-list)) '(&optional &rest &allow-other-keys &key)) (:method ((self macro-lambda-list)) '(&optional &rest &allow-other-keys &key &aux &whole &body &environment)) (:method ((self type-lambda-list)) '(&optional &rest &allow-other-keys &key &aux &whole &body &environment)) (:method ((self destructuring-lambda-list)) '(&optional &rest &allow-other-keys &key &aux &whole &body)) (:method ((self setf-lambda-list)) '(&optional &rest &allow-other-keys &key &environment)) (:method ((self method-combination-lambda-list)) '(&optional &rest &allow-other-keys &key &aux &whole))) (defmethod lambda-list-mandatory-parameter-count ((self or-ll)) "RETURN: The number of mandatory parameters." (length (lambda-list-mandatory-parameters self))) (defmethod lambda-list-optional-parameter-count ((self or-ll)) "RETURN: The number of optional parameters." (length (lambda-list-mandatory-parameters self))) (defgeneric lambda-list-rest-p (self) (:documentation "RETURN: Whether &REST or &BODY parameters are present.") (:method ((self or-ll)) (lambda-list-rest-parameter-p self)) (:method ((self orakawb-ll)) (or (lambda-list-rest-parameter-p self) (lambda-list-body-parameter-p self)))) ;; auxvars ::= [&aux {var | (var [init-form])}*] ;; optvars ::= [&optional {var | (var [init-form [supplied-p-parameter]])}*] ;; goptvars ::= [&optional {var | (var)}*] (defmethod parse-optvars ((self or-ll) current slot lambda-list-keyword class) " DO: Parses optional parameters. RETURN: The remaining tokens. " (when (eq (car current) lambda-list-keyword) (pop current) (setf (slot-value self slot) (loop :while (and current (not (member (car current) lambda-list-keywords))) :collect (parse-parameter (make-instance class) (pop current))))) current) (defmethod auxvars ((self or-ll) current) (parse-optvars self current 'aux '&aux 'auxiliary-parameter)) (defmethod optvars ((self or-ll) current) (parse-optvars self current 'optionals '&optional 'optional-parameter)) (defmethod goptvars ((self or-ll) current) (parse-optvars self current 'optionals '&optional 'generic-optional-parameter)) ;; keyvars ::= [&key {var | ({var | (keyword-name var)} [init-form [supplied-p-parameter]])}* [&allow-other-keys]] ;; gkeyvars ::= [&key {var | ({var | (keyword-name var)})}* [&allow-other-keys]]) (defmethod parse-keyvars ((self orak-ll) current class) " DO: Parses keywork parameters. RETURN: The remaining tokens. " (when (eq '&key (car current)) (pop current) (setf (lambda-list-key-p self) t (lambda-list-keyword-parameters self) (loop :while (and current (not (member (car current) lambda-list-keywords))) :collect (parse-parameter (make-instance class) (pop current))) (lambda-list-allow-other-keys-p self) (and (eq '&allow-other-keys (car current)) (pop current) t))) current) (defmethod keyvars ((self orak-ll) current) (parse-keyvars self current 'keyword-parameter)) (defmethod gkeyvars ((self orak-ll) current) (parse-keyvars self current 'generic-keyword-parameter)) ;; reqvars ::= var* ;; sreqvars ::= {var | (var [specializer])}* ;; preqvars ::= {var | destructuring-lambda-list}* (defmethod parse-reqvars ((self or-ll) current class) " DO: Parses required parameters. RETURN: (values list-of-parameters following) " (setf (lambda-list-mandatory-parameters self) (loop :while (and current (not (member (car current) lambda-list-keywords))) :collect (parse-parameter (make-instance class) (pop current)))) current) (defmethod reqvars ((self or-ll) current) (parse-reqvars self current 'parameter)) (defmethod sreqvars ((self or-ll) current) (parse-reqvars self current 'specialized-parameter)) (defmethod preqvars ((self or-ll) current) " DO: Parses required parameters or patterns. RETURN: (values list-of-parameters following) " (setf (lambda-list-mandatory-parameters self) (loop :while (and current (not (member (car current) lambda-list-keywords))) :collect (if (consp (car current)) (parse-original-lambda-list (make-instance 'destructuring-lambda-list :lambda-list (pop current))) (parse-parameter (make-instance 'specialized-parameter) (pop current))))) current) ;; bodyvar ::= [{&rest | &body} var] ;; restvar ::= [&rest var] ;; wholevar ::= [&whole var] ;; envvar ::= [&environment var] (defun bodyvar (self current) " RETURN: (values parameter following) TODO: See what happens for (&BODY) or (&REST). " (flet ((check-duplicate (lambda-list-keyword) (when (lambda-list-rest-p self) (error "~:[&BODY~;&REST~] parameter already given before ~A in ~S" (lambda-list-rest-parameter-p self) lambda-list-keyword (original-lambda-list self))))) (case (car current) ((&rest) (check-duplicate (pop current)) (setf (lambda-list-rest-parameter self) (parse-parameter (make-instance 'rest-parameter) (pop current)))) ((&body) (check-duplicate (pop current)) (pop current) (setf (lambda-list-body-parameter self) (parse-parameter (make-instance 'body-parameter) (pop current))))) current)) (defun parse-var (self current slot lambda-list-keyword class ) " RETURN: (values parameter following) " (when (eq (car current) lambda-list-keyword) (pop current) (when (slot-boundp self slot) (error "~A parameter duplicated in ~S" lambda-list-keyword (original-lambda-list self))) (setf (slot-value self slot) (parse-parameter (make-instance class) (pop current)))) current) (defun restvar (self current) (parse-var self current 'rest '&rest 'rest-parameter)) (defun wholevar (self current) (parse-var self current 'whole '&whole 'whole-parameter)) (defun envvar (self current) (parse-var self current 'environment '&environment 'environment-parameter)) ;; macro-lambda-list ::= (wholevar envvar preqvars envvar optvars envvar ;; bodyvar envvar keyvars envvar auxvars envvar) ;; | (wholevar envvar preqvars envvar optvars envvar . var) ;; ;; destructuring-lambda-list ::= (wholevar preqvars optvars bodyvar keyvars auxvars) ;; | (wholevar preqvars optvars . var) ;; ;; type-lambda-list ::= macro-lambda-list ;; ;; ;; ordinary-lambda-list ::= (reqvars optvars restvar keyvars auxvars) ;; boa-lambda-list ::= ordinary-lambda-list ;; specialized-lambda-list ::= (sreqvars optvars restvar keyvars auxvars) ;; generic-lambda-list ::= (reqvars goptvars restvar gkeyvars) ;; setf-lambda-list ::= (reqvars optvars restvar keyvars envvar) ;; modify-macro-lambda-list ::= (reqvars optvars restvar) ;; method-combination-lambda-list ::= (wholevar reqvars optvars restvar keyvars auxvars) (defun parse-rest (self current syntax) (if (listp current) (dolist (fun syntax current) (setf current (funcall fun self current))) (restvar self (list '&rest current)))) (defun destructuring-rest (self current) (parse-rest self current '(bodyvar keyvars auxvars))) (defun macro-rest (self current) (parse-rest self current '(bodyvar envvar keyvars envvar auxvars envvar))) (defgeneric lambda-list-syntax (self) (:method ((self ordinary-lambda-list)) '(reqvars optvars restvar keyvars auxvars)) (:method ((self boa-lambda-list)) '(reqvars optvars restvar keyvars auxvars)) (:method ((self specialized-lambda-list)) '(sreqvars optvars restvar keyvars auxvars)) (:method ((self generic-lambda-list)) '(reqvars goptvars restvar gkeyvars)) (:method ((self setf-lambda-list)) '(reqvars optvars restvar keyvars envvar)) (:method ((self modify-macro-lambda-list)) '(reqvars optvars restvar)) (:method ((self method-combination-lambda-list)) '(wholevar reqvars optvars restvar keyvars auxvars)) (:method ((self macro-lambda-list)) '(wholevar envvar preqvars envvar optvars envvar macro-rest)) (:method ((self type-lambda-list)) '(wholevar envvar preqvars envvar optvars envvar macro-rest)) (:method ((self destructuring-lambda-list)) '(wholevar preqvars optvars destructuring-rest))) (defmethod parse-original-lambda-list ((self lambda-list)) (let ((current (original-lambda-list self))) (dolist (fun (lambda-list-syntax self)) (setf current (funcall fun self current))) (when current (error "Syntax error in ~(~A~) at: ~S~%in ~S" (class-name (class-of self)) current (original-lambda-list self))) self)) (defun parse-lambda-list (lambda-list &optional (kind :ordinary)) " DO: Parse a lambda-list of the specified kind. KIND: (MEMBER :ORDINARY :BOA :SPECIALIZED :MODIFY-MACRO :GENERIC :MACRO :TYPE :DESTRUCTURING :SETF :METHOD-COMBINATION) RETURN: A lambda-list instance. " (parse-original-lambda-list (make-instance (or (cdr (assoc kind '((:ordinary . ordinary-lambda-list) (:boa . boa-lambda-list) (:specialized . specialized-lambda-list) (:modify-macro . modify-macro-lambda-list) (:generic . generic-lambda-list) (:macro . macro-lambda-list) (:type . type-lambda-list) (:destructuring . destructuring-lambda-list) (:setf . setf-lambda-list) (:method-combination . method-combination-lambda-list)))) (error "Invalid lambda-list kind ~S" kind)) :lambda-list lambda-list))) ;;------------------------------------------------------------------------ (defgeneric parameter-help-label (self) (:method ((self parameter)) (format nil "~A" (parameter-name self))) (:method ((self optional-parameter)) (format nil "[~A]" (parameter-name self))) (:method ((self rest-parameter)) (format nil "~A..." (parameter-name self))) (:method ((self body-parameter)) (format nil "~A..." (parameter-name self))) (:method ((self keyword-parameter)) (format nil "~A" (ensure-parameter-keyword self)))) (defmethod make-help ((self lambda-list)) " RETURN: A list describing the lambda-list for the user. Each item is a cons: (lambda-list-keyword . description) where - the lambda-list-keyword is either :mandatory, :optional, :rest, :body, :key, or :allow-other-keys. - the description is a string indicating the name of the parameter, and whether it's optional '[n]' or takes several arguments 'n...'. " (append ;; mandatory: (mapcar (lambda (par) (cons :mandatory (parameter-help-label par))) (lambda-list-mandatory-parameters self)) ;; optional: (mapcar (lambda (par) (cons :optional (parameter-help-label par))) (lambda-list-optional-parameters self)) (when (lambda-list-rest-parameter-p self) (list (cons :rest (parameter-help-label (lambda-list-rest-parameter self))))) (when (lambda-list-body-parameter-p self) (list (cons :body (parameter-help-label (lambda-list-body-parameter self))))) ;; keywords: (mapcar (lambda (par) (cons :key (parameter-help-label par))) (lambda-list-keyword-parameters self)) (when (lambda-list-allow-other-keys-p self) (list (cons :allow-other-keys "(other keys allowed)"))))) (defmethod make-argument-list ((self lambda-list)) " RETURN: A list of arguments taken from the parameters usable with apply to call a function with the same lambda-list. " (let ((rest (lambda-list-rest-p self))) (append (mapcar (function parameter-name) (lambda-list-mandatory-parameters self)) (mapcar (function parameter-name) (lambda-list-optional-parameters self)) (when (lambda-list-key-p self) (mapcan (lambda (par) (list (ensure-parameter-keyword par) (parameter-name par))) (lambda-list-keyword-parameters self))) (list (if rest (parameter-name rest) 'nil))))) ;;;; MAKE-ARGUMENT-LIST-FORM ;; +------+--------+-----+---------+ ;; | rest | k-wo-i | aok | all-opt | ;; +------+--------+-----+---------+ ;; | no | no | no | <=> there is some keyword ;; | no | no | yes | <=> there is some keyword ; we can't know the other keywords! ;; | no | yes | no | yes ;; | no | yes | yes | yes ; we can't know the other keywords! ;; | yes | no | no | <=> there is some keyword <=> (not (null rest)) ;; | yes | no | yes | <=> there is some keyword <=> (not (null rest)) ;; | yes | yes | no | yes ;; | yes | yes | yes | yes ;; +------+--------+-----+---------+ (defgeneric make-argument-list-form (lambda-list)) (defmethod make-argument-list-form ((self lambda-list)) " RETURN: A form that will build a list of arguments passing the same arguments given to lambda-list, to be passed to APPLY. NOTE: If optional or key arguments have an indicator, then they're not passed unless necessary or the indicator is true. BUG: We don't handle MACRO-LAMBDA-LISTs nor DESTRUCTURING-LAMBDA-LISTs, etc. " (flet ((genopt () (loop :with result = '() :with pars = (reverse (lambda-list-optional-parameters self)) :for par = (pop pars) :while (and par (parameter-indicator-p par)) :do (push `(when ,(parameter-indicator par) (list ,(parameter-name par))) result) :finally (return `(,@(when (or par pars) `((list ,@(nreverse (mapcar (function parameter-name) (if par (cons par pars) pars)))))) ,@result))))) (let* ((rest (cond ((lambda-list-rest-parameter-p self) (lambda-list-rest-parameter self)) ((lambda-list-body-parameter-p self) (lambda-list-body-parameter self)))) (form `(append ,@(if (not (every (function parameter-indicator-p) (lambda-list-keyword-parameters self))) ;; If some keyword parameter has no indicator, ;; we will be forced to pass it again as argument, ;; therefore we must pass all optional argumentst too. `( (list ,@(mapcar (function parameter-name) (lambda-list-mandatory-parameters self)) ,@(mapcar (function parameter-name) (lambda-list-optional-parameters self)))) `( (list ,@(mapcar (function parameter-name) (lambda-list-mandatory-parameters self))) ,@(if (not (or rest (lambda-list-keyword-parameters self))) (genopt) `((if ,(if rest (parameter-name rest) `(or ,@(mapcar (function parameter-indicator) (lambda-list-keyword-parameters self)))) (list ,@(mapcar (function parameter-name) (lambda-list-optional-parameters self))) ,(let ((subforms (genopt))) (cond ((null subforms) '()) ((cdr subforms) `(append ,@subforms)) (t (car subforms))))))))) ,@(if rest ;; When we have a rest (or body) parameter, we don't need ;; to generate the keyword parameters, since they're ;; covered by the rest. We just append the rest to the ;; list of arguments. `(,(parameter-name rest)) ;; Without a rest (or body) parameter, we need to pass ;; the keyword arguments. (mapcar (lambda (parameter) (if (parameter-indicator-p parameter) ;; If we have an indicator parameter, ;; we pass the keyword argument ;; only when we got it. `(when ,(parameter-indicator parameter) (list ,(ensure-parameter-keyword parameter) ,(parameter-name parameter))) ;; otherwise we pass the keyword argument ;; unconditionnaly: `(list ,(ensure-parameter-keyword parameter) ,(parameter-name parameter)))) (lambda-list-keyword-parameters self)))))) (if (= 2 (length form)) (second form) form)))) (defmethod make-lambda-list ((self lambda-list)) " RETURN: A newly rebuilt lambda-list s-expr. " (append (when (lambda-list-body-parameter self) (list '&whole (parameter-specifier (lambda-list-whole-parameter self)))) (when (lambda-list-body-parameter self) (list '&environment (parameter-specifier (lambda-list-environment-parameter self)))) (mapcar (function parameter-specifier) (lambda-list-mandatory-parameters self)) (when (lambda-list-optional-parameters self) (cons '&optional (mapcar (function parameter-specifier) (lambda-list-optional-parameters self)))) (when (lambda-list-body-parameter-p self) (list '&body (parameter-specifier (lambda-list-body-parameter self)))) (when (lambda-list-rest-parameter-p self) (list '&rest (parameter-specifier (lambda-list-rest-parameter self)))) (when (lambda-list-key-p self) '(&key)) (when (lambda-list-keyword-parameters self) (mapcar (function parameter-specifier) (lambda-list-keyword-parameters self))) (when (lambda-list-allow-other-keys-p self) '(&allow-other-keys)) (when (lambda-list-auxiliary-parameters self) (cons '&aux (mapcar (function parameter-specifier) (lambda-list-auxiliary-parameters self)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; (defmacro m (&environment env &whole whole ;; ((a b) (c (d e)) &optional (o t op)) ;; e f &body g &key k1 k2) ;; (print (list env whole a b c d e o op e f g k1 k2)) nil) ;; ;; (m ((1 2) (3 (4 5))) 6 7 :k1 (print c) :k2 (print d)) ;; ;; (#(NIL NIL) ;; (M ((1 2) (3 (4 5))) 6 7 :K1 (PRINT C) :K2 (PRINT D)) ;; 1 2 3 4 6 T NIL 6 7 ;; (:K1 (PRINT C) :K2 (PRINT D)) ;; (PRINT C) ;; (PRINT D)) ;; (make-help-from-split-lambda-list ;; (split-lambda-list-on-keywords ;; '(m1 m2 m3 &optional o1 o2 o3 &rest r1 &key k1 k2 k3 &aux a1 a2 a3 ;; &allow-other-keys) ;; :ordinary)) ;;'(m1 m2 m3 &optional o1 o2 o3 &rest r1 &key k1 k2 k3 &aux a1 a2 a3 &allow-other-keys) (eval-when (:compile-toplevel :load-toplevel :execute) (defun extract-documentation (body) " RETURN: The documentation string found in BODY, or NIL if none is present. 3.4.11 Syntactic Interaction of Documentation Strings and Declarations In a number of situations, a documentation string can appear amidst a series of declare expressions prior to a series of forms. In that case, if a string S appears where a documentation string is permissible and is not followed by either a declare expression or a form then S is taken to be a form; otherwise, S is taken as a documentation string. The consequences are unspecified if more than one such documentation string is present. " (loop :for (item . rest) :on body :while (and (consp item) (eq 'declare (first item))) :finally (return (and (stringp item) rest item)))) (defun extract-declarations (body) " RETURN: The list of declaration forms. " (loop :with seen-doc = nil :for item :in body :while (or (and (not seen-doc) (stringp item)) (and (consp item) (eq 'declare (car item)))) :when (and (not seen-doc) (stringp item)) :do (setf seen-doc t) :when (and (consp item) (eq 'declare (car item))) :collect item)) (defun declarations-hash-table (declarations) ;; Todo: add some knowledge on how declarations merge. (loop :with table = (make-hash-table) :for decl :in declarations :do (loop :for (key . value) :in (rest decl) :do (push value (gethash key table '()))) :finally (return table))) (defun extract-body (body) (loop :with seen-doc = nil :for (item . rest) :on body :while (or (and (not seen-doc) (stringp item)) (and (consp item) (eq 'declare (car item)))) :when (and (not seen-doc) (stringp item)) :do (setf seen-doc t) :finally (return (cons item rest))))) (defun extract-method-qualifiers (method-stuff) (loop :for item :in method-stuff :until (listp item) :collect item)) (defun extract-method-lambda-list (method-stuff) (loop :for item :in method-stuff :until (listp item) :finally (return item))) (defun extract-method-ddl (method-stuff) (loop :for (item . body) :in method-stuff :until (listp item) :finally (return body))) (defun extract-method-documentation (method-stuff) (extract-documentation (extract-method-ddl method-stuff))) (defun extract-method-declarations (method-stuff) (extract-declarations (extract-method-ddl method-stuff))) (defun extract-method-body (method-stuff) (extract-body (extract-method-ddl method-stuff))) ;; (eval-when (:compile-toplevel :load-toplevel :execute) ;; (shadow '(DEFUN DEFGENERIC DEFMETHOD))) ;; ;; ;; (defparameter *call-stack* '()) ;; ;; ;; (cl:defmacro defun (name args &body body) ;; (let ((lambda-list (parse-lambda-list args :ordinary)) ;; (docu (extract-documentation body)) ;; (decl (extract-declarations body)) ;; (body (extract-body body))) ;; `(cl:defun ,name ,args ;; ,@(when docu (list docu)) ;; ,@decl ;; (push (list ',name ,@(make-argument-list lambda-list)) *call-stack*) ;; (multiple-value-prog1 (progn ,@body) ;; (pop *call-stack*))))) ;; ;; ;; (cl:defmacro defmethod (name &rest stuff) ;; (let* ((qualifiers (extract-method-qualifiers stuff)) ;; (args (extract-method-lambda-list stuff)) ;; (lambda-list (parse-lambda-list args :specialized)) ;; (docu (extract-method-documentation stuff)) ;; (decl (extract-method-declarations stuff)) ;; (body (extract-method-body stuff))) ;; `(cl:defmethod ;; ,name ,@qualifiers ,args ;; ,@(when docu (list docu)) ;; ,@decl ;; (push (list ',name ,@(make-argument-list lambda-list)) *call-stack*) ;; (multiple-value-prog1 (progn ,@body) ;; (pop *call-stack*))))) ;; ;; (cl:defmacro defgeneric (name args &rest options-and-methods) ;; `(cl:defgeneric ,name ,args ;; ,@(mapcar ;; (lambda (item) ;; (if (and (consp item) (eq :method (car item))) ;; (let* ((stuff (rest item)) ;; (qualifiers (extract-method-qualifiers stuff)) ;; (args (extract-method-lambda-list stuff)) ;; (lambda-list (parse-lambda-list args :specialized)) ;; (docu (extract-method-documentation stuff)) ;; (decl (extract-method-declarations stuff)) ;; (body (extract-method-body stuff))) ;; `(:method ,@qualifiers ,args ;; ,@(when docu (list docu)) ;; ,@decl ;; (push (list ',name ,@(make-argument-list lambda-list)) ;; *call-stack*) ;; (multiple-value-prog1 (progn ,@body) ;; (pop *call-stack*)))) ;; item)) ;; options-and-methods))) ;;;; The End ;;;;
48,803
Common Lisp
.lisp
1,031
40.042677
116
0.609713
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
bddd226ada7c0ef64aa657d25a879e52228f98c4dbe974a395345469b0d5f956
40,311
[ -1 ]
40,312
reader.lisp
hu-dwim_hu_dwim_reader/source/reader.lisp
;;;;************************************************************************** ;;;;FILE: reader.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; Implements the Common Lisp Reader. ;;;; ;;;; We implement a Common Lisp Reader to be able to read lisp sources. ;;;; First, we implement a complete standard compliant lisp reader, ;;;; with additionnal hooks (token parser). ;;;; ;;;; A READTABLE-PARSE-TOKEN function takes a TOKEN as argument, and ;;;; must return two values: ;;;; - A boolean indicating whether the it could parse the token, ;;;; - a parsed lisp object it could, or an error message (string) if not. ;;;; ;;;; See also the TOKEN functions, CONSTITUENT-TRAIT, SYNTAX-TABLE and ;;;; CHARACTER-DESCRIPTION... ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2007-03-04 <PJB> Extracted from source.lisp ;;;;BUGS ;;;; When we've reached the end of the stream, if we (read stream nil) ;;;; it goes on an infinite loop. ;;;;LEGAL ;;;; GPL ;;;; ;;;; Copyright Pascal Bourguignon 2006 - 2007 ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU General Public License ;;;; as published by the Free Software Foundation; either version ;;;; 2 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be ;;;; useful, but WITHOUT ANY WARRANTY; without even the implied ;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;;;; PURPOSE. See the GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public ;;;; License along with this program; if not, write to the Free ;;;; Software Foundation, Inc., 59 Temple Place, Suite 330, ;;;; Boston, MA 02111-1307 USA ;;;;************************************************************************** (in-package "COMMON-LISP-USER") (defpackage "COM.INFORMATIMAGO.COMMON-LISP.READER" (:nicknames "READER") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-FORM") (:shadow "READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*") (:export "READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*" ;; Extensions: "READTABLE-SYNTAX-TABLE" "READTABLE-PARSE-TOKEN" "SET-INDIRECT-DISPATCH-MACRO-CHARACTER" "SET-INDIRECT-MACRO-CHARACTER" "LIST-ALL-MACRO-CHARACTERS" "SIMPLE-READER-ERROR" "SIMPLE-END-OF-FILE") (:documentation "This package implements a standard Common Lisp reader. Copyright Pascal J. Bourguignon 2006 - 2007 This package is provided under the GNU General Public License. See the source file for details.")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.READER") (define-condition simple-reader-error (simple-error reader-error) ()) (define-condition simple-end-of-file (simple-error end-of-file) ()) (defun serror (condition stream control-string &rest arguments) (error condition :stream stream :format-control control-string :format-arguments arguments)) ;; (LET ((*READTABLE* (COPY-READTABLE NIL))) ;; (SET-DISPATCH-MACRO-CHARACTER ;; #\# #\. (LAMBDA (&REST ARGS) ARGS))) ;; ;; (setf (readtable-case *readtable*) :preserve) ;; (let ((*readtable* (copy-readtable))) ;; ;; Quick and dirty disable : --> read three or four tokens ;; ;; for pack:sym or pack::sym ;; (set-macro-character #\: (lambda (stream char) #\:) nil) ;; (SAFE-TEXT-FILE-TO-STRING-LIST path)) ;; ;; ;; (defun unnamed-char-p (ch) ;; (not (null (regexp:match "^U\\([0-9A-F]\\{4\\}\\|[0-9A-F]\\{8\\}\\)$" ;; (char-name ch))))) ;; ;; ;; (defun collect-chars (&key (start 0) (end #x11000) name) ;; (loop ;; :with table = (make-hash-table :test (function equalp)) ;; :for code :from start :below end ;; :for char = (code-char code) ;; :for name = (char-name char) ;; :do (unless (unnamed-char-p char) ;; (dolist (word (regexp:regexp-split "[-_]" name)) ;; (push char (gethash word table nil)))) ;; :finally (return table))) ;;---------------------------------------- (defclass character-description () ((syntax :reader character-syntax :initarg :syntax) (traits :reader character-constituent-traits :initarg :traits :initform nil) (macro :reader character-macro :initarg :macro :initform nil :documentation "A macro character function.") (dispatch :reader character-dispatch :initarg :dispatch :initform nil :documentation "A HASH-TABLE character -> dmc function.")) (:documentation " Description of one character. In the syntax tables, a single character description instance can be shared by several characters, but with copy-on-write. ")) ;; macro-character-function ;; dispatch-macro --> map character -> dispatch-macro-character-function (eval-when (:compile-toplevel :load-toplevel :execute) ;;; Character syntaxes: (defconstant +cs-invalid+ 0) (defconstant +cs-whitespace+ 1) (defconstant +cs-single-escape+ 2) (defconstant +cs-multiple-escape+ 3) (defconstant +cs-constituent+ 4) (defconstant +cs-terminating-macro-character+ 5) (defconstant +cs-non-terminating-macro-character+ 6) ;;; Constituent traits: (defconstant +ct-invalid+ #b00000000000001) (defconstant +ct-alphabetic+ #b00000000000010) (defconstant +ct-digit+ #b00000000000100) (defconstant +ct-alphadigit+ #b00000000000110) (defconstant +ct-package-marker+ #b00000000001000) (defconstant +ct-plus-sign+ #b00000000010000) (defconstant +ct-minus-sign+ #b00000000100000) (defconstant +ct-sign+ #b00000000110000) (defconstant +ct-dot+ #b00000001000000) (defconstant +ct-decimal-point+ #b00000010000000) (defconstant +ct-ratio-marker+ #b00000100000000) (defconstant +ct-float-exponent-marker+ #b00001000000000) (defconstant +ct-short-float-exponent-marker+ #b00011000000000) (defconstant +ct-single-float-exponent-marker+ #b00101000000000) (defconstant +ct-double-float-exponent-marker+ #b01001000000000) (defconstant +ct-long-float-exponent-marker+ #b10001000000000) (defconstant +ct-max+ +ct-long-float-exponent-marker+) ) ;;eval-when (deftype constituent-trait () `(integer 0 ,(expt 2 (integer-length +ct-max+)))) (declaim (inline traitp)) (defun traitp (trait traits) "Returns whether the TRAIT is in the TRAITS 'set'." (plusp (logand trait traits))) ;;; The shared character descriptions: (defparameter *cd-invalid* (make-instance 'character-description :syntax +cs-invalid+ :traits +ct-invalid+)) (defparameter *cd-whitespace* (make-instance 'character-description :syntax +cs-whitespace+ :traits +ct-invalid+)) (defparameter *cd-constituent-invalid* (make-instance 'character-description :syntax +cs-whitespace+ :traits +ct-invalid+)) (defparameter *cd-constituent-alphabetic* (make-instance 'character-description :syntax +cs-constituent+ :traits +ct-alphabetic+)) ;; ---------------------------------------- (defclass syntax-table () (standard-characters extended-characters constituent invalid) (:documentation " STANDARD-CHARACTERS is a vector of CHARACTER-DESCRIPTION instances for the standard character codes below +STANDARD-CHARACTERS-LIMIT+. EXTENDED-CHARACTERS is NIL, or a HASH-TABLE mapping characters to CHARACTER-DESCRIPTIONS instances for the extended characters with codes above +STANDARD-CHARACTERS-LIMIT+. Extended characters without an entry in EXTENDED-CHARACTERS either have CONSTITUENT or INVALID CHARACTER-DESCRIPTION, depending on whether they're GRAPHIC-CHAR-P or not. ")) (defconstant +standard-characters-limit+ 128) (defmethod initialize-instance :after ((self syntax-table) &key &allow-other-keys) (let ((table (make-array +standard-characters-limit+ :initial-element *cd-invalid*))) (setf (aref table (char-code #\Backspace)) *cd-constituent-invalid* (aref table (char-code #\Rubout)) *cd-constituent-invalid* (aref table (char-code #\Tab)) *cd-whitespace* (aref table (char-code #\Newline)) *cd-whitespace* (aref table (char-code #\Linefeed)) *cd-whitespace* (aref table (char-code #\Page)) *cd-whitespace* (aref table (char-code #\Return)) *cd-whitespace* (aref table (char-code #\Space)) *cd-whitespace*) (loop :for chdesc :in '((#.+cs-terminating-macro-character+ "\"'(),;`" #.+ct-alphabetic+) (#.+cs-non-terminating-macro-character+ "#" #.+ct-alphabetic+) (#.+cs-single-escape+ "\\" #.+ct-alphabetic+) (#.+cs-multiple-escape+ "|" #.+ct-alphabetic+) (#.+cs-constituent+ "!$%&*<=>?@[]^_{}~" #.+ct-alphabetic+) (#.+cs-constituent+ ":" #.+ct-package-marker+) (#.+cs-constituent+ "+" #.+ct-alphabetic+ #.+ct-plus-sign+) (#.+cs-constituent+ "-" #.+ct-alphabetic+ #.+ct-minus-sign+) (#.+cs-constituent+ "." #.+ct-alphabetic+ #.+ct-dot+ #.+ct-decimal-point+) (#.+cs-constituent+ "/" #.+ct-alphabetic+ #.+ct-ratio-marker+) (#.+cs-constituent+ "0123456789" #.+ct-alphadigit+) (#.+cs-constituent+ "Dd" #.+ct-alphadigit+ #.+ct-double-float-exponent-marker+) (#.+cs-constituent+ "Ee" #.+ct-alphadigit+ #.+ct-float-exponent-marker+) (#.+cs-constituent+ "Ff" #.+ct-alphadigit+ #.+ct-single-float-exponent-marker+) (#.+cs-constituent+ "Ll" #.+ct-alphadigit+ #.+ct-long-float-exponent-marker+) (#.+cs-constituent+ "Ss" #.+ct-alphadigit+ #.+ct-short-float-exponent-marker+) (#.+cs-constituent+ "ABCGHIJKMNOPQRTUVWXYZabcghijkmnopqrtuvwxyz" #.+ct-alphadigit+)) :do (loop :with desc = (make-instance 'character-description :syntax (first chdesc) :traits (if (null (cdddr chdesc)) (third chdesc) (apply (function logior) (cddr chdesc)))) :for ch :across (second chdesc) :do (setf (aref table (char-code ch)) desc))) (setf (slot-value self 'standard-characters) table (slot-value self 'extended-characters) nil)) self) (defgeneric copy-syntax-table (syntax-table)) (defgeneric character-description (syntax-table character)) (defmethod copy-syntax-table ((self syntax-table)) (let ((copy (make-instance 'syntax-table))) (setf (slot-value copy 'standard-characters) (copy-seq (slot-value self 'standard-characters)) (slot-value copy 'extended-characters) (and (slot-value self 'extended-characters) (copy-hash-table (slot-value self 'extended-characters)))) copy)) (defmethod character-description ((self syntax-table) (ch character)) (let ((code (char-code ch))) (if (< code +standard-characters-limit+) (aref (slot-value self 'standard-characters) code) (or (and (slot-value self 'extended-characters) (gethash code (slot-value self 'extended-characters))) (if (graphic-char-p ch) *cd-constituent-alphabetic* *cd-invalid*))))) (defgeneric (setf character-description) (val syntax-table character)) (defmethod (setf character-description) (val (self syntax-table) (ch character)) (let ((code (char-code ch))) (if (< code +standard-characters-limit+) (setf (aref (slot-value self 'standard-characters) code) val) (progn (unless (slot-value self 'extended-characters) (setf (slot-value self 'extended-characters) (make-hash-table))) (setf (gethash code (slot-value self 'extended-characters)) val))))) ;;---------------------------------------- (defvar *standard-readtable* nil "Only used by SET-SYNTAX-FROM-CHAR") (defvar *readtable* nil " The value of *READTABLE* is called the current readtable. It controls the parsing behavior of the Lisp reader, and can also influence the Lisp printer (e.g., see the function READTABLE-CASE). URL: http://www.lispworks.com/documentation/HyperSpec/Body/v_rdtabl.htm ") (defvar *read-base* 10 " Controls the interpretation of tokens by READ as being integers or ratios. The value of *READ-BASE*, called the current input base, is the radix in which integers and ratios are to be read by the Lisp reader. The parsing of other numeric types (e.g., floats) is not affected by this option. The effect of *READ-BASE* on the reading of any particular rational number can be locally overridden by explicit use of the #O, #X, #B, or #nR syntax or by a trailing decimal point. URL: http://www.lispworks.com/documentation/HyperSpec/Body/v_rd_bas.htm ") (defvar *read-eval* t " If it is true, the #. reader macro has its normal effect. Otherwise, that reader macro signals an error of type reader-error. URL: http://www.lispworks.com/documentation/HyperSpec/Body/v_rd_eva.htm ") (defvar *read-suppress* nil " This variable is intended primarily to support the operation of the read-time conditional notations #+ and #-. If it is false, the Lisp reader operates normally. If the value of *read-suppress* is true, read, read-preserving-whitespace, read-delimited-list, and read-from-string all return a primary value of nil when they complete successfully. URL: http://www.lispworks.com/documentation/HyperSpec/Body/v_rd_sup.htm ") (defvar *READ-DEFAULT-FLOAT-FORMAT* 'single-float " Controls the floating-point format that is to be used when reading a floating-point number that has no exponent marker or that has e or E for an exponent marker. Other exponent markers explicitly prescribe the floating-point format to be used. The printer uses *read-default-float-format* to guide the choice of exponent markers when printing floating-point numbers. URL: http://www.lispworks.com/documentation/HyperSpec/Body/v_rd_def.htm ") (declaim (ftype (function (t) t) parse-token)) (defclass readtable () ((case :initarg :case :initform :upcase :type (member :upcase :downcase :preserve :invert)) (syntax-table :accessor readtable-syntax-table :initarg :syntax-table :initform (make-instance 'syntax-table)) (parse-token :accessor readtable-parse-token :initarg :parse-token :initform (function parse-token))) (:documentation " A READTABLE maps characters into syntax types for the Lisp reader; see Section 2 (Syntax). A readtable also contains associations between macro characters and their reader macro functions, and records information about the case conversion rules to be used by the Lisp reader when parsing symbols. Each simple character must be representable in the readtable. It is implementation-defined whether non-simple characters can have syntax descriptions in the readtable. URL: http://www.lispworks.com/documentation/HyperSpec/Body/t_rdtabl.htm ")) (defun copy-readtable (&optional (from-readtable *readtable*) (to-readtable nil)) (if (null from-readtable) (if (null to-readtable) (make-instance 'readtable) (progn (setf (readtable-case to-readtable) :upcase (readtable-syntax-table to-readtable) (make-instance 'syntax-table) (readtable-parse-token to-readtable) (function parse-token)) to-readtable)) (if (null to-readtable) (make-instance 'readtable :case (readtable-case from-readtable) :syntax-table (copy-syntax-table (readtable-syntax-table from-readtable)) :parse-token (readtable-parse-token from-readtable)) (progn (setf (readtable-case to-readtable) (readtable-case from-readtable) (readtable-syntax-table to-readtable) (copy-syntax-table (readtable-syntax-table from-readtable)) (readtable-parse-token to-readtable) (readtable-parse-token from-readtable)) to-readtable)))) (defun reader-dispatch-macro-error-undefined (stream ch sub-char) (serror 'simple-reader-error stream "After #\\~A is #\\~A an undefined dispatch macro character" ch sub-char)) (defun reader-dispatch-macro-error-invalid (stream sub-char arg) (declare (ignore sub-char arg)) (serror 'simple-reader-error stream "objects printed as # in view of *PRINT-LEVEL* cannot be read back in")) (defun reader-macro-dispatch-function (stream ch) (let* ((arg (loop :for ch = (read-char stream t nil t) :while (digit-char-p ch) :collect ch :into digits :finally (unread-char ch stream) (return (when digits (parse-integer (coerce digits 'string)))))) (sub-char (read-char stream t nil t)) (cd (character-description (readtable-syntax-table *readtable*) ch)) (fun (gethash (char-upcase sub-char) (character-dispatch cd)))) (if fun (funcall fun stream arg sub-char) (reader-dispatch-macro-error-undefined stream ch sub-char)))) (defgeneric process-case-function (mode) (:method ((mode (eql :preserve))) (function identity)) (:method ((mode (eql :downcase))) (function char-downcase)) (:method ((mode (eql :upcase))) (function char-upcase)) (:method ((mode (eql :invert))) (lambda (ch) (cond ((upper-case-p ch) (char-downcase ch)) ((lower-case-p ch) (char-upcase ch)) (t ch))))) ;;; For tokens we need to keep track of the characters and their ;;; traits in parallel: (declaim (inline make-token token-text token-traits token-length token-char token-char-traits token-collect-character)) (defun make-token () (flet ((arr (type) (make-array 8 :adjustable t :fill-pointer 0 :element-type type))) (declare (inline arr)) (cons (arr 'character) (arr 'constituent-trait)))) (defun token-text (token) (car token)) (defun token-traits (token) (cdr token)) (defun token-length (token) (length (car token))) (defun token-char (token index) (aref (car token) index)) (defun token-char-traits (token index) (aref (cdr token) index)) (defun token-collect-character (token character traits) (vector-push-extend character (car token)) (vector-push-extend traits (cdr token))) (defun token-delimiter-p (character) (let ((cs (character-syntax (character-description (readtable-syntax-table *readtable*) character)))) (or (= cs +cs-whitespace+) (= cs +cs-terminating-macro-character+)))) (defvar *references* nil "Used to implement #= and ##.") (defun read-token (input-stream eof-error-p eof-value recursive-p preserve-whitespace-p first-char readtable) " DO: Implements parts of READ and READ-PRESERVING-WHITESPACE. RETURN: tokenp == t ; a token. Or tokenp == :EOF ; the eof-value. Or tokenp == NIL ; a list of values read. " (macrolet ((unless-eof (place &body body) `(cond (,place ,@body) (eof-error-p (serror 'simple-end-of-file input-stream "input stream ~S has reached its end" input-stream)) (t (return-from read-token (values :eof eof-value))))) (error-invalid-character (ch) `(serror 'simple-reader-error input-stream "invalid character #\\~A" ,ch))) (let ((*references* (if recursive-p *references* (make-hash-table)))) (prog (x y (token (make-token)) (syntax-table (readtable-syntax-table readtable)) (procase (process-case-function (readtable-case readtable)))) :begin (setf x (or first-char (read-char input-stream nil nil t)) first-char nil) (unless-eof x (let ((cd (character-description syntax-table x))) (ecase (character-syntax cd) ((#.+cs-invalid+) (error-invalid-character x)) ((#.+cs-whitespace+) (go :begin)) ((#.+cs-single-escape+) (let ((z (read-char input-stream nil nil t))) (unless-eof z (token-collect-character token z +ct-alphabetic+))) (go :collect-token)) ((#.+cs-multiple-escape+) (go :collect-multiple-escape-token)) ((#.+cs-constituent+) (token-collect-character token (funcall procase x) (character-constituent-traits cd)) (go :collect-token)) ((#.+cs-terminating-macro-character+ #.+cs-non-terminating-macro-character+) ;; If the macro returns no value, the caller will ;; have to call us again, or not: (#-(and)x) (return-from read-token (values nil (multiple-value-list (funcall (get-macro-character x readtable) input-stream x)))))))) :collect-token (setf y (read-char input-stream nil nil t)) (if y (let ((cd (character-description syntax-table y))) (ecase (character-syntax cd) ((#.+cs-invalid+) (error-invalid-character y)) ((#.+cs-whitespace+) (when preserve-whitespace-p (unread-char y input-stream)) (go :parse-token)) ((#.+cs-single-escape+) (let ((z (read-char input-stream nil nil t))) (unless-eof z (token-collect-character token z +ct-alphabetic+))) (go :collect-token)) ((#.+cs-multiple-escape+) (go :collect-multiple-escape-token)) ((#.+cs-constituent+ #.+cs-non-terminating-macro-character+) (token-collect-character token (funcall procase y) (character-constituent-traits cd)) (go :collect-token)) ((#.+cs-terminating-macro-character+) (unread-char y input-stream) (go :parse-token)))) (go :parse-token)) :collect-multiple-escape-token (setf y (read-char input-stream nil nil t)) (unless-eof y (let ((cd (character-description syntax-table y))) (ecase (character-syntax cd) ((#.+cs-invalid+) (error-invalid-character y)) ((#.+cs-single-escape+) (let ((z (read-char input-stream nil nil t))) (unless-eof z (token-collect-character token z +ct-alphabetic+))) (go :collect-multiple-escape-token)) ((#.+cs-multiple-escape+) (go :collect-token)) ((#.+cs-whitespace+ #.+cs-constituent+ #.+cs-non-terminating-macro-character+ #.+cs-terminating-macro-character+) (token-collect-character token y +ct-alphabetic+) (go :collect-multiple-escape-token))))) :parse-token (assert (plusp (length (car token)))) (return (values t token)))))) ;; numeric-token ::= integer | ratio | float ;; integer ::= [sign] decimal-digit+ decimal-point ;; integer ::= [sign] digit+ ;; ratio ::= [sign] {digit}+ slash {digit}+ ;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ exponent ;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ ;; float ::= [sign] {decimal-digit}+ exponent ;; float ::= [sign] {decimal-digit}+ decimal-point {decimal-digit}* exponent ;; exponent ::= exponent-marker [sign] {digit}+ ;; ;; consing-dot ::= dot ;; ;; symbol ::= symbol-name ;; | package-marker symbol-name ;; | package-marker package-marker symbol-name ;; | package-name package-marker symbol-name ;; | package-name package-marker package-marker symbol-name ;; ;; symbol-name ::= {alphabetic}+ ;; package-name ::= {alphabetic}+ (defmacro defparser (name arguments &body body) "Defines a token parser function, which parses its argument token and returns three values: a ok flag; a type of value; and a value parsed from the token. When the ok flag is false, the type indicates whether it's a strong error, and the value returned is an error message. A strong error is a lexical error that is not ambiguous. A weak error is when the token could still be of another lexical category. In the body of the parser, there are macrolet defined to REJECT or ACCEPT the token, and to describe the parsed syntax with ALT, ZERO-OR-MORE, ONE-OR-MORE and OPT-SIGN." (let ((docu (extract-documentation body)) (decl (extract-declarations body)) (body (extract-body body))) `(defun ,name ,arguments ,@(when docu (list docu)) ,@decl (macrolet ((reject (strongp &rest ctrlstring-and-args) `(return-from ,',name (values nil ,strongp ,(when ctrlstring-and-args `(format nil ,@ctrlstring-and-args))))) (accept (type token) `(return-from ,',name (values t ,type ,token))) (alt (&rest clauses) `(cond ,@clauses)) (zero-or-more (test &body body) `(loop :while ,test :do ,@body)) (one-or-more (test &body body) `(progn (if ,test (progn ,@body) (reject nil)) (loop :while ,test :do ,@body))) (opt-sign (sign token i) `(alt ((>= ,i (token-length ,token))) ((traitp +ct-plus-sign+ (token-char-traits ,token ,i)) (setf ,sign +1 ,i (1+ ,i))) ((traitp +ct-minus-sign+ (token-char-traits ,token ,i)) (setf ,sign -1 ,i (1+ ,i)))))) ,@body)))) (defparser parse-decimal-integer-token (token) "integer ::= [sign] decimal-digit+ decimal-point" (let ((sign 1) (mant 0) (i 0)) (unless (traitp +ct-decimal-point+ (token-char-traits token (1- (token-length token)))) (reject nil)) (unless (< i (token-length token)) (reject nil)) (opt-sign sign token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf mant (+ (* 10. mant) (digit-char-p (token-char token i))) i (1+ i))) (if (and (= (1+ i) (token-length token)) (traitp +ct-decimal-point+ (token-char-traits token i))) (accept 'integer (* sign mant)) (reject t (if (= (1+ i) (token-length token)) "Missing decimal point in decimal integer ~S" "Junk after decimal point in decimal integer ~S") (token-text token))))) (defparser parse-integer-token (token) "integer ::= [sign] digit+" (let ((sign 1) (mant 0) (i 0)) (unless (< i (token-length token)) (reject nil)) (opt-sign sign token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i) *read-base*)) (setf mant (+ (* *read-base* mant) (digit-char-p (token-char token i) *read-base*)) i (1+ i))) (if (= i (token-length token)) (accept 'integer (* sign mant)) (reject t "Junk after integer ~S" (token-text token))))) (defparser parse-ratio-token (token) "ratio ::= [sign] {digit}+ slash {digit}+" (let ((sign 1) (nume 0) (denu 0) (i 0)) (unless (< i (token-length token)) (reject nil)) (opt-sign sign token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i) *read-base*)) (setf nume (+ (* *read-base* nume) (digit-char-p (token-char token i) *read-base*)) i (1+ i))) (if (traitp +ct-ratio-marker+ (token-char-traits token i)) (incf i) (reject nil)) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i) *read-base*)) (setf denu (+ (* *read-base* denu) (digit-char-p (token-char token i) *read-base*)) i (1+ i))) (cond ((< i (token-length token)) (reject t "Junk after ratio ~S" (token-text token))) #+(or) ((zerop denu) (reject t "Zero denominator ratio ~S" (token-text token))) (t (accept 'ratio (/ (* sign nume) denu)))))) (defparser parse-float-1-token (token) "float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ [exponent] exponent ::= exponent-marker [sign] {digit}+" (let ((sign 1) (nume 0) (denu 1) (type *READ-DEFAULT-FLOAT-FORMAT*) (esgn 1) (expo 0) (i 0)) (opt-sign sign token i) (zero-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf nume (+ (* 10. nume) (digit-char-p (token-char token i))) i (1+ i))) (if (and (< i (token-length token)) (traitp +ct-decimal-point+ (token-char-traits token i))) (incf i) (reject nil)) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf nume (+ (* 10. nume) (digit-char-p (token-char token i))) denu (* 10. denu) i (1+ i))) (when (and (< i (token-length token)) (traitp +ct-float-exponent-marker+ (token-char-traits token i))) (cond ((traitp +ct-short-float-exponent-marker+ (token-char-traits token i)) (setf type 'short-float)) ((traitp +ct-single-float-exponent-marker+ (token-char-traits token i)) (setf type 'single-float)) ((traitp +ct-double-float-exponent-marker+ (token-char-traits token i)) (setf type 'double-float)) ((traitp +ct-long-float-exponent-marker+ (token-char-traits token i)) (setf type 'long-float))) (incf i) (opt-sign esgn token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf expo (+ (* 10. expo) (digit-char-p (token-char token i))) i (1+ i)))) (if (= i (token-length token)) (accept type (* (coerce (/ (* sign nume) denu) type) (expt 10.0 (* esgn expo)))) (reject t "Junk after floating point number ~S" (token-text token))))) (defparser parse-float-2-token (token) "float ::= [sign] {decimal-digit}+ [decimal-point {decimal-digit}*] exponent exponent ::= exponent-marker [sign] {digit}+" (let ((sign 1) (nume 0) (denu 1) (type *READ-DEFAULT-FLOAT-FORMAT*) (esgn 1) (expo 0) (i 0)) (opt-sign sign token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf nume (+ (* 10. nume) (digit-char-p (token-char token i))) i (1+ i))) (when (and (< i (token-length token)) (traitp +ct-decimal-point+ (token-char-traits token i))) (incf i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf nume (+ (* 10. nume) (digit-char-p (token-char token i))) denu (* 10. denu) i (1+ i)))) (unless (and (< i (token-length token)) (traitp +ct-float-exponent-marker+ (token-char-traits token i))) (reject nil)) (cond ((traitp +ct-short-float-exponent-marker+ (token-char-traits token i)) (setf type 'short-float)) ((traitp +ct-single-float-exponent-marker+ (token-char-traits token i)) (setf type 'single-float)) ((traitp +ct-double-float-exponent-marker+ (token-char-traits token i)) (setf type 'double-float)) ((traitp +ct-long-float-exponent-marker+ (token-char-traits token i)) (setf type 'long-float))) (incf i) (opt-sign esgn token i) (one-or-more (and (< i (token-length token)) (traitp +ct-digit+ (token-char-traits token i)) (digit-char-p (token-char token i))) (setf expo (+ (* 10. expo) (digit-char-p (token-char token i))) i (1+ i))) (if (= i (token-length token)) (accept type (* (coerce (/ (* sign nume) denu) type) (expt 10.0 (* esgn expo)))) (reject t "Junk after floating point number ~S" (token-text token))))) ;; (defparser parse-consing-dot-token (token) ;; "consing-dot ::= dot" ;; (if (and (= 1 (token-length token)) ;; (traitp +ct-dot+ (token-char-traits token 0))) ;; (accept 'consing-dot ".") ;; (reject nil))) (defparser parse-symbol-token (token) "symbol ::= symbol-name symbol ::= package-marker symbol-name symbol ::= package-marker package-marker symbol-name symbol ::= package-name package-marker symbol-name symbol ::= package-name package-marker package-marker symbol-name symbol-name ::= {alphabetic}+ package-name ::= {alphabetic}+ " (let ((colon (position-if (lambda (traits) (traitp +ct-package-marker+ traits)) (token-traits token)))) (if colon (let* ((double-colon (and (< (1+ colon) (token-length token)) (traitp +ct-package-marker+ (token-char-traits token (1+ colon))))) (pname (subseq (token-text token) 0 colon)) (sname (subseq (token-text token) (+ colon (if double-colon 2 1))))) (when (position-if (lambda (traits) (traitp +ct-package-marker+ traits)) (token-traits token) :start (+ colon (if double-colon 2 1))) (reject t "Too many package markers in token ~S" (token-text token))) (when (zerop colon) ;; Keywords always exist, so let's intern them before finding them. (setf pname "KEYWORD") (intern sname pname)) ;; The following form thanks to Andrew Philpot <[email protected]> ;; corrects a bug when reading with double-colon uninterned symbols: (if (find-package pname) (if double-colon (accept 'symbol (intern sname pname)) (multiple-value-bind (sym where) (find-symbol sname pname) (if (eq where :external) (accept 'symbol sym) (reject t "There is no external symbol named ~S in ~ the package named ~S" sname pname)))) (reject t "There is no package with name ~S" pname))) ;; no colon in token, let's just intern the symbol in the current package: (accept 'symbol (intern (token-text token) *package*))))) (defun parse-token (token) " RETURN: okp ; the parsed lisp object if okp, or an error message if (not okp) " (let ((message nil)) (macrolet ((rom (&body body) "Result Or Message" (if (null body) 'nil (let ((vals (gensym))) `(let ((,vals (multiple-value-list ,(car body)))) ;; (format *trace-output* "~S --> ~S~%" ',(car body) ,vals) (if (first ,vals) (values-list ,vals) (progn (when (second ,vals) (setf message (third ,vals))) (rom ,@(cdr body))))))))) (multiple-value-bind (ok type object) (rom (parse-decimal-integer-token token) (parse-integer-token token) (parse-ratio-token token) (parse-float-1-token token) (parse-float-2-token token) ;; (parse-consing-dot-token token) (parse-symbol-token token)) (declare (ignorable type)) ;; (format *trace-output* "ok = ~S ; type = ~S ; object = ~S~%" ;; ok type object) (values ok (if ok object message)))))) (Defun all-dots-p (token) " RETURN: Whether the token is all dots, (excluding escaped dots). " (assert (plusp (length (token-text token)))) (every (lambda (traits) (traitp +ct-dot+ traits)) (token-traits token))) (defun read-0/1 (input-stream eof-error-p eof-value recursive-p preserve-whitespace-p first-char allowed-all-dots) " DO: Read zero or one token. RETURN: tokenp == t ; a token. Or tokenp == :EOF ; the eof-value. Or tokenp == NIL ; a list of values read. " (multiple-value-bind (tokenp token) (read-token input-stream eof-error-p eof-value recursive-p preserve-whitespace-p first-char *readtable*) (if (eq 't tokenp) (cond (*read-suppress* (values nil (list nil))) ((or (eq 't allowed-all-dots) (not (all-dots-p token))) ; We got a token, let's parse it. (values nil (list (multiple-value-bind (okp object) (funcall (readtable-parse-token *readtable*) token) (if okp object (serror 'simple-reader-error input-stream "~A" object)))))) ((member (token-text token) allowed-all-dots :test (function string=)) (values t token)) (t (serror 'simple-reader-error input-stream "a token consisting only of dots cannot be ~ meaningfully read in"))) (values tokenp token)))) (defun read-1 (input-stream eof-error-p eof-value recursive-p preserve-whitespace-p first-char allowed-all-dots) (loop :for (tokenp token) = (multiple-value-list (read-0/1 input-stream eof-error-p eof-value recursive-p preserve-whitespace-p first-char allowed-all-dots)) :until (or (eq :eof tokenp) token) :finally (return (if (eq :eof tokenp) token (first token))))) (defun read (&optional input-stream (eof-error-p t) (eof-value nil) (recursive-p nil)) "URL: http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_rd.htm" (read-1 input-stream eof-error-p eof-value recursive-p nil nil '())) (defun read-preserving-whitespace (&optional input-stream (eof-error-p t) (eof-value nil) (recursive-p nil)) "URL: http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_rd.htm" (read-1 input-stream eof-error-p eof-value recursive-p t nil '())) (defun read-delimited-list (char &optional (input-stream *standard-input*) (recursive-p nil)) "URL: http://www.lispworks.com/documentation/HyperSpec/Body/f_rd_del.htm" (loop :with result = '() :for peek = (peek-char t input-stream nil input-stream recursive-p) :do (cond ((eql peek input-stream) (serror 'simple-end-of-file input-stream "input stream ~S has reached its end" input-stream)) ((char= peek char) (read-char input-stream nil nil recursive-p) (return-from read-delimited-list (nreverse result))) (t (push (read input-stream t nil t) result))))) (locally #+sbcl(declare (sb-ext:muffle-conditions style-warning)) (defun read-from-string (string &optional (eof-error-p t) (eof-value nil) &key (start 0) (end nil) (preserve-whitespace nil)) (let ((index 0)) (values (with-input-from-string (input string :index index :start start :end end) (funcall (if preserve-whitespace (function read-preserving-whitespace) (function read)) input eof-error-p eof-value)) index)))) (defun readtable-case (readtable) (slot-value readtable 'case)) (defun (setf readtable-case) (value readtable) (check-type value (member :upcase :downcase :preserve :invert)) (setf (slot-value readtable 'case) value)) (defun readtablep (object) (typep object 'readtable)) (defun make-dispatch-macro-character (char &optional (non-terminating-p nil) (readtable *readtable*)) (let ((rst (readtable-syntax-table readtable))) (setf (character-description rst char) (make-instance 'character-description :syntax (if non-terminating-p +cs-non-terminating-macro-character+ +cs-terminating-macro-character+) :traits (character-constituent-traits (character-description rst char)) :macro (function reader-macro-dispatch-function) :dispatch (make-hash-table))))) (defun get-dispatch-macro-character (disp-char sub-char &optional (readtable *readtable*)) (let* ((rst (readtable-syntax-table readtable)) (cd (character-description rst disp-char))) (unless (character-dispatch cd) (error "~S is not a dispatch macro character" disp-char)) (and (character-dispatch cd) (gethash (char-upcase sub-char) (character-dispatch cd))))) (defun set-dispatch-macro-character (disp-char sub-char new-function &optional (readtable *readtable*)) (let* ((rst (readtable-syntax-table readtable)) (cd (character-description rst disp-char))) (unless (character-dispatch cd) (error "~S is not a dispatch macro character" disp-char)) (setf (gethash (char-upcase sub-char) (character-dispatch cd)) new-function)) t) (defun get-macro-character (char &optional (readtable *readtable*)) (let* ((rst (readtable-syntax-table readtable)) (cd (character-description rst char))) (values (character-macro cd) (= (character-syntax cd) +cs-non-terminating-macro-character+)))) (defun set-macro-character (char new-function &optional (non-terminating-p nil) (readtable *readtable*)) (let* ((rst (readtable-syntax-table readtable))) (setf (character-description rst char) (make-instance 'character-description :syntax (if non-terminating-p +cs-non-terminating-macro-character+ +cs-terminating-macro-character+) :traits (character-constituent-traits (character-description rst char)) :macro new-function))) t) (defun set-indirect-dispatch-macro-character (disp-char sub-char function-name &optional (readtable *readtable*)) "Like set-dispatch-macro-character, but with an indirect function, to enable TRACE and redefinitions of the dispatch macro character function." (set-dispatch-macro-character disp-char sub-char (compile nil (let ((s (gensym)) (c (gensym)) (a (gensym))) `(lambda (,s ,c ,a) (,function-name ,s ,c ,a)))) readtable)) (defun set-indirect-macro-character (char function-name &optional (readtable *readtable*)) "Like set-macro-character, but with an indirect function, to enable TRACE and redefinitions of the macro character function." (set-macro-character char (compile nil (let ((s (gensym)) (a (gensym))) `(lambda (,s ,a) (,function-name ,s ,a)))) readtable)) ;; Copied from com.informatimago.common-lisp.utility to avoid package use loop. (defun copy-hash-table (table) " TABLE: (OR NULL HASH-TABLE) RETURN: If TABLE is NIL, then NIL, else a new HASH-TABLE with the same TEST, SIZE, REHASH-THRESHOLD REHASH-SIZE and KEY->VALUE associations than TABLE. (Neither the keys nor the values are copied). " (check-type table (or null hash-table)) (when table (let ((copy (make-hash-table :test (hash-table-test table) :size (hash-table-size table) :rehash-threshold (hash-table-rehash-threshold table) :rehash-size (hash-table-rehash-size table)))) (maphash (lambda (k v) (setf (gethash k copy) v)) table) copy))) (defun set-syntax-from-char (to-char from-char &optional (to-readtable *readtable*) (from-readtable *standard-readtable*)) (let* ((frst (readtable-syntax-table from-readtable)) (trst (readtable-syntax-table to-readtable)) (fcd (character-description frst from-char)) (tcd (character-description trst to-char))) (setf (slot-value tcd 'syntax) (make-instance 'character-description :syntax (character-syntax fcd) :traits (character-constituent-traits fcd) :macro (character-macro fcd) :dispatch (copy-hash-table (character-dispatch fcd))))) t) ;;;---------------------------------------- ;;; STANDARD READER MACRO FUNCTIONS ;;;---------------------------------------- (defun reader-macro-line-comment (stream ch) "Standard ; macro reader." (declare (ignore ch)) (read-line stream nil) (values)) (defun reader-macro-string (stream delim) "Standard \" macro reader." (flet ((error-eof () (serror 'simple-end-of-file stream "input stream ~S ends within a string" stream))) (loop :with rst = (readtable-syntax-table *readtable*) :with string = (make-array 64 :element-type 'character :adjustable t :fill-pointer 0) :for ch = (read-char stream nil nil t) :do (cond ((null ch) (error-eof)) ((eql ch delim) (return-from reader-macro-string (copy-seq string))) ((= (character-syntax (character-description rst ch)) +cs-single-escape+) (let ((next (read-char stream nil nil))) (when (null next) (error-eof)) (vector-push-extend next string))) (t (vector-push-extend ch string)))))) (defun reader-macro-quote (stream ch) "Standard ' macro reader." (declare (ignore ch)) `(quote ,(read stream t nil t))) (defun reader-macro-backquote (stream ch) "Standard ` macro reader." (declare (ignore ch)) `(backquote ,(read stream t nil t))) (defun reader-macro-comma (stream ch) "Standard , macro reader." (declare (ignore ch)) `(,(if (char= #\@ (peek-char nil stream t nil t)) 'splice 'unquote) ,(read stream t nil t))) (defun reader-macro-left-parenthesis (stream ch) "Standard ( macro reader." (declare (ignore ch)) (loop :with result = (cons nil nil) :with last-cons = result :with last-cdr-p = nil :for ch = (progn (peek-char t stream nil t) (read-char stream t nil t)) ;; :do (print `(:result ,result :last-cons ,last-cons ;; :last-cdr-p ,last-cdr-p :ch ,ch)) :do (flet ((read-and-nconc (ch) (let ((objects (nth-value 1 (read-0/1 stream t nil t nil ch '())))) (when objects (case last-cdr-p ((nil) (setf (cdr last-cons) objects ;; (list (first objects)) last-cons (cdr last-cons))) ((t) (setf (cdr last-cons) (first objects) last-cdr-p :done)) (otherwise (serror 'simple-reader-error stream "illegal end of dotted list"))))))) (cond ((char= #\) ch) (loop-finish)) ((char= #\. ch) (if (token-delimiter-p (peek-char nil stream t nil t)) (if (eq result last-cons) (serror 'simple-reader-error stream "missing an object before the \".\" in a cons cell") (case last-cdr-p ((nil) (setf last-cdr-p t)) ((t) (serror 'simple-reader-error stream "token \".\" not allowed here")) (otherwise (serror 'simple-reader-error stream "illegal end of dotted list")))) (read-and-nconc ch))) (t (read-and-nconc ch)))) :finally (if (eq last-cdr-p 't) (serror 'simple-reader-error stream "illegal end of dotted list") (return (cdr result))))) (defun reader-macro-error-start (stream ch) (serror 'simple-reader-error stream "an object cannot start with ~C" ch)) ;;;---------------------------------------- ;;; STANDARD READER DISPATCH MACRO FUNCTIONS ;;;---------------------------------------- (defun reader-dispatch-macro-label-reference (stream arg sub-char) "Standard ## dispatch macro reader." (declare (ignore sub-char)) (when (null arg) (serror 'simple-reader-error stream "a number must be given between # and #")) (multiple-value-bind (object presentp) (gethash arg *references*) (if presentp object (serror 'simple-reader-error stream "undefined label #~D#" arg)))) (defun reader-dispatch-macro-label-definition (stream arg sub-char) "Standard #= dispatch macro reader." (declare (ignore sub-char)) (when (null arg) (serror 'simple-reader-error stream "a number must be given between # and =")) (multiple-value-bind (object presentp) (gethash arg *references*) (if presentp (serror 'simple-reader-error stream "label #~D=~S already defined as ~S" (read stream t nil t) arg object) (setf (gethash arg *references*) (read stream t nil t))))) (defun eval-feature (expression stream) "Evaluates a feature expression as a BOOLEAN." (flet ((illegal-feature () (serror 'simple-reader-error stream "illegal feature ~S" expression)) (eval-term (term) (eval-feature term stream))) (cond ;; Some implementations accept any atom: ((atom expression) (not (null (member expression *features*)))) (t (case (first expression) ((:not) (if (cddr expression) (illegal-feature) (not (eval-feature (second expression) stream)))) ((:and) (every (function eval-term) (rest expression))) ((:or) (some (function eval-term) (rest expression))) (t (illegal-feature))))))) (defun read-feature (stream affirmativep) "Reads a feature expression, and possibly eats one following sexp" (let ((expression (let ((*package* (find-package "KEYWORD")) (*read-suppress* nil)) (read stream nil stream t)))) ;; (print `(:read-feature ,expression)) (when (eq expression stream) (serror 'simple-end-of-file stream "EOF in ~S while reading the feature expression" stream)) (unless (funcall (if affirmativep (function identity) (function not)) (eval-feature expression stream)) ;; (print `(:read-feature ,expression false we eat)) (let ((*read-suppress* t)) ;; (print `(:read-feature ,(read stream t nil nil) :eaten)) (read stream t nil nil))) (values))) (defun reader-dispatch-macro-feature (stream arg sub-char) "Standard #+ dispatch macro reader." (declare (ignore sub-char arg)) (read-feature stream t)) (defun reader-dispatch-macro-not-feature (stream arg sub-char) "Standard #- dispatch macro reader." (declare (ignore sub-char arg)) (read-feature stream nil)) ;; (defparameter *rt* ;; (let ((rt (copy-readtable))) ;; (set-dispatch-macro-character ;; #\# #\+ (function reader-dispatch-macro-feature) rt) ;; (set-dispatch-macro-character ;; #\# #\- (function reader-dispatch-macro-not-feature) rt) ;; rt)) (defun reader-dispatch-macro-read-eval (stream arg sub-char) "Standard #. dispatch macro reader." (declare (ignore sub-char arg)) (if *read-eval* (eval (read stream t nil t)) (serror 'simple-reader-error stream "*READ-EVAL* = NIL does not allow the evaluation of ~S" (read stream t nil t)))) (defun reader-dispatch-macro-uninterned (stream arg sub-char) "Standard #: dispatch macro reader." (declare (ignore sub-char arg)) (multiple-value-bind (tokenp token) (read-token stream t nil t nil nil *readtable*) (if tokenp (make-symbol (token-text token)) (serror 'simple-reader-error stream "token expected after #:")))) (defun reader-dispatch-macro-unreadable (stream arg sub-char) "Standard #< dispatch macro reader." (declare (ignore sub-char arg)) (serror 'simple-reader-error stream "objects printed as #<...> cannot be read back in")) (defun reader-dispatch-macro-COMMENT (stream arg sub-char) "Standard #| dispatch macro reader." (declare (ignore sub-char arg)) ;; #|...|# is treated as a comment by the reader. It must be balanced ;; with respect to other occurrences of #| and |#, but otherwise may ;; contain any characters whatsoever. (loop :with level = 1 :with state = :normal :until (zerop level) :do (case state ((:normal) (case (read-char stream t nil t) ((#\#) (setf state :sharp)) ((#\|) (setf state :pipe)))) ((:sharp) (case (read-char stream t nil t) ((#\#)) ((#\|) (incf level) (setf state :normal)) (otherwise (setf state :normal)))) ((:pipe) (case (read-char stream t nil t) ((#\#) (decf level) (setf state :normal)) ((#\|)) (otherwise (setf state :normal)))))) (values)) (defun reader-dispatch-macro-function (stream arg sub-char) "Standard #' dispatch macro reader." (declare (ignore sub-char arg)) `(cl:function ,(read stream t nil t))) (defun reader-dispatch-macro-vector (stream arg sub-char) "Standard #( dispatch macro reader." (declare (ignore sub-char)) ;; If an unsigned decimal integer appears between the # and (, it ;; specifies explicitly the length of the vector. The consequences are ;; undefined if the number of objects specified before the closing ) ;; exceeds the unsigned decimal integer. If the number of objects ;; supplied before the closing ) is less than the unsigned decimal ;; integer but greater than zero, the last object is used to fill all ;; remaining elements of the vector. The consequences are undefined if ;; the unsigned decimal integer is non-zero and number of objects ;; supplied before the closing ) is zero. For example, (if arg (loop :with vector = (make-array arg) :for i :from 0 :below arg :until (char= #\) (peek-char t stream t nil t)) :do (setf (aref vector i) (read stream t nil t)) :finally (progn (if (>= i arg) (let ((*read-suppress* t)) ;; TODO: serror "vector is longer than the explicitly given length" (loop :until (char= #\) (peek-char t stream t nil t)) :do (read stream t nil t))) (loop :with last-item = (aref vector (1- i)) :for j :from i :below arg :do (setf (aref vector j) last-item))) (return vector))) (loop :with vector = (make-array 1024 :adjustable t :fill-pointer 0) :until (char= #\) (peek-char t stream t nil t)) :do (vector-push-extend (read stream t nil t) vector) :finally (return (copy-seq vector))))) (defun reader-dispatch-macro-bit-vector (stream arg sub-char) "Standard #* dispatch macro reader. URL: http://www.lispworks.com/documentation/HyperSpec/Body/02_dhd.htm " (declare (ignore sub-char)) ;; Syntax: #*<<bits>> ;; ;; A simple bit vector is constructed containing the indicated bits (0's ;; and 1's), where the leftmost bit has index zero and the subsequent ;; bits have increasing indices. ;; ;; Syntax: #<<n>>*<<bits>> ;; ;; With an argument n, the vector to be created is of length n. If the ;; number of bits is less than n but greater than zero, the last bit is ;; used to fill all remaining bits of the bit vector. ;; ;; The notations #* and #0* each denote an empty bit vector. ;; ;; Regardless of whether the optional numeric argument n is provided, the ;; token that follows the asterisk is delimited by a normal token ;; delimiter. However, (unless the value of *read-suppress* is true) an ;; error of type reader-error is signaled if that token is not composed ;; entirely of 0's and 1's, or if n was supplied and the token is ;; composed of more than n bits, or if n is greater than one, but no bits ;; were specified. Neither a single escape nor a multiple escape is ;; permitted in this token. (if arg (loop :with vector = (make-array arg :element-type 'bit :initial-element 0) :for i :from 0 :below arg :while (let ((ch (peek-char nil stream nil nil t))) (and ch (not (token-delimiter-p ch)))) :do (setf (aref vector i) (digit-char-p (read-char stream nil nil t))) :finally (progn (cond ((>= i arg) (let ((*read-suppress* t)) (loop :while (let ((ch (peek-char nil stream nil nil t))) (and ch (not (token-delimiter-p ch)))) :do (read-char stream nil nil t)))) ((plusp (aref vector (1- i))) (loop :for j :from i :below arg :do (setf (aref vector j) 1)))) (return vector))) (loop :with vector = (make-array 1024 :adjustable t :fill-pointer 0 :element-type 'bit :initial-element 0) :while (let ((ch (peek-char nil stream nil nil t))) (and ch (not (token-delimiter-p ch)))) ;; TODO: Check the behavior when the character is not a bit. :do (vector-push-extend (digit-char-p (read-char stream nil nil t)) vector) :finally (return (copy-seq vector))))) (defun reader-dispatch-macro-CHAR (stream arg sub-char) "Standard #\\ dispatch macro reader." (declare (ignore sub-char arg)) (read-char stream t nil t)) (defun reader-dispatch-macro-ARRAY (stream arg sub-char) "Standard #A dispatch macro reader." (declare (ignore sub-char)) (let ((initial-contents (read stream t nil t))) (labels ((collect-dimensions (n contents dimensions) (if (zerop n) (nreverse dimensions) (collect-dimensions (1- n) (first contents) (cons (length contents) dimensions))))) ;; TODO: we rely on make-array to raise some errors that it may not raise... (make-array (collect-dimensions (or arg 1) initial-contents '()) :initial-contents initial-contents)))) (defun read-rational-in-base (stream arg sub-char *read-base*) " DO: Read a rational number in the base specified. RETURN: The rational read. " (when arg (serror stream "no number allowed between # and ~A" sub-char)) (let ((value (read stream t nil t))) (if (rationalp value) value (serror stream "token \"~A\" after #~A is not a rational number in base ~D" sub-char *read-base*)))) (defun reader-dispatch-macro-BINARY (stream arg sub-char) "Standard #B dispatch macro reader." (read-rational-in-base stream arg sub-char 2.)) (defun reader-dispatch-macro-OCTAL (stream arg sub-char) "Standard #O dispatch macro reader." (read-rational-in-base stream arg sub-char 8.)) (defun reader-dispatch-macro-HEXADECIMAL (stream arg sub-char) "Standard #X dispatch macro reader." (read-rational-in-base stream arg sub-char 16.)) (defun reader-dispatch-macro-RADIX (stream arg sub-char) "Standard #R dispatch macro reader." (unless arg (serror stream "the number base must be given between # and ~A" sub-char)) (read-rational-in-base stream nil sub-char arg)) ;; Copied from com.informatimago.common-lisp.list to avoid package use loop. (defun proper-list-p (object) " RETURN: whether object is a proper list NOTE: terminates with any kind of list, dotted, circular, etc. " (labels ((proper (current slow) (cond ((null current) t) ((atom current) nil) ((null (cdr current)) t) ((atom (cdr current)) nil) ((eq current slow) nil) (t (proper (cddr current) (cdr slow)))))) (and (listp object) (proper object (cons nil object))))) (defun reader-dispatch-macro-COMPLEX (stream arg sub-char) "Standard #C dispatch macro reader." (declare (ignore sub-char arg)) (let ((c (read stream t nil t))) (unless (and (proper-list-p c) (= 2 (length c)) (every (function realp) c)) (serror 'simple-reader-error stream "bad syntax for complex number: #C~S" c)) (complex (first c) (second c)))) (defun reader-dispatch-macro-PATHNAME (stream arg sub-char) "Standard #P dispatch macro reader." (declare (ignore sub-char arg)) (pathname (read stream t nil t))) (defun reader-dispatch-macro-STRUCTURE (stream arg sub-char) "Standard #S dispatch macro reader." (declare (ignore sub-char arg)) (let* ((data (read stream t nil t)) (constructor (intern (format nil "MAKE-~A" (first data)))) (arguments (loop :with keyword-package = (find-package "KEYWORD") :for (k v) :on (rest data) :by (function cddr) :collect (intern (string k) keyword-package) :collect v))) (apply constructor arguments))) ;;;; ;;;; (defun test-proper-list-p () (assert (every (function identity) (mapcar (lambda (test) (eq (first test) (proper-list-p (second test)))) '((nil x) (t ()) (t (a)) (t (a b)) (t (a b c)) (t (a b c d)) (nil (a . x)) (nil (a b . x)) (nil (a b c . x)) (nil (a b c d . x)) (nil #1=(a . #1#)) (nil #2=(a b . #2#)) (nil #3=(a b c . #3#)) (nil #4=(a b c d . #4#)) (nil (1 . #1#)) (nil (1 2 . #1#)) (nil (1 2 3 . #1#)) (nil (1 2 3 4 . #1#)) (nil (1 . #2#)) (nil (1 2 . #2#)) (nil (1 2 3 . #2#)) (nil (1 2 3 4 . #2#)) (nil (1 . #3#)) (nil (1 2 . #3#)) (nil (1 2 3 . #3#)) (nil (1 2 3 4 . #3#)) (nil (1 . #4#)) (nil (1 2 . #4#)) (nil (1 2 3 . #4#)) (nil (1 2 3 4 . #4#))))))) ;;;; (defmethod initialize-instance :after ((self readtable) &rest rest &key &allow-other-keys) (unless (getf rest :syntax-table) (macrolet ((smc (&rest clauses) `(progn ,@(mapcar (lambda (clause) `(set-macro-character ,(first clause) (function ,(second clause)) ,(third clause) self)) clauses)))) (smc (#\; reader-macro-line-comment nil) (#\" reader-macro-string nil) (#\' reader-macro-quote nil) (#\` reader-macro-backquote nil) (#\, reader-macro-comma nil) (#\( reader-macro-left-parenthesis nil) (#\) reader-macro-error-start nil))) (macrolet ((dmc (&rest clauses) `(progn ,@(mapcar (lambda (clause) `(set-dispatch-macro-character ,(first clause) ,(second clause) (function ,(third clause)) self)) clauses)))) (make-dispatch-macro-character #\# t self) (dmc (#\# #\Space reader-dispatch-macro-error-invalid) (#\# #\Newline reader-dispatch-macro-error-invalid) (#\# #\# reader-dispatch-macro-label-reference) (#\# #\' reader-dispatch-macro-function) (#\# #\( reader-dispatch-macro-vector) (#\# #\* reader-dispatch-macro-bit-vector) (#\# #\+ reader-dispatch-macro-feature) (#\# #\- reader-dispatch-macro-not-feature) (#\# #\. reader-dispatch-macro-read-eval) (#\# #\: reader-dispatch-macro-uninterned) (#\# #\< reader-dispatch-macro-unreadable) (#\# #\= reader-dispatch-macro-label-definition) (#\# #\A reader-dispatch-macro-array) (#\# #\B reader-dispatch-macro-binary) (#\# #\C reader-dispatch-macro-complex) (#\# #\O reader-dispatch-macro-octal) (#\# #\P reader-dispatch-macro-pathname) (#\# #\R reader-dispatch-macro-radix) (#\# #\S reader-dispatch-macro-structure) (#\# #\X reader-dispatch-macro-hexadecimal) (#\# #\\ reader-dispatch-macro-char) (#\# #\| reader-dispatch-macro-comment) ;; clisp extensions: ;; (#\# #\! reader-dispatch-macro-executable) ;; (#\# #\" reader-dispatch-macro-clisp-pathname) ;; (#\# #\, reader-dispatch-macro-load-eval) ;; (#\# #\Y SYSTEM::CLOSURE-READER) )))) (setf *standard-readtable* (copy-readtable nil) *readtable* (copy-readtable nil)) ;; or could go to UTILITIES, but this version will run on our own readtables... (defun list-all-macro-characters (&optional (*readtable* *readtable*)) " RETURN: A list of all the macro and dispatch-macro characters in the readtable. " (loop :with results = '() :for code :from 0 :below CHAR-CODE-LIMIT :for ch = (code-char code) :do (multiple-value-bind (fun ntp) (get-macro-character ch) (when (or fun ntp) (push (list ch fun ntp (when (handler-case (progn (get-dispatch-macro-character ch #\a) t) (error () nil)) (loop :for code :from 0 :below char-code-limit :for sub = (code-char code) :for fun = (get-dispatch-macro-character ch sub) :when fun :collect (list sub fun)))) results))) :finally (return results))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Tests ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; #| (defun test-extract () (let ((test-cases '(() ("Result") ("Doc" "Result") ((declare (ignore it))) ((declare (ignore it)) "Result") ((declare (ignore it)) "Doc" "Result") ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it)) "Result") ((declare (ignore it)) "Doc" (declare (ignore it))) ((declare (ignore it)) (declare (ignore it)) "Doc" "Result") ((declare (ignore it)) "Doc" (declare (ignore it)) "Result") ((declare (ignore it)) "Doc" "Illegal" (declare (ignore it)) "Result") ("Doc" (declare (ignore it)) "Result") ("Doc" (declare (ignore it)) (declare (ignore it))) ("Doc" (declare (ignore it)) (declare (ignore it)) "Result") ("Doc" (declare (ignore it)) "Illegal" (declare (ignore it)) "Result") ))) (assert (equalp '(NIL NIL "Doc" NIL NIL "Doc" NIL NIL "Doc" "Doc" "Doc" "Doc" "Doc" "Doc" "Doc" "Doc" ) (mapcar (function extract-documentation) test-cases))) (assert (equalp '(nil nil nil ((declare (ignore it))) ((declare (ignore it))) ((declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it))) ;; "Illegal" ((declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)) (declare (ignore it))) ((declare (ignore it)))) ;; "Illegal" (mapcar (function extract-declarations) test-cases))) (assert (equalp '((nil) ("Result") ("Result") ((declare (ignore it))) ("Result") ("Result") ((declare (ignore it))) ("Result") ((declare (ignore it))) ("Result") ("Result") ("Illegal" (declare (ignore it)) "Result") ("Result") ((declare (ignore it))) ("Result") ("Illegal" (declare (ignore it)) "Result")) (mapcar (function extract-body) test-cases))) :success)) (defun test-reader () (let ((*read-base* 10) (*read-eval* t) (*read-suppress* nil) (*read-default-float-format* 'single-float)) (dolist (test '( ;; integer ::= [sign] digit+ (nil "0" 0.) (nil "1" 1.) (nil "2" 2.) (nil "9" 9.) (nil "10" 10.) (nil "11" 11.) (nil "12" 12.) (nil "19" 19.) (((*read-base* 3.)) "0" 0.) (((*read-base* 3.)) "1" 1.) (((*read-base* 3.)) "2" 2.) (((*read-base* 3.)) "9" |9|) (((*read-base* 3.)) "10" 3.) (((*read-base* 3.)) "11" 4.) (((*read-base* 3.)) "13" |13|) (nil "-0" -0.) (nil "-1" -1.) (nil "-2" -2.) (nil "-9" -9.) (nil "-10" -10.) (nil "-11" -11.) (nil "-12" -12.) (nil "-19" -19.) (((*read-base* 3.)) "-0" -0.) (((*read-base* 3.)) "-1" -1.) (((*read-base* 3.)) "-2" -2.) (((*read-base* 3.)) "-9" |-9|) (((*read-base* 3.)) "-10" -3.) (((*read-base* 3.)) "-11" -4.) (((*read-base* 3.)) "-13" |-13|) (nil "+0" +0.) (nil "+1" +1.) (nil "+2" +2.) (nil "+9" +9.) (nil "+10" +10.) (nil "+11" +11.) (nil "+12" +12.) (nil "+19" +19.) (((*read-base* 3.)) "+0" +0.) (((*read-base* 3.)) "+1" +1.) (((*read-base* 3.)) "+2" +2.) (((*read-base* 3.)) "+9" |+9|) (((*read-base* 3.)) "+10" +3.) (((*read-base* 3.)) "+11" +4.) (((*read-base* 3.)) "+13" |+13|) ;; integer ::= [sign] decimal-digit+ decimal-point (nil "0." 0.) (nil "1." 1.) (nil "2." 2.) (nil "9." 9.) (nil "10." 10.) (nil "11." 11.) (nil "12." 12.) (nil "19." 19.) (((*read-base* 3.)) "0." 0.) (((*read-base* 3.)) "1." 1.) (((*read-base* 3.)) "2." 2.) (((*read-base* 3.)) "9." 9.) (((*read-base* 3.)) "10." 10.) (((*read-base* 3.)) "11." 11.) (((*read-base* 3.)) "13." 13.) (nil "-0." -0.) (nil "-1." -1.) (nil "-2." -2.) (nil "-9." -9.) (nil "-10." -10.) (nil "-11." -11.) (nil "-12." -12.) (nil "-19." -19.) (((*read-base* 3.)) "-0." -0.) (((*read-base* 3.)) "-1." -1.) (((*read-base* 3.)) "-2." -2.) (((*read-base* 3.)) "-9." -9.) (((*read-base* 3.)) "-10." -10.) (((*read-base* 3.)) "-11." -11.) (((*read-base* 3.)) "-13." -13.) (nil "+0." +0.) (nil "+1." +1.) (nil "+2." +2.) (nil "+9." +9.) (nil "+10." +10.) (nil "+11." +11.) (nil "+12." +12.) (nil "+19." +19.) (((*read-base* 3.)) "+0." +0.) (((*read-base* 3.)) "+1." +1.) (((*read-base* 3.)) "+2." +2.) (((*read-base* 3.)) "+9." +9.) (((*read-base* 3.)) "+10." +10.) (((*read-base* 3.)) "+11." +11.) (((*read-base* 3.)) "+13." +13.) ;; ratio ::= [sign] {digit}+ slash {digit}+ (nil "0/0" nil division-by-zero) (nil "1/0" nil division-by-zero) (nil "10/000" nil division-by-zero) (nil "0/1" 0) (nil "1/1" 1) (nil "2/1" 2) (nil "20/10" 2) (nil "200/100" 2) (nil "0/2" 0) (nil "1/2" 1/2) (nil "0/20" 0) (nil "10/20" 1/2) (nil "100/200" 1/2) (nil "001/2" 1/2) (nil "000/20" 0) (nil "010/20" 1/2) (nil "100/200" 1/2) (nil "12345/54321" 12345/54321) (nil "+0/0" nil division-by-zero) (nil "+1/0" nil division-by-zero) (nil "+10/000" nil division-by-zero) (nil "+0/1" 0) (nil "+1/1" 1) (nil "+2/1" 2) (nil "+20/10" 2) (nil "+200/100" 2) (nil "+0/2" 0) (nil "+1/2" 1/2) (nil "+0/20" 0) (nil "+10/20" 1/2) (nil "+100/200" 1/2) (nil "+001/2" 1/2) (nil "+000/20" 0) (nil "+010/20" 1/2) (nil "+100/200" 1/2) (nil "+12345/54321" 12345/54321) (nil "-0/0" nil division-by-zero) (nil "-1/0" nil division-by-zero) (nil "-10/000" nil division-by-zero) (nil "-0/1" -0) (nil "-1/1" -1) (nil "-2/1" -2) (nil "-20/10" -2) (nil "-200/100" -2) (nil "-0/2" -0) (nil "-1/2" -1/2) (nil "-0/20" -0) (nil "-10/20" -1/2) (nil "-100/200" -1/2) (nil "-001/2" -1/2) (nil "-000/20" -0) (nil "-010/20" -1/2) (nil "-100/200" -1/2) (nil "-12345/54321" -12345/54321) ;;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ exponent ;;; float ::= [sign] {decimal-digit}* decimal-point {decimal-digit}+ ;;; float ::= [sign] {decimal-digit}+ exponent ;;; float ::= [sign] {decimal-digit}+ decimal-point {decimal-digit}* exponent ;;; exponent ::= exponent-marker [sign] {digit}+ ;;; ;;; consing-dot ::= dot ;;; ;;; symbol ::= symbol-name ;;; | package-marker symbol-name ;;; | package-marker package-marker symbol-name ;;; | package-name package-marker symbol-name ;;; | package-name package-marker package-marker symbol-name ) :success) (multiple-value-bind (val err) (ignore-errors (eval `(progv ',(mapcar (function first) (first test)) ',(mapcar (function second) (first test)) (read-from-string ,(second test))))) (assert (if (fourth test) (typep err (fourth test)) (eql val (third test))) nil "~S gives ~:[~S~;~:*~S~*~]; expected: ~S" `(let ,(first test) (read-from-string ,(second test))) err val (or (fourth test) (third test))))))) (defun test-cases (cases) (dolist (test cases :success) (destructuring-bind (expression expected-values expected-error) test (multiple-value-bind (actual-values actual-error) (ignore-errors (multiple-value-list (eval expression))) (assert (or (and (null expected-error) (null actual-error)) (typep actual-error expected-error)) () "Testing ~S, expected ~ ~:[no error~;an error of type ~:*~S~], ~ got this error: ~A" expression expected-error actual-error) (assert (equalp expected-values actual-values) () "Testing ~S, expected ~S, got ~S" expression expected-values actual-values))))) (defmacro tests (&rest cases) `(test-cases ',cases)) (test-extract) (test-reader) (let ((*features* '(:a :b :c))) (tests ((eval-feature ':a *standard-input*) (t) nil) ((eval-feature ':z *standard-input*) (nil) nil) ((eval-feature '42 *standard-input*) (nil) nil) ((eval-feature '(:not :a) *standard-input*) (nil) nil) ((eval-feature '(:not :z) *standard-input*) (t) nil) ((eval-feature '(:not :a :b) *standard-input*) () reader-error) ((eval-feature '(:and) *standard-input*) (t) nil) ((eval-feature '(:and :a) *standard-input*) (t) nil) ((eval-feature '(:and :a :b) *standard-input*) (t) nil) ((eval-feature '(:and :a :c) *standard-input*) (t) nil) ((eval-feature '(:and :a :z) *standard-input*) (nil) nil) ((eval-feature '(:and :y :z) *standard-input*) (nil) nil) ((eval-feature '(:or) *standard-input*) (nil) nil) ((eval-feature '(:or :a) *standard-input*) (t) nil) ((eval-feature '(:or :a :b) *standard-input*) (t) nil) ((eval-feature '(:or :a :c) *standard-input*) (t) nil) ((eval-feature '(:or :a :z) *standard-input*) (t) nil) ((eval-feature '(:or :y :z) *standard-input*) (nil) nil) ((eval-feature '(:or (:and :a (:not :z)) (:and (:not :a) :z)) *standard-input*) (t) nil) ((eval-feature '(:and (:or :a (:not :z)) (:or (:not :a) :z)) *standard-input*) (nil) nil) ((eval-feature '(:and :a :b (:or :y :z (:not :a))) *standard-input*) (nil) nil) ((eval-feature '(:and :a :b (:or :y :z (:not 42))) *standard-input*) (t) nil))) (tests ((read-from-string "()") (() 2) nil) ((read-from-string "(a)") ((a) 3) nil) ((read-from-string "(a b)") ((a b) 5) nil) ((read-from-string "(a b c)") ((a b c) 7) nil) ((read-from-string "(a b c d)") ((a b c d) 9) nil) ((read-from-string "(a b c . d)") ((a b c . d) 11) nil) ((read-from-string "(a b c . d e)") nil reader-error) ((read-from-string "(a b c . . d)") nil reader-error) ((read-from-string "(a b c . d .)") nil reader-error) ((let ((*features* '(:test))) (read-from-string "(a b c #+test d)")) ((a b c d) 16) nil) ((let ((*features* '(:test))) (read-from-string "(a b c #-test d)")) ((a b c) 16) nil) ((let ((*features* '(:test))) (read-from-string "(a b c . #+test d)")) ((a b c . d) 18) nil) ((let ((*features* '(:test))) (read-from-string "(a b c . #-test d e)")) ((a b c . e) 20) nil) ((let ((*features* '(:test))) (read-from-string "(a b c #+test . d)")) ((a b c . d) 18) nil) ((let ((*features* '(:test))) (read-from-string "(a b c #-test . d)")) ((a b c d) 18) nil)) (tests ((let ((*features* (quote (:a :b)))) (read-from-string "(#+#1=(or a b) #1#)")) (((:or :a :b)) 19) nil) ((let ((*features* (quote (:a :b)))) (read-from-string "(#+#.(cl:if (cl:eq :a (cl:first cl:*features*)) '(:and) '(:or)) equal)")) ((equal) 70) nil)) #- (and) (tests ((let ((*features* (quote (:a :b)))) (read-from-string "#+#1=(or a b) #1#")) ((:OR :A :B) 44) nil)) (tests ((read-from-string "(#*101111 #6*10111110101 #6*101111 #6*1010 #6*1011 #* #0*11010)") ((#*101111 #*101111 #*101111 #*101000 #*101111 #* #*) 63) nil) ((read-from-string "(#b10111101 #o275 #xbd #36r59)") ((189 189 189 189) 30) nil) ((read-from-string "#P\"/tmp/a.c\"") (#.(make-pathname :directory '(:absolute "tmp") :name "a" :type "c" :version nil :case :local) 12) nil)) #- (and) (tests ((progn (defstruct s a b c) (read-from-string "#S(s a 1 b 2 c 3)")) (#S(S :A 1 :B 2 :C 3) 17) nil)) (defun check-symbols () (dolist (sym '("READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*") :success) (let ((s-here (find-symbol sym *package*)) (s-cl (find-symbol sym "COMMON-LISP"))) (assert (not (eq s-here s-cl)) () "The symbol ~S is interned both in COMMON-LISP and in ~A" s-here (package-name *package*))))) (check-symbols) |# ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; The End ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
87,948
Common Lisp
.lisp
1,901
35.534982
96
0.534209
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
2d8ca5867480a08d589bf8ebaba42f83109cf98895afa75ab7b1a72dde78c562
40,312
[ -1 ]
40,313
source-text.lisp
hu-dwim_hu_dwim_reader/source/source-text.lisp
;;;;************************************************************************** ;;;;FILE: source-text.lisp ;;;;LANGUAGE: Common-Lisp ;;;;SYSTEM: Common-Lisp ;;;;USER-INTERFACE: NONE ;;;;DESCRIPTION ;;;; ;;;; This package exports functions to read and manipulate ;;;; Common Lisp sources. Most of the text source properties ;;;; are kept (file position, line number, comments, feature ;;;; tests, etc), while no package is created and no symbol is ;;;; interned (TODO: but perhaps keywords?) ;;;; ;;;;AUTHORS ;;;; <PJB> Pascal Bourguignon <[email protected]> ;;;;MODIFICATIONS ;;;; 2007-03-07 <PJB> Created. ;;;;BUGS ;;;;LEGAL ;;;; GPL ;;;; ;;;; Copyright Pascal Bourguignon 2007 - 2007 ;;;; ;;;; This program is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU General Public License ;;;; as published by the Free Software Foundation; either version ;;;; 2 of the License, or (at your option) any later version. ;;;; ;;;; This program is distributed in the hope that it will be ;;;; useful, but WITHOUT ANY WARRANTY; without even the implied ;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR ;;;; PURPOSE. See the GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public ;;;; License along with this program; if not, write to the Free ;;;; Software Foundation, Inc., 59 Temple Place, Suite 330, ;;;; Boston, MA 02111-1307 USA ;;;;************************************************************************** (in-package "COMMON-LISP-USER") (defpackage "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT" (:nicknames "SOURCE-TEXT") (:use "COMMON-LISP" "COM.INFORMATIMAGO.COMMON-LISP.READER") (:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.READER" "READTABLE" "COPY-READTABLE" "MAKE-DISPATCH-MACRO-CHARACTER" "READ" "READ-PRESERVING-WHITESPACE" "READ-DELIMITED-LIST" "READ-FROM-STRING" "READTABLE-CASE" "READTABLEP" "SET-DISPATCH-MACRO-CHARACTER" "GET-DISPATCH-MACRO-CHARACTER" "SET-MACRO-CHARACTER" "GET-MACRO-CHARACTER" "SET-SYNTAX-FROM-CHAR" "WITH-STANDARD-IO-SYNTAX" "*READ-BASE*" "*READ-DEFAULT-FLOAT-FORMAT*" "*READ-EVAL*" "*READ-SUPPRESS*" "*READTABLE*") (:export "BUILD-LINE-INDEX" "GET-LINE-AND-COLUMN" ;; ---- ;; "*SOURCE-READTABLE*" "SOURCE-SIGNAL-ERRORS*" "SOURCE-READ" "SOURCE-READ-FROM-STRING" "SOURCE-OBJECT" "SOURCE-OBJECT-FILE" "SOURCE-OBJECT-POSITION" "SOURCE-OBJECT-TEXT" "SOURCE-TOKEN" "SOURCE-TOKEN-TEXT" "SOURCE-TOKEN-TRAITS" "SOURCE-LEXICAL-ERROR" "SOURCE-LEXICAL-ERROR-ERROR" "MACRO-CHARACTER-MIXIN" "MACRO-CHARACTER" "DISPATCH-MACRO-CHARACTER-MIXIN" "DISPATCH-MACRO-ARGUMENT" "DISPATCH-MACRO-SUB-CHARACTER" "COMMENT" "COMMENT-TEXT" "SOURCE-FORM" "SOURCE-FORMAT" "SOURCE-FORMAT-STRING" "SOURCE-PRINT" "SOURCE-STRING" "SOURCE-SEMICOLON-COMMENT" "SOURCE-WHITESPACE" "SOURCE-WHITESPACE-VALUE" "SOURCE-STRING" "SOURCE-STRING-VALUE" "SOURCE-SUBFORM" "SOURCE-OBJECT-SUBFORM" "SOURCE-QUOTE" "SOURCE-BACKQUOTE" "SOURCE-UNQUOTE" "SOURCE-SPLICE" "SOURCE-SEQUENCE" "SOURCE-SEQUENCE-ELEMENTS" "SOURCE-LIST" "SOURCE-LABEL-REFERENCE" "SOURCE-LABEL-REFERENCE-LABEL" "SOURCE-LABEL-DEFINITION" "SOURCE-LABEL-DEFINITION-LABEL" "SOURCE-LABEL-DEFINITION-FORM" "SOURCE-FEATURE" "SOURCE-NOT-FEATURE" "SOURCE-READ-EVAL" "SOURCE-TOKEN" "SOURCE-OBJECT-TOKEN" "SOURCE-SHARP-PIPE-COMMENT" "SOURCE-FUNCTION" "SOURCE-VECTOR" "SOURCE-BIT-VECTOR" "SOURCE-CHARACTER" "SOURCE-CHARACTER" "SOURCE-ARRAY" "SOURCE-NUMBER" "SOURCE-NUMBER-VALUE" "SOURCE-SYMBOL" "SOURCE-SYMBOL-VALUE" "SOURCE-BASE-NUMBER" "SOURCE-BASE-NUMBER-BASE" "SOURCE-BASE-NUMBER-SPECIFIC" "SOURCE-COMPLEX" "SOURCE-PATHNAME" "SOURCE-STRUCTURE" ;; ---- ;; "SOURCE-ATOM-P" "MAP-SOURCE-STREAM" "MAP-SOURCE-FILE" ) (:documentation " This package exports functions to read and manipulate Common Lisp sources. Most of the text source properties are kept (file position, line number, comments, feature tests, etc), while no package is created and no symbol is interned. Copyright Pascal J. Bourguignon 2007 - 2007 This package is provided under the GNU General Public License. See the source file for details.")) (in-package "COM.INFORMATIMAGO.COMMON-LISP.SOURCE-TEXT") ;;; ---------------------------------------- ;;; (defun build-line-index (file-path &key (external-format :default)) (with-open-file (input file-path :external-format external-format) (let ((line-positions (make-array 0 :adjustable t :fill-pointer 0 :element-type '(integer 0)))) (loop :for pos = (file-position input) :do (vector-push-extend pos line-positions) :while (peek-char #\newline input nil nil) :do (read-char input) :finally (return line-positions))))) ;;; Copied from utility.lisp to avoid package loops (defun dichotomy (vector value compare &key (start 0) (end (length vector)) (key (function identity))) " PRE: entry is the element to be searched in the table. (<= start end) RETURN: (values found index order) POST: (<= start index end) +-------------------+----------+-------+----------+----------------+ | Case | found | index | order | Error | +-------------------+----------+-------+----------+----------------+ | x < a[min] | FALSE | min | less | 0 | | a[i] = x | TRUE | i | equal | 0 | | a[i] < x < a[i+1] | FALSE | i | greater | 0 | | a[max] < x | FALSE | max | greater | 0 | +-------------------+----------+-------+----------+----------------+ " (let* ((curmin start) (curmax end) (index (truncate (+ curmin curmax) 2)) (order (funcall compare value (funcall key (aref vector index)))) ) (loop :while (and (/= 0 order) (/= curmin index)) :do (if (< order 0) (setf curmax index) (setf curmin index)) (setf index (truncate (+ curmin curmax) 2)) (setf order (funcall compare value (funcall key (aref vector index))))) (when (and (< start index) (< order 0)) (setf order 1) (decf index)) (assert (or (< (funcall compare value (funcall key (aref vector index))) 0) (and (> (funcall compare value (funcall key (aref vector index))) 0) (or (>= (1+ index) end) (< (funcall compare value (funcall key (aref vector (1+ index)))) 0))) (= (funcall compare value (funcall key (aref vector index))) 0))) (values (= order 0) index order))) (defun get-line-and-column (line-positions pos) (multiple-value-bind (foundp index order) (dichotomy line-positions pos (lambda (a b) (cond ((< a b) -1) ((> a b) 1) (t 0)))) (declare (ignore foundp order)) ;; The case x < a[min] cannot occur since (= 0 (aref line-positions 0)) ;; and (<= 0 pos) (values index (- pos (aref line-positions index))))) ;;; ---------------------------------------- ;;; (defvar *stream* nil "The source stream.") (defvar *file* nil "The pathname of the source file.") (defvar *start* nil "The start file position of the current reader dispatch macro character.") (defvar *macro-character* nil "The current dispatch macro character.") ;;; ---------------------------------------- ;;; ;;; ---------------------------------------- ;;; (defclass source-object () ((parent :accessor source-object-parent :initarg :parent :initform nil :type (or null source-object)) (file :accessor source-object-file :initarg :file :initform nil :type (or null string pathname)) (position :accessor source-object-position :initarg :position :initform nil :type (or null integer) :documentation "This are file-positions. We don't keep track of line/column, since this can be done by reading the source file again, as a character file instead of a sexp file..") (text :accessor source-object-text :initarg :text :initform nil :type (or null string)) (form :accessor source-object-form :initarg :form :initform nil :type t))) (defmethod print-object ((self source-object) stream) (if *print-readably* (format stream "~A" (source-object-text self)) (print-unreadable-object (self stream :type t :identity t))) self) ;;; ---------------------------------------- ;;; (defun read-string-between-file-positions (stream start end) " PRE: (eq 'character (stream-element-type stream)) and START and END are file positions of this STREAM. RETURN: A string containing the characters read between the START and END file positions in the STREAM. POST: (= end (file-position stream)) " (let ((buffer (make-array (- end start) :element-type 'character :fill-pointer 0))) (file-position stream start) (loop :while (< (file-position stream) end) :do (vector-push (read-char stream) buffer) ;; We could use copy-seq to return a simple-string, ;; but it's not worth it. :finally (unless (= (file-position stream) end) (warn "While reading beetween file positions, ~ reached a different file position: ~A < ~A" end (file-position stream))) (return buffer)))) (defvar *source-signal-errors* nil " NIL ==> return source-lexical-error objects T ==> signal the errors. ") (defun read-source-object (stream start class make-arguments) " DO: Read a source-object instance, of class CLASS, and re-read the STREAM from START to the file position after reading the source-object instance, as SOURCE-OBJECT-TEXT. START: The file position in STREAM of the first character of the source object. The current file position may be beyond this START position, when we're called from a reader macro (1) or a reader dispatch macro (2+). MAKE-ARGUMENTS: A function returning a plist of keyword and values to be passed as argument to (make-instance class ...) This function should be doing the reading of the source-object. RETURN: A new source-object instance of class CLASS, or an instance of SOURCE-LEXICAL-ERROR in case of error (READER-ERROR). " (let* ((inst (handler-case (apply (function make-instance) (list* class :file (ignore-errors (pathname stream)) :position start (funcall make-arguments))) (end-of-file (err) (error err)) (error (err) (if *source-signal-errors* (error err) (make-instance 'source-lexical-error :file (ignore-errors (pathname stream)) :position start :error err)))))) (setf (source-object-text inst) (read-string-between-file-positions stream start (file-position stream))) inst)) (defmacro building-source-object (stream start class &rest args &key &allow-other-keys) " USAGE: (building-source-object stream *start* 'source-object-class :attribute (source-read stream t nil t) :other-attribute (read-line stream t nil t) #| ... |#) RETURN: the source-object-class instance build. DO: Keep track of the file position to seek back and read again the source, for the text attribute of the instance. " `(read-source-object ,stream ,start ,class (lambda () (list ,@args)))) ;;; ---------------------------------------- ;;; (defclass source-token (source-object) ((token :accessor source-token-text :initarg :token) (traits :accessor source-token-traits :initarg :traits))) (defun source-parse-token (token) " DO: Parse the lisp reader token and return a source token object. RETURN: okp ; the parsed lisp object if okp, or an error message if (not okp) " (multiple-value-bind (okp value) (reader::parse-token token) (values t (if okp (etypecase value (number (building-source-object *stream* *start* 'source-number :value value)) (symbol (building-source-object *stream* *start* 'source-symbol :value value))) (building-source-object *stream* *start* 'source-token :token (reader::token-text token) :traits (reader::token-traits token)))))) ;;; ---------------------------------------- ;;; (defclass source-lexical-error (source-object) ((error :accessor source-lexical-error-error :initarg :error :initform nil :type (or null condition)))) (defmethod print-object ((self source-lexical-error) stream) (if *print-readably* (call-next-method) (print-unreadable-object (self stream :type t :identity t) (format stream "in file ~S at position ~S: ~A" (source-object-file self) (source-object-position self) (source-lexical-error-error self)))) self) ;;; ---------------------------------------- ;;; (defmacro building-reader-macro-source-object (stream macro-character class &rest args &key &allow-other-keys) " DO: Calls BUILDING-SOURCE-OBJECT, keeping track of the file position of the MACRO-CHARACTER. MACRO-CHARACTER: The macro character that has been read (as passed to the reader macro). " `(building-source-object ,stream *start* ,class :macro-character ,macro-character ,@args)) ;;; ---------------------------------------- ;;; (defclass macro-character-mixin () ((macro-character :accessor macro-character :initarg :macro-character))) (defclass dispatch-macro-character-mixin (macro-character-mixin) ((argument :accessor dispatch-macro-argument :initarg :argument) (sub-character :accessor dispatch-macro-sub-character :initarg :sub-character))) ;;;--------------------------------------------- ;;; STANDARD READER MACRO FUNCTIONS ;;;--------------------------------------------- (defclass comment (source-object) ((comment :accessor comment-text :initarg :comment))) ;;; ---------------------------------------- ;;; (defclass source-semicolon-comment (comment macro-character-mixin) ()) (defun source-reader-macro-line-comment (stream ch) "Source reader ; macro reader." (building-reader-macro-source-object stream ch 'source-semicolon-comment :comment (read-line stream nil ""))) ;;; ---------------------------------------- ;;; (defclass source-whitespace (source-object macro-character-mixin) ((value :accessor source-whitespace-value :initarg :value :initform nil :type (or null string)))) (defun source-reader-macro-whitespace (stream ch) "Source reader #\Space macro reader." (building-reader-macro-source-object stream ch 'source-whitespace :value (loop with whitespace = (make-array 4 :element-type 'character :adjustable t :fill-pointer 0) for ch = (peek-char nil stream nil nil t) while (and ch (member ch '(#\Space #\Tab #\Newline) :test #'char=)) do (vector-push-extend (read-char stream nil nil t) whitespace) finally (return whitespace)))) ;;; ---------------------------------------- ;;; (defclass source-string (source-object macro-character-mixin) ((value :accessor source-string-value :initarg :value :initform nil :type (or null string)))) (defun source-reader-macro-string (stream delim) "Source reader \" macro reader." (building-reader-macro-source-object stream delim 'source-string :value (flet ((error-eof () (com.informatimago.common-lisp.reader::serror 'simple-end-of-file stream "input stream ~S ends within a string" stream))) (loop :named read-string :with rst = (readtable-syntax-table *readtable*) :with string = (make-array 64 :element-type 'character :adjustable t :fill-pointer 0) :for ch = (read-char stream nil nil t) :do (cond ((null ch) (error-eof)) ((eql ch delim) (return-from read-string string)) ((= (reader::character-syntax (reader::character-description rst ch)) reader::+cs-single-escape+) (let ((next (read-char stream nil nil))) (when (null next) (error-eof)) (vector-push-extend next string))) (t (vector-push-extend ch string))))))) ;;; ---------------------------------------- ;;; (defclass source-subform (source-object macro-character-mixin) ((subform :accessor source-object-subform :initarg :subform))) ;;; ---------------------------------------- ;;; (defclass source-quote (source-subform macro-character-mixin) ()) (defun source-reader-macro-quote (stream ch) "Source reader ' macro reader." (building-reader-macro-source-object stream ch 'source-quote :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-backquote (source-subform macro-character-mixin) ()) (defun source-reader-macro-backquote (stream ch) "Source reader ` macro reader." (building-reader-macro-source-object stream ch 'source-backquote :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-unquote (source-subform macro-character-mixin) ()) (defclass source-splice (source-subform macro-character-mixin) ()) (defun source-reader-macro-comma (stream ch) "Source reader , macro reader." (building-reader-macro-source-object stream ch (if (char= #\@ (peek-char nil stream t nil t)) 'source-splice 'source-unquote) :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-sequence (source-object) ((elements :accessor source-sequence-elements :initarg :elements :initform nil :type sequence :documentation " Works for conses, lists, and invalid stuff put in parentheses, like ( . . ) Dots are represented by a source-object, so they can appear even in invalid syntaxes. "))) (defclass source-list (source-sequence macro-character-mixin) ()) (defun source-reader-macro-left-parenthesis (stream ch) "Source reader ( macro reader." (building-reader-macro-source-object stream ch 'source-list :elements (loop :until (char= #\) (peek-char nil stream t nil t)) :collect (source-read stream t nil t t) :finally (read-char stream t nil t)))) ;;; ---------------------------------------- ;;; (defun source-reader-macro-error-start (stream ch) ;; Actually exits thru the error handler... (building-reader-macro-source-object stream ch 'source-lexical-error :error (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "an object cannot start with ~C" ch))) ;;; ---------------------------------------- ;;; (defun make-source-dispatch-macro-character (macro-character &optional (readtable *readtable*)) " PRE: MACRO-CHARACTER is a reader dispatch macro character. POST: The dispatching reader macro function for the MACRO-CHARACTER is replaced by a function that encapsulates the original dispatching reader macro function, in a binding to *START* of the file position of the MACRO-CHARACTER. " (multiple-value-bind (dispatch non-terminating-p) (get-macro-character macro-character readtable) (set-macro-character macro-character (lambda (stream macro-character) (unread-char macro-character stream) (let ((*start* (file-position stream)) (*macro-character* macro-character)) (read-char stream) (funcall dispatch stream macro-character))) non-terminating-p readtable))) (defmacro building-reader-dispatch-macro-source-object (stream argument sub-char class &rest initargs &key &allow-other-keys) `(building-source-object ,stream *start* ,class :macro-character *macro-character* :argument ,argument :sub-character ,sub-char ,@initargs)) ;;;--------------------------------------------- ;;; STANDARD READER DISPATCH MACRO FUNCTIONS ;;;--------------------------------------------- (defclass source-label-reference (source-object dispatch-macro-character-mixin) ((label :accessor source-label-reference-label :initarg :label :type (integer 0)))) (defun source-reader-dispatch-macro-label-reference (stream arg sub-char) "Source reader ## dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-label-reference :label (or arg (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "a number must be given between # and #")))) ;;; ---------------------------------------- ;;; (defclass source-label-definition (source-object dispatch-macro-character-mixin) ((label :accessor source-label-definition-label :initarg :label :type (integer 0)) (form :accessor source-label-definition-form :initarg :form))) (defun source-reader-dispatch-macro-label-definition (stream arg sub-char) "Source reader #= dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-label-definition :label (or arg (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "a number must be given between # and =")) :form (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-feature (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-feature (stream arg sub-char) "Source reader #+ dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-feature :subform (let ((*package* (find-package "KEYWORD")) (*read-suppress* nil)) (source-read stream t nil t)))) (defclass source-not-feature (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-not-feature (stream arg sub-char) "Source reader #- dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-not-feature :subform (let ((*package* (find-package "KEYWORD")) (*read-suppress* nil)) (source-read stream t nil t)))) ;;; ---------------------------------------- ;;; (defclass source-read-eval (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-read-eval (stream arg sub-char) "Source reader #. dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-read-eval :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; ;;; We cannot decide between some symbol and integer, or the type of ;;; floating point before knowing *read-case* and *READ-DEFAULT-FLOAT-FORMAT* ;;; (defclass source-symbol (source-object) ((value :accessor source-symbol-value :initarg :value))) (defun source-reader-dispatch-macro-uninterned (stream arg sub-char) "Source reader #: dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-token :token (multiple-value-bind (tokenp token) (com.informatimago.common-lisp.reader::read-token stream t nil t nil nil *readtable*) (if tokenp (make-instance 'source-token ;; TODO: Here, we know we have a symbol whatever... :file (pathname stream) :position *start* :token token) (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "token expected after #:"))))) ;;; ---------------------------------------- ;;; (defun source-reader-dispatch-macro-unreadable (stream arg sub-char) "Source reader #< dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-token :token "<unreadable>")) ;;; ---------------------------------------- ;;; (defclass source-sharp-pipe-comment (comment dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-COMMENT (stream arg sub-char) "Source reader #| dispatch macro reader." ;; #|...|# is treated as a comment by the reader. It must be balanced ;; with respect to other occurrences of #| and |#, but otherwise may ;; contain any characters whatsoever. (building-reader-dispatch-macro-source-object stream arg sub-char 'source-token :comment (loop :with comment = (make-array 0 :adjustable t :fill-pointer 0 :element-type 'character) :with level = 1 :with state = :normal :until (zerop level) :do (let ((ch (read-char stream t nil t))) (vector-push-extend ch comment) (case state ((:normal) (case ch ((#\#) (setf state :sharp)) ((#\|) (setf state :pipe)))) ((:sharp) (case ch ((#\#)) ((#\|) (incf level) (setf state :normal)) (otherwise (setf state :normal)))) ((:pipe) (case ch ((#\#) (decf level) (setf state :normal)) ((#\|)) (otherwise (setf state :normal)))))) :finally (progn (decf (fill-pointer comment) 2) (return comment))))) ;;; ---------------------------------------- ;;; (defclass source-function (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-function (stream arg sub-char) "Source reader #' dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-function :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-vector (source-sequence dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-vector (stream arg sub-char) "Source reader #( dispatch macro reader." ;; If an unsigned decimal integer appears between the # and (, it ;; specifies explicitly the length of the vector. The consequences are ;; undefined if the number of objects specified before the closing ) ;; exceeds the unsigned decimal integer. If the number of objects ;; supplied before the closing ) is less than the unsigned decimal ;; integer but greater than zero, the last object is used to fill all ;; remaining elements of the vector. The consequences are undefined if ;; the unsigned decimal integer is non-zero and number of objects ;; supplied before the closing ) is zero. For example, (building-reader-dispatch-macro-source-object stream arg sub-char 'source-vector :elements (loop :until (char= #\) (peek-char t stream t nil t)) :collect (source-read stream t nil t) :finally (read-char stream t nil t)))) ;;; ---------------------------------------- ;;; (defclass source-bit-vector (source-sequence dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-bit-vector (stream arg sub-char) "Source reader #* dispatch macro reader. URL: http://www.lispworks.com/documentation/HyperSpec/Body/02_dhd.htm " ;; Syntax: #*<<bits>> ;; ;; A simple bit vector is constructed containing the indicated bits (0's ;; and 1's), where the leftmost bit has index zero and the subsequent ;; bits have increasing indices. ;; ;; Syntax: #<<n>>*<<bits>> ;; ;; With an argument n, the vector to be created is of length n. If the ;; number of bits is less than n but greater than zero, the last bit is ;; used to fill all remaining bits of the bit vector. ;; ;; The notations #* and #0* each denote an empty bit vector. ;; ;; Regardless of whether the optional numeric argument n is provided, the ;; token that follows the asterisk is delimited by a normal token ;; delimiter. However, (unless the value of *read-suppress* is true) an ;; error of type reader-error is signaled if that token is not composed ;; entirely of 0's and 1's, or if n was supplied and the token is ;; composed of more than n bits, or if n is greater than one, but no bits ;; were specified. Neither a single escape nor a multiple escape is ;; permitted in this token. (building-reader-dispatch-macro-source-object stream arg sub-char 'source-bit-vector :elements (reader::reader-dispatch-macro-bit-vector stream arg sub-char))) ;;; ---------------------------------------- ;;; (defclass source-character (source-object dispatch-macro-character-mixin) ((character :accessor source-character :initarg :character))) (defun source-reader-dispatch-macro-CHAR (stream arg sub-char) "Source reader #\\ dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-character :character (read-char stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-array (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-ARRAY (stream arg sub-char) "Source reader #A dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-array :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defclass source-number (source-object) ((value :accessor source-number-value :initarg :value))) (defclass source-base-number (source-number dispatch-macro-character-mixin) ((base :accessor source-base-number-base :initarg :base) (specificp :accessor source-base-number-specific :initarg :specificp))) (defun source-reader-dispatch-macro-BINARY (stream arg sub-char) "Source reader #B dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-base-number :base 2. :specificp t :value (com.informatimago.common-lisp.reader::read-rational-in-base stream arg sub-char 2.))) (defun source-reader-dispatch-macro-OCTAL (stream arg sub-char) "Source reader #O dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-base-number :base 8. :specificp t :value (com.informatimago.common-lisp.reader::read-rational-in-base stream arg sub-char 8.))) (defun source-reader-dispatch-macro-HEXADECIMAL (stream arg sub-char) "Source reader #X dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-base-number :base 16. :specificp t :value (com.informatimago.common-lisp.reader::read-rational-in-base stream arg sub-char 16.))) (defun source-reader-dispatch-macro-RADIX (stream arg sub-char) "Source reader #R dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-base-number :base arg :specificp nil :value (if arg (com.informatimago.common-lisp.reader::read-rational-in-base stream nil sub-char arg) (com.informatimago.common-lisp.reader::serror stream "the number base must be given between # and ~A" sub-char)))) ;;; ---------------------------------------- ;;; (defclass source-complex (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-COMPLEX (stream arg sub-char) "Source reader #C dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-base-complex :subform (let ((c (source-read stream t nil t))) (if (and (com.informatimago.common-lisp.reader::proper-list-p c) (= 2 (length c)) (every (function realp) c)) c (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "bad syntax for complex number: #C~S" c))))) ;;; ---------------------------------------- ;;; (defclass source-pathname (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-PATHNAME (stream arg sub-char) "Source reader #P dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-pathname :subform (source-read stream t nil t) )) ;;; ---------------------------------------- ;;; (defclass source-structure (source-subform dispatch-macro-character-mixin) ()) (defun source-reader-dispatch-macro-STRUCTURE (stream arg sub-char) "Source reader #S dispatch macro reader." (building-reader-dispatch-macro-source-object stream arg sub-char 'source-structure :subform (source-read stream t nil t))) ;;; ---------------------------------------- ;;; (defun SOURCE-READER-DISPATCH-MACRO-ERROR-INVALID (stream sub-char arg) (building-reader-dispatch-macro-source-object stream arg sub-char 'source-lexical-error :error (com.informatimago.common-lisp.reader::serror 'simple-reader-error stream "objects printed as # in view of *PRINT-LEVEL* cannot be read back in"))) ;;; ---------------------------------------- ;;; (defun make-source-readtable () " RETURN: A new readtable where all the reader macros are set to return source objects instead of lisp objects. " (let ((readtable (copy-readtable nil))) (macrolet ((smc (&rest clauses) `(progn ,@(mapcar (lambda (clause) `(set-macro-character ,(first clause) (function ,(second clause)) ,(third clause) readtable)) clauses)))) (smc (#\; source-reader-macro-line-comment nil) (#\" source-reader-macro-string nil) (#\Space source-reader-macro-whitespace nil) (#\Tab source-reader-macro-whitespace nil) (#\Newline source-reader-macro-whitespace nil) (#\' source-reader-macro-quote nil) (#\` source-reader-macro-backquote nil) (#\, source-reader-macro-comma nil) (#\( source-reader-macro-left-parenthesis nil) (#\) source-reader-macro-error-start nil))) (macrolet ((dmc (&rest clauses) `(progn ,@(mapcar (lambda (clause) `(set-dispatch-macro-character ,(first clause) ,(second clause) (function ,(third clause)) readtable)) clauses)))) (make-dispatch-macro-character #\# t readtable) (dmc (#\# #\SPACE SOURCE-READER-DISPATCH-MACRO-ERROR-INVALID) (#\# #\NEWLINE SOURCE-READER-DISPATCH-MACRO-ERROR-INVALID) (#\# #\# SOURCE-READER-DISPATCH-MACRO-LABEL-REFERENCE) (#\# #\' SOURCE-READER-DISPATCH-MACRO-FUNCTION) (#\# #\( SOURCE-READER-DISPATCH-MACRO-VECTOR) (#\# #\* SOURCE-READER-DISPATCH-MACRO-BIT-VECTOR) (#\# #\+ SOURCE-READER-DISPATCH-MACRO-FEATURE) (#\# #\- SOURCE-READER-DISPATCH-MACRO-NOT-FEATURE) (#\# #\. SOURCE-READER-DISPATCH-MACRO-READ-EVAL) (#\# #\: SOURCE-READER-DISPATCH-MACRO-UNINTERNED) (#\# #\< SOURCE-READER-DISPATCH-MACRO-UNREADABLE) (#\# #\= SOURCE-READER-DISPATCH-MACRO-LABEL-DEFINITION) (#\# #\A SOURCE-READER-DISPATCH-MACRO-ARRAY) (#\# #\B SOURCE-READER-DISPATCH-MACRO-BINARY) (#\# #\C SOURCE-READER-DISPATCH-MACRO-COMPLEX) (#\# #\O SOURCE-READER-DISPATCH-MACRO-OCTAL) (#\# #\P SOURCE-READER-DISPATCH-MACRO-PATHNAME) (#\# #\R SOURCE-READER-DISPATCH-MACRO-RADIX) (#\# #\S SOURCE-READER-DISPATCH-MACRO-STRUCTURE) (#\# #\X SOURCE-READER-DISPATCH-MACRO-HEXADECIMAL) (#\# #\\ SOURCE-READER-DISPATCH-MACRO-CHAR) (#\# #\| SOURCE-READER-DISPATCH-MACRO-COMMENT) ;; clisp extensions: ;; (#\# #\! reader-dispatch-macro-executable) ;; (#\# #\" reader-dispatch-macro-clisp-pathname) ;; (#\# #\, reader-dispatch-macro-load-eval) ;; (#\# #\Y SYSTEM::CLOSURE-READER) )) (setf (readtable-parse-token readtable) (function source-parse-token)) readtable)) (defvar *source-readtable* (make-source-readtable) "The source readtable.") (defun source-read (&optional input-stream (eof-error-p t) (eof-value nil) (recursive-p nil) (preserve-whitespace-p nil)) (let ((*read-suppress* nil) ; we do want the source! (*readtable* *source-readtable*) (*stream* input-stream) (*file* (ignore-errors (pathname input-stream)))) (unless preserve-whitespace-p (peek-char t input-stream nil nil t)) (let ((*start* (file-position input-stream))) ;; (read input-stream eof-error-p eof-value recursive-p) ;; We want to allow all-dots tokens. (reader::read-1 input-stream eof-error-p eof-value recursive-p preserve-whitespace-p nil t)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defgeneric source-atom-p (self) (:method ((self source-object)) t) (:method ((self source-list)) nil)) (defgeneric map-subforms (fun self) (:method (fun (self source-object)) (funcall fun self) (values)) (:method (fun (self source-array)) (funcall fun self) (values)) (:method (fun (self source-complex)) (funcall fun self) (values)) (:method (fun (self source-pathname)) (funcall fun self) (values)) (:method (fun (self source-subform)) (funcall fun self) (map-subforms fun (source-object-subform self))) (:method (fun (self source-label-definition)) (funcall fun self) (map-subforms fun (source-label-definition-form self))) (:method (fun (self source-list)) (funcall fun self) (dolist (item (source-sequence-elements self) (values)) (map-subforms fun item)))) (defun map-source-stream (fun source-stream &key (deeply t) (only-atoms nil)) (loop :for top-level-form = (source-read source-stream nil source-stream t) :until (eq top-level-form source-stream) :if deeply :do (map-subforms (if only-atoms (lambda (x) (when (source-atom-p x) (funcall fun x))) fun) top-level-form) :else :do (when (or (not only-atoms) (source-atom-p top-level-form)) (funcall fun top-level-form)))) (defun map-source-file (fun source-file &key (deeply t) (only-atoms nil) (external-format :default)) " FUN: A function (source-object) source-object: An instance of source-object parsed from a source file. When atoms is true, FUN is called only on source-objects not representing cons cells (lists). " (with-open-file (src source-file :external-format external-format) (map-source-stream fun src :deeply deeply :only-atoms only-atoms))) ;;;;;; ;;; Levy's addition (defun source-read-from-string (&optional text (eof-error-p t) (eof-value nil) (recursive-p nil) (preserve-whitespace-p nil)) (with-input-from-string (stream text) (source-text:source-read stream eof-error-p eof-value recursive-p preserve-whitespace-p))) (defun source-form (instance) "Build the lisp form that would be read by the original lisp reader and set it for each source-object." (%source-form instance)) (defgeneric %source-form (instance) (:method :around (instance) (setf (source-object-form instance) (call-next-method))) (:method ((instance source-quote)) (list 'quote (%source-form (source-object-subform instance)))) (:method ((instance source-read-eval)) (eval (%source-form (source-object-subform instance)))) (:method ((instance source-symbol)) (source-symbol-value instance)) (:method ((instance source-character)) (source-character instance)) (:method ((instance source-number)) (source-number-value instance)) (:method ((instance source-string)) (source-string-value instance)) (:method ((instance source-function)) `(function ,(%source-form (source-object-subform instance)))) (:method ((instance source-sequence)) (loop :with index = 0 :for element :in (source-sequence-elements instance) :unless (typep element 'source-whitespace) :collect (prog1 (%source-form element) (incf index))))) (defun source-print (instance &optional (stream *standard-output*)) "Print INSTANCE to STREAM in its original form." (%source-print instance stream)) (defgeneric %source-print (instance stream) (:method ((instance source-object) stream) (write-string (source-object-text instance) stream) (values)) (:method ((instance source-list) stream) (write-char #\( stream) (dolist (element (source-sequence-elements instance)) (%source-print element stream)) (write-char #\) stream) (values))) (defun source-string (instance) "Return a string representing INSTANCE according to SOURCE-PRINT." (with-output-to-string (stream) (source-print instance stream))) (defun source-format (source &key (default-indent 2) (normalize-whitespace t) (insert-newlines t)) (labels ((recurse (parent-source source indent) (setf (source-object-parent source) parent-source) (loop :with prefix-indent = 1 :with subform-indent = (+ indent prefix-indent) :with subform-index = 0 :for element-cell :on (typecase source (source-sequence (source-sequence-elements source)) (source-subform (list (source-object-subform source)))) :for element = (car element-cell) :do (let* ((text (source-object-text element)) (text-length (length text))) (if (typep element 'source-whitespace) (let* ((source-form (source-object-form source)) (next-source (find-if-not (lambda (next-source) (typep next-source 'source-whitespace)) element-cell)) (next-form (when next-source (source-object-form next-source))) (insert-newline? (or (position #\Newline text :test #'char= :from-end t) (and insert-newlines (source-insert-newline source-form source next-form next-source subform-index))))) (if insert-newline? (let* ((indent-length (+ indent (or (source-parent-relative-indent source-form source next-form next-source subform-index) default-indent))) (original-newlines (string-right-trim '(#\Space #\Tab) text)) (text (concatenate 'string (if (or normalize-whitespace (zerop (length original-newlines))) #.(coerce '(#\Newline) 'simple-string) original-newlines) (make-string indent-length :initial-element #\Space)))) (setf (slot-value element 'text) text subform-indent indent-length)) (if normalize-whitespace (setf (slot-value element 'text) " ") (incf subform-indent text-length)))) (progn (recurse source element subform-indent) (incf subform-index) (incf subform-indent text-length))))))) (recurse nil source 0) source)) (defgeneric source-parent-relative-indent (parent-form parent-source form source form-index) (:method (parent-form parent-source form source form-index) nil)) (defgeneric source-insert-newline (parent-form parent-source form source form-index) (:method (parent-form parent-source form source form-index) nil)) (defun source-format-string (text) (with-output-to-string (output) (with-input-from-string (input text) (loop :for element = (source-read input nil input nil t) :until (eq element input) :do (write-string (source-string (source-format element)) output) :until (typep element 'source-text:source-lexical-error))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; To be tested: ;;; ;;; '(#1=#2=#3=#4=a #2# #3# #4#) #- (and) (defparameter *some* (with-open-file (src "source-text.lisp") (loop :for item = (source-text:source-read src nil src) :until (eq item src) :collect item :until (typep item 'source-text:source-lexical-error) :do (princ "**") (let ((*print-readably* nil)) (print item)) :do (princ "==") (let ((*print-readably* t )) (prin1 item))))) #- (and) (defparameter *some* (with-input-from-string (src "(a b c) (d e f)") (loop :for item = (source-text:source-read src nil src) :until (eq item src) :collect item :until (typep item 'source-text:source-lexical-error) :do (princ "**") (let ((*print-readably* nil)) (print item)) :do (princ "==") (let ((*print-readably* t )) (prin1 item))))) #- (and) (with-input-from-string (src " ") (com.informatimago.common-lisp.reader::read-token src nil :eof t nil nil reader::*readtable*)) #- (and) (with-input-from-string (src " ") (com.informatimago.common-lisp.READER::READ-0/1 src nil :eof nil NIL NIL T)) #- (and) (with-input-from-string (src " ") (com.informatimago.common-lisp.source-text:source-read src nil :eof)) #- (and) (defparameter *some* (with-open-file (src "source-text.lisp") (loop :for item = (com.informatimago.common-lisp.source-text:source-read src nil src) :until (eq item src) :collect item :until (typep item 'com.informatimago.common-lisp.source-text:source-lexical-error) :do (let ((*print-readably* t)) (prin1 item))))) #- (and) (with-input-from-string (src "#+(and)(a b c #-(or) d e)") (com.informatimago.common-lisp.source-text:source-read src nil :eof)) #- (and) (with-input-from-string (src "( a . b . c ... d #+(and)(a b c) #-(or)(d e))") (com.informatimago.common-lisp.source-text:source-read src nil :eof)) #- (and) (setf *some* (with-input-from-string (src "'(#1=#2=#3=#4=a #2# #3# #4#)") (com.informatimago.common-lisp.source-text:source-read src nil :eof))) ;; (with-input-from-string (src "(a (b c #(1 2 3) (e f) g) h) (1 2 3)") ;; (let ((*print-readably* t)) ;; (map-source-stream (lambda (x) (terpri) (prin1 x)) src))) ;; ;; (with-input-from-string (src "(a (b c (1 2 3) (e f) g) h) (1 2 3)") ;; (let ((*print-readably* t)) ;; (map-source-stream (lambda (x) (terpri) (prin1 x)) src ;; :deeply t :only-atoms nil))) ;; ;; (with-input-from-string (src "(a (b c #(1 2 3) (e f) g) h) (1 2 3)") ;; (map-source-stream (lambda (x) ;; (terpri) ;; (let ((*print-readably* t)) (prin1 x))) ;; src :deeply t :only-atoms nil)) ;;;; The End ;;;;
50,962
Common Lisp
.lisp
1,120
36.867857
146
0.580068
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
61bc3d7d8a7651eb86489c98a7a7cc2c7ccd8f3ebcd5d87b9a6cc201f3ba6f17
40,313
[ -1 ]
40,314
hu.dwim.reader+hu.dwim.syntax-sugar.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader+hu.dwim.syntax-sugar.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader+hu.dwim.syntax-sugar :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.system" :depends-on (:hu.dwim.reader :hu.dwim.syntax-sugar) :components ((:module "integration" :components ((:file "syntax-sugar")))))
412
Common Lisp
.asd
12
30
55
0.634085
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
f0da470075bbfbb820600ff70238fa463076616322d8e75db1a390fec33dcd30
40,314
[ -1 ]
40,315
hu.dwim.reader+swank.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader+swank.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader+swank :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.system" :description "Loads code that can deal with SBCL's #! syntax. Requires Swank to reuse its implementation." :depends-on (:hu.dwim.reader :swank) :components ((:module "integration" :components ((:file "sbcl+swank" :if-feature :sbcl)))))
507
Common Lisp
.asd
13
34.769231
108
0.655172
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
efe36c9fe76c5ebc9291beee4656894c37605fd81e2212c69cbaf1600e2b4141
40,315
[ -1 ]
40,316
hu.dwim.reader.test.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader.test.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader.test :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.test-system" :depends-on (:hu.dwim.reader :hu.dwim.stefil+hu.dwim.def+swank :hu.dwim.util) :components ((:module "test" :components ((:file "package") (:file "suite" :depends-on ("package"))))))
499
Common Lisp
.asd
14
28.642857
72
0.572314
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
d65abc901bdc1dbc93786b7074dabba03e7e18e514195b099c75940b3cabfc8b
40,316
[ -1 ]
40,317
hu.dwim.reader+hu.dwim.walker.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader+hu.dwim.walker.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader+hu.dwim.walker :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.system" :depends-on (:hu.dwim.def+contextl :hu.dwim.reader :hu.dwim.walker) :components ((:module "integration" :components ((:file "walker")))))
431
Common Lisp
.asd
13
27.923077
49
0.611511
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
bcddd8c7b689f52f966c2d518a959388ea516f7dc8c1806949ea4dc5e3970781
40,317
[ -1 ]
40,318
hu.dwim.reader.documentation.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader.documentation.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader.documentation :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.documentation-system" :depends-on (:hu.dwim.reader.test :hu.dwim.presentation) :components ((:module "documentation" :components ((:file "reader" :depends-on ("package")) (:file "package")))))
491
Common Lisp
.asd
13
31.461538
69
0.610063
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
8c47a27f9d56c236e95e47fab8eb6003dc56047623b9f4aee860139ab7965a9a
40,318
[ -1 ]
40,319
hu.dwim.reader.asd
hu-dwim_hu_dwim_reader/hu.dwim.reader.asd
;;; -*- mode: Lisp; Syntax: Common-Lisp; -*- ;;; ;;; Copyright (c) 2009 by the authors. ;;; ;;; See LICENCE for details. (defsystem :hu.dwim.reader :defsystem-depends-on (:hu.dwim.asdf) :class "hu.dwim.asdf:hu.dwim.system" :description "Whitespace preserving Common Lisp reader." :components ((:module "source" :components ((:file "reader" :depends-on ("source-form")) (:file "source-form") (:file "source-text" :depends-on ("reader")))) (:module "integration" :depends-on ("source") :components ((:file "sbcl" :if-feature :sbcl)))))
664
Common Lisp
.asd
16
32.375
75
0.556414
hu-dwim/hu.dwim.reader
0
0
0
GPL-2.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
83d335892cab126ad08a78e73afd235dc5e4078676d71c8728e55b8b2d4447a0
40,319
[ -1 ]
40,350
LM_Copy2DrawingsV1-3_KGedition.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/LM_Copy2DrawingsV1-3_KGedition.lsp
;;-----------------------=={ Copy to Drawings }==-----------------------;; ;; ;; ;; This program enables the user to copy a selection of objects to a ;; ;; selected set of drawings, without opening the drawings in the ;; ;; AutoCAD Editor. ;; ;; ;; ;; The program will first prompt the user to make a selection of ;; ;; objects residing in the active drawing layout that are to be ;; ;; copied. Following a valid selection, the user will be prompted via ;; ;; a dialog interface to compile a list of drawings (dwg/dwt/dws) to ;; ;; which the selected objects will be copied. ;; ;; ;; ;; The program will then proceed to copy every object in the selection ;; ;; to each selected drawing using an ObjectDBX interface. ;; ;; ;; ;; The program will retain all information associated with each ;; ;; copied object, including the position, scale, rotation, etc. ;; ;; Properties such as layers & linetypes will be imported if not ;; ;; already present in the external drawing. Similarly, the drawing ;; ;; layout in which the source objects reside will be created if not ;; ;; already present in the external drawing. ;; ;; ;; ;; The program is compatible for use with all drawing objects ;; ;; (including XRefs & Dynamic Blocks) with the exception of Viewports. ;; ;; ;; ;; After copying the set of objects to each drawing, the program will ;; ;; save the external drawing. Due to a restriction on the saveas ;; ;; method when invoked through an ObjectDBX interface, all drawings ;; ;; will be saved to the native format, i.e. the latest version ;; ;; available - this is unfortunately unavoidable. ;; ;; ;; ;; Note that when saving drawings through ObjectDBX, drawing file ;; ;; thumbnails will be lost until the next manual save. ;; ;;----------------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2013 - www.lee-mac.com ;; ;;----------------------------------------------------------------------;; ;; Version 1.2 - 2013-05-17 ;; ;;----------------------------------------------------------------------;; ;; Version 1.3 - 2016-03-21 ;; ;; ;; ;; - Updated Get Files Dialog function to fix filename sorting bug ;; ;; and incorrect enabling of 'Add Files' button when a directory is ;; ;; selected. ;; ;; - Refined output message to report unsuccessful drawings. ;; ;;----------------------------------------------------------------------;; ;;----------------------------------------------------------------------;; ;; Modification: Andrey Adamenko ;; ;; Date: 2021-02-25 ;; ;;----------------------------------------------------------------------;; (defun c:c2dwg ( / ) (c2dwg (ssget (list '(0 . "~VIEWPORT") (cons 410 (if (= 1 (getvar 'cvport)) (getvar 'ctab) "Model") ))) (LM:GetFiles "Select Drawings to Copy to" "" "dwg;dwt;dws") ) ) ; sel - Selection set ; lst - List of DWG files path strings (defun c2dwg (sel lst / *error* _getitem acd app dbx doc dwl err inc msg tab var vrs ) (defun *error* ( msg ) (if (and (= 'vla-object (type dbx)) (not (vlax-object-released-p dbx))) (vlax-release-object dbx) ) (if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*")) (princ (strcat "\nError: " msg)) ) (princ) ) (defun _getitem ( col itm ) (if (not (vl-catch-all-error-p (setq itm (vl-catch-all-apply 'vla-item (list col itm))))) itm ) ) (setq app (vlax-get-acad-object) acd (vla-get-activedocument app) tab (if (= 1 (getvar 'cvport)) (getvar 'ctab) "Model") cnt 0 ) (cond ( (not (and sel lst) ) (princ "\n*Cancel*") ) ( (progn (setq dbx (vl-catch-all-apply 'vla-getinterfaceobject (list (setq app (vlax-get-acad-object)) (if (< (setq vrs (atoi (getvar 'acadver))) 16) "objectdbx.axdbdocument" (strcat "objectdbx.axdbdocument." (itoa vrs)) ) ) ) ) (or (null dbx) (vl-catch-all-error-p dbx)) ) (prompt "\nUnable to interface with ObjectDBX.") ) ( t (vlax-for doc (vla-get-documents app) (setq dwl (cons (cons (strcase (vla-get-fullname doc)) doc) dwl)) ) (repeat (setq inc (sslength sel)) (setq var (cons (vlax-ename->vla-object (ssname sel (setq inc (1- inc)))) var)) ) (setq var (vlax-make-variant (vlax-safearray-fill (vlax-make-safearray vlax-vbobject (cons 0 (1- (length var)))) var ) ) ) (foreach dwg lst (if (or (setq doc (cdr (assoc (strcase dwg) dwl))) (and (not (vl-catch-all-error-p (vl-catch-all-apply 'vla-open (list dbx dwg)))) (setq doc dbx) ) ) (progn (vla-copyobjects acd var (vla-get-block (cond ( (_getitem (vla-get-layouts doc) tab)) ( (vla-add (vla-get-layouts doc) tab)) ) ) ) (vla-saveas doc dwg) (setq cnt (1+ cnt)) ) (princ (apply 'strcat (cons "\nUnable to interface with file: " (cdr (fnsplitl dwg))))) ) ) (setq msg (if (< 0 cnt) (strcat "\n" (itoa (sslength sel)) (if (= 1 (sslength sel)) " object" " objects" ) " copied to " (itoa cnt) (if (= 1 cnt) " drawing." " drawings." ) ) "" ) ) (if (< 0 (setq err (- (length lst) cnt))) (setq msg (strcat msg "\nUnable to copy to" (itoa err) (if (= 1 err) " drawing." " drawings." ) ) ) ) (princ msg) (if (= 'vla-object (type dbx)) (vlax-release-object dbx) ) ) ) (princ) ) ;;------------------------=={ Get Files Dialog }==----------------------;; ;; ;; ;; An analog of the 'getfiled' function for multiple file selection. ;; ;;----------------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2012 - www.lee-mac.com ;; ;;----------------------------------------------------------------------;; ;; Arguments: ;; ;; msg - [str/nil] Dialog box label; 'Select Files' if nil or "". ;; ;; def - [str/nil] Default directory; dwgprefix if nil or "". ;; ;; ext - [str/nil] File extension filter (e.g. "dwg;lsp"); "*" if nil ;; ;;----------------------------------------------------------------------;; ;; Returns: List of selected files, else nil ;; ;;----------------------------------------------------------------------;; ;; Version 1.6 - 2016-03-21 ;; ;;----------------------------------------------------------------------;; (defun LM:getfiles ( msg def ext / *error* dch dcl des dir dirdata lst rtn ) (defun *error* ( msg ) (if (= 'file (type des)) (close des) ) (if (and (= 'int (type dch)) (< 0 dch)) (unload_dialog dch) ) (if (and (= 'str (type dcl)) (findfile dcl)) (vl-file-delete dcl) ) (if (and msg (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*"))) (princ (strcat "\nError: " msg)) ) (princ) ) (if (and (setq dcl (vl-filename-mktemp nil nil ".dcl")) (setq des (open dcl "w")) (progn (foreach x '( "lst : list_box" "{" " width = 40.0;" " height = 20.0;" " fixed_width = true;" " fixed_height = true;" " alignment = centered;" " multiple_select = true;" "}" "but : button" "{" " width = 20.0;" " height = 1.8;" " fixed_width = true;" " fixed_height = true;" " alignment = centered;" "}" "getfiles : dialog" "{" " key = \"title\"; spacer;" " : row" " {" " alignment = centered;" " : edit_box { key = \"dir\"; label = \"Folder:\"; }" " : button" " {" " key = \"brw\";" " label = \"Browse\";" " fixed_width = true;" " }" " }" " spacer;" " : row" " {" " : column" " {" " : lst { key = \"box1\"; }" " : but { key = \"add\" ; label = \"Add Files\"; }" " }" " : column {" " : lst { key = \"box2\"; }" " : but { key = \"del\" ; label = \"Remove Files\"; }" " }" " }" " spacer; ok_cancel;" "}" ) (write-line x des) ) (setq des (close des)) (< 0 (setq dch (load_dialog dcl))) ) (new_dialog "getfiles" dch) ) (progn (setq ext (if (= 'str (type ext)) (LM:getfiles:str->lst (strcase ext) ";") '("*"))) (set_tile "title" (if (member msg '(nil "")) "Select Files" msg)) (set_tile "dir" (setq dir (LM:getfiles:fixdir (if (or (member def '(nil "")) (not (vl-file-directory-p (LM:getfiles:fixdir def)))) (getvar 'dwgprefix) def ) ) ) ) (setq lst (LM:getfiles:updatefilelist dir ext nil)) (mode_tile "add" 1) (mode_tile "del" 1) (action_tile "brw" (vl-prin1-to-string '(if (setq tmp (LM:getfiles:browseforfolder "" nil 512)) (setq lst (LM:getfiles:updatefilelist (set_tile "dir" (setq dir tmp)) ext rtn) rtn (LM:getfiles:updateselected dir rtn) ) ) ) ) (action_tile "dir" (vl-prin1-to-string '(if (= 1 $reason) (setq lst (LM:getfiles:updatefilelist (set_tile "dir" (setq dir (LM:getfiles:fixdir $value))) ext rtn) rtn (LM:getfiles:updateselected dir rtn) ) ) ) ) (action_tile "box1" (vl-prin1-to-string '( (lambda ( / itm tmp ) (if (setq itm (mapcar '(lambda ( n ) (nth n lst)) (read (strcat "(" $value ")")))) (if (= 4 $reason) (cond ( (equal '("..") itm) (setq lst (LM:getfiles:updatefilelist (set_tile "dir" (setq dir (LM:getfiles:updir dir))) ext rtn) rtn (LM:getfiles:updateselected dir rtn) ) ) ( (vl-file-directory-p (setq tmp (LM:getfiles:checkredirect (strcat dir "\\" (car itm))))) (setq lst (LM:getfiles:updatefilelist (set_tile "dir" (setq dir tmp)) ext rtn) rtn (LM:getfiles:updateselected dir rtn) ) ) ( (setq rtn (LM:getfiles:sort (append rtn (mapcar '(lambda ( x ) (strcat dir "\\" x)) itm))) rtn (LM:getfiles:updateselected dir rtn) lst (LM:getfiles:updatefilelist dir ext rtn) ) ) ) (if (vl-every '(lambda ( x ) (vl-file-directory-p (strcat dir "\\" x))) itm) (mode_tile "add" 1) (mode_tile "add" 0) ) ) ) ) ) ) ) (action_tile "box2" (vl-prin1-to-string '( (lambda ( / itm ) (if (setq itm (mapcar '(lambda ( n ) (nth n rtn)) (read (strcat "(" $value ")")))) (if (= 4 $reason) (setq rtn (LM:getfiles:updateselected dir (vl-remove (car itm) rtn)) lst (LM:getfiles:updatefilelist dir ext rtn) ) (mode_tile "del" 0) ) ) ) ) ) ) (action_tile "add" (vl-prin1-to-string '( (lambda ( / itm ) (if (setq itm (vl-remove-if 'vl-file-directory-p (mapcar '(lambda ( n ) (nth n lst)) (read (strcat "(" (get_tile "box1") ")"))) ) ) (setq rtn (LM:getfiles:sort (append rtn (mapcar '(lambda ( x ) (strcat dir "\\" x)) itm))) rtn (LM:getfiles:updateselected dir rtn) lst (LM:getfiles:updatefilelist dir ext rtn) ) ) (mode_tile "add" 1) (mode_tile "del" 1) ) ) ) ) (action_tile "del" (vl-prin1-to-string '( (lambda ( / itm ) (if (setq itm (read (strcat "(" (get_tile "box2") ")"))) (setq rtn (LM:getfiles:updateselected dir (LM:getfiles:removeitems itm rtn)) lst (LM:getfiles:updatefilelist dir ext rtn) ) ) (mode_tile "add" 1) (mode_tile "del" 1) ) ) ) ) (if (zerop (start_dialog)) (setq rtn nil) ) ) ) (*error* nil) rtn ) (defun LM:getfiles:listbox ( key lst ) (start_list key) (foreach x lst (add_list x)) (end_list) lst ) (defun LM:getfiles:listfiles ( dir ext lst ) (vl-remove-if '(lambda ( x ) (member (strcat dir "\\" x) lst)) (cond ( (cdr (assoc dir dirdata))) ( (cdar (setq dirdata (cons (cons dir (append (LM:getfiles:sortlist (vl-remove "." (vl-directory-files dir nil -1))) (LM:getfiles:sort (if (member ext '(("") ("*"))) (vl-directory-files dir nil 1) (vl-remove-if-not (function (lambda ( x / e ) (and (setq e (vl-filename-extension x)) (setq e (strcase (substr e 2))) (vl-some '(lambda ( w ) (wcmatch e w)) ext) ) ) ) (vl-directory-files dir nil 1) ) ) ) ) ) dirdata ) ) ) ) ) ) ) (defun LM:getfiles:checkredirect ( dir / itm pos ) (cond ( (vl-directory-files dir) dir) ( (and (= (strcase (getenv "UserProfile")) (strcase (substr dir 1 (setq pos (vl-string-position 92 dir nil t)))) ) (setq itm (cdr (assoc (substr (strcase dir t) (+ pos 2)) '( ("my documents" . "Documents") ("my pictures" . "Pictures") ("my videos" . "Videos") ("my music" . "Music") ) ) ) ) (vl-file-directory-p (setq itm (strcat (substr dir 1 pos) "\\" itm))) ) itm ) ( dir ) ) ) (defun LM:getfiles:sort ( lst ) (apply 'append (mapcar 'LM:getfiles:sortlist (vl-sort (LM:getfiles:groupbyfunction lst (lambda ( a b / x y ) (and (setq x (vl-filename-extension a)) (setq y (vl-filename-extension b)) (= (strcase x) (strcase y)) ) ) ) (function (lambda ( a b / x y ) (and (setq x (vl-filename-extension (car a))) (setq y (vl-filename-extension (car b))) (< (strcase x) (strcase y)) ) ) ) ) ) ) ) (defun LM:getfiles:sortlist ( lst ) (mapcar (function (lambda ( n ) (nth n lst))) (vl-sort-i (mapcar 'LM:getfiles:splitstring lst) (function (lambda ( a b / x y ) (while (and (setq x (car a)) (setq y (car b)) (= x y) ) (setq a (cdr a) b (cdr b) ) ) (cond ( (null x) b) ( (null y) nil) ( (and (numberp x) (numberp y)) (< x y)) ( (numberp x)) ( (numberp y) nil) ( (< x y)) ) ) ) ) ) ) (defun LM:getfiles:groupbyfunction ( lst fun / tmp1 tmp2 x1 ) (if (setq x1 (car lst)) (progn (foreach x2 (cdr lst) (if (fun x1 x2) (setq tmp1 (cons x2 tmp1)) (setq tmp2 (cons x2 tmp2)) ) ) (cons (cons x1 (reverse tmp1)) (LM:getfiles:groupbyfunction (reverse tmp2) fun)) ) ) ) (defun LM:getfiles:splitstring ( str ) ( (lambda ( l ) (read (strcat "(" (vl-list->string (apply 'append (mapcar (function (lambda ( a b c ) (cond ( (member b '(45 46 92)) (list 32) ) ( (< 47 b 58) (list b) ) ( (list 32 34 b 34 32)) ) ) ) (cons nil l) l (append (cdr l) '(( ))) ) ) ) ")" ) ) ) (vl-string->list (strcase str)) ) ) (defun LM:getfiles:browseforfolder ( msg dir flg / err fld pth shl slf ) (setq err (vl-catch-all-apply (function (lambda ( / app hwd ) (if (setq app (vlax-get-acad-object) shl (vla-getinterfaceobject app "shell.application") hwd (vl-catch-all-apply 'vla-get-hwnd (list app)) fld (vlax-invoke-method shl 'browseforfolder (if (vl-catch-all-error-p hwd) 0 hwd) msg flg dir) ) (setq slf (vlax-get-property fld 'self) pth (LM:getfiles:fixdir (vlax-get-property slf 'path)) ) ) ) ) ) ) (if slf (vlax-release-object slf)) (if fld (vlax-release-object fld)) (if shl (vlax-release-object shl)) (if (vl-catch-all-error-p err) (prompt (vl-catch-all-error-message err)) pth ) ) (defun LM:getfiles:full->relative ( dir path / p q ) (setq dir (vl-string-right-trim "\\" dir)) (cond ( (and (setq p (vl-string-position 58 dir)) (setq q (vl-string-position 58 path)) (/= (strcase (substr dir 1 p)) (strcase (substr path 1 q))) ) path ) ( (and (setq p (vl-string-position 92 dir)) (setq q (vl-string-position 92 path)) (= (strcase (substr dir 1 p)) (strcase (substr path 1 q))) ) (LM:getfiles:full->relative (substr dir (+ 2 p)) (substr path (+ 2 q))) ) ( (and (setq q (vl-string-position 92 path)) (= (strcase dir) (strcase (substr path 1 q))) ) (strcat ".\\" (substr path (+ 2 q))) ) ( (= "" dir) path ) ( (setq p (vl-string-position 92 dir)) (LM:getfiles:full->relative (substr dir (+ 2 p)) (strcat "..\\" path)) ) ( (LM:getfiles:full->relative "" (strcat "..\\" path))) ) ) (defun LM:getfiles:str->lst ( str del / pos ) (if (setq pos (vl-string-search del str)) (cons (substr str 1 pos) (LM:getfiles:str->lst (substr str (+ pos 1 (strlen del))) del)) (list str) ) ) (defun LM:getfiles:updatefilelist ( dir ext lst ) (LM:getfiles:listbox "box1" (LM:getfiles:listfiles dir ext lst)) ) (defun LM:getfiles:updateselected ( dir lst ) (LM:getfiles:listbox "box2" (mapcar '(lambda ( x ) (LM:getfiles:full->relative dir x)) lst)) lst ) (defun LM:getfiles:updir ( dir ) (substr dir 1 (vl-string-position 92 dir nil t)) ) (defun LM:getfiles:fixdir ( dir ) (vl-string-right-trim "\\" (vl-string-translate "/" "\\" dir)) ) (defun LM:getfiles:removeitems ( itm lst / idx ) (setq idx -1) (vl-remove-if '(lambda ( x ) (member (setq idx (1+ idx)) itm)) lst) ) ;;----------------------------------------------------------------------;; (vl-load-com) (princ (strcat "\n:: Copy2Drawings.lsp | Version 1.3 | \\U+00A9 Lee Mac " (menucmd "m=$(edtime,0,yyyy)") " www.lee-mac.com ::" "\n:: Type \"c2dwg\" to Invoke ::" ) ) (princ) ;;----------------------------------------------------------------------;; ;; End of File ;; ;;----------------------------------------------------------------------;;
21,646
Common Lisp
.l
655
24.838168
110
0.429207
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
f3661a8b8e4e1af41bad037eb15505d2da700d0e0f08f9bdc441f810f5c1e8d4
40,350
[ -1 ]
40,351
LM_ViewportOutline.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/LM_ViewportOutline.lsp
;;-----------------------=={ Viewport Outline }==-----------------------;; ;; ;; ;; This program allows the user to automatically generate a polyline ;; ;; in modelspace representing the outline of a selected paperspace ;; ;; viewport. ;; ;; ;; ;; The command is only available in paperspace (that is, when a ;; ;; layout tab other than the Model tab is the current layout, and no ;; ;; viewports are active). ;; ;; ;; ;; Upon issuing the command syntax 'VPO' at the AutoCAD command-line, ;; ;; the user is prompted to select a viewport for which to construct ;; ;; the viewport outline in modelspace. ;; ;; ;; ;; Following a valid selection, the boundary of the selected viewport ;; ;; is transformed appropriately to account for the position, scale, ;; ;; rotation, & orientation of the modelspace view displayed through ;; ;; the selected viewport, and a 2D polyline (LWPolyline) representing ;; ;; this transformed boundary is constructed in modelspace. ;; ;; ;; ;; The program is compatible for use with all Rectangular, Polygonal & ;; ;; Clipped Viewports (including those with Arc segments), and with all ;; ;; views & construction planes. ;; ;; ;; ;; The program also offers the ability to optionally offset the ;; ;; polyline outline to the interior of the viewport boundary by a ;; ;; predetermined number of paperspace units specified in the ;; ;; 'Program Parameters' section of the program source code. ;; ;; ;; ;; The program may also be configured to automatically apply a ;; ;; predefined set of properties (e.g. layer, colour, linetype, etc.) ;; ;; to the resulting polyline outline - these properties are also ;; ;; listed within the 'Program Parameters' section of the source code. ;; ;; ;; ;;----------------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2015 - www.lee-mac.com ;; ;;----------------------------------------------------------------------;; ;; Version 1.0 - 2015-01-02 ;; ;; ;; ;; - First release. ;; ;;----------------------------------------------------------------------;; ;; Version 1.1 - 2016-08-11 ;; ;; ;; ;; - Program modified to account for polygonal viewports represented ;; ;; by 2D (Heavy) Polylines. ;; ;;----------------------------------------------------------------------;; ;; Version 1.2 - 2017-09-03 ;; ;; ;; ;; - Added the ability to specify an optional interior offset ;; ;; (relative to Paperspace Viewport dimensions). ;; ;; - Added default polyline properties. ;; ;;----------------------------------------------------------------------;; ;; Version 1.3 - 2019-08-12 ;; ;; ;; ;; - Restructured program as a main function accepting a viewport ;; ;; entity argument. ;; ;; - Added two additional custom commands: ;; ;; - 'vpol' - outlines all viewports in the active Paperspace layout ;; ;; - 'vpoa' - outlines all viewports in all Paperspace layouts ;; ;;----------------------------------------------------------------------;; ;;----------------------------------------------------------------------;; ;; VPO - Outline a selected viewport in the active Paperspace layout ;; ;;----------------------------------------------------------------------;; (defun c:vpo ( / *error* sel ) (defun *error* ( msg ) (LM:endundo (LM:acdoc)) (if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*")) (princ (strcat "\nError: " msg)) ) (princ) ) (LM:startundo (LM:acdoc)) (cond ( (/= 1 (getvar 'cvport)) (princ "\nCommand not available in Modelspace.") ) ( (setq sel (LM:ssget "\nSelect viewport: " '("_+.:E:S" ((0 . "VIEWPORT"))))) (vpo:main (ssname sel 0)) ) ) (LM:endundo (LM:acdoc)) (princ) ) ;;----------------------------------------------------------------------;; ;; VPOL - Outline all viewports in the active Paperspace layout ;; ;;----------------------------------------------------------------------;; (defun c:vpol ( / *error* idx sel ) (defun *error* ( msg ) (LM:endundo (LM:acdoc)) (if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*")) (princ (strcat "\nError: " msg)) ) (princ) ) (cond ( (/= 1 (getvar 'cvport)) (princ "\nCommand not available in Modelspace.") ) ( (setq sel (ssget "_X" (list '(0 . "VIEWPORT") '(-4 . "<>") '(69 . 1) (cons 410 (getvar 'ctab))))) (LM:startundo (LM:acdoc)) (repeat (setq idx (sslength sel)) (vpo:main (ssname sel (setq idx (1- idx)))) ) (LM:endundo (LM:acdoc)) ) ( (princ "\nNo viewports were found in the active layout.")) ) (princ) ) ;;----------------------------------------------------------------------;; ;; VPOA - Outline all viewports in all Paperspace layouts ;; ;;----------------------------------------------------------------------;; (defun c:vpoa ( / *error* idx sel ) (defun *error* ( msg ) (LM:endundo (LM:acdoc)) (if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*")) (princ (strcat "\nError: " msg)) ) (princ) ) (cond ( (setq sel (ssget "_X" '((0 . "VIEWPORT") (-4 . "<>") (69 . 1) (410 . "~Model")))) (LM:startundo (LM:acdoc)) (repeat (setq idx (sslength sel)) (vpo:main (ssname sel (setq idx (1- idx)))) ) (LM:endundo (LM:acdoc)) ) ( (princ "\nNo viewports were found in any Paperspace layouts.")) ) (princ) ) ;;----------------------------------------------------------------------;; (defun vpo:main ( vpt / cen dpr ent lst ltp ocs ofe off tmp vpe ) (setq ;;----------------------------------------------------------------------;; ;; Program Parameters ;; ;;----------------------------------------------------------------------;; ;; Optional Interior Offset ;; Set this parameter to nil or 0.0 for no offset off 0.0 ;; Default Polyline Properties ;; Omitted properties will use current settings when the program is run dpr '( (006 . "BYLAYER") ;; Linetype (must be loaded) (008 . "VPOutline") ;; Layer (automatically created if not present in drawing) (039 . 0.0) ;; Thickness (048 . 1.0) ;; Linetype Scale (062 . 256) ;; Colour (0 = ByBlock, 256 = ByLayer) (370 . -1) ;; Lineweight (-1 = ByLayer, -2 = ByBlock, -3 = Default, 0.3 = 30 etc.) ) ;;----------------------------------------------------------------------;; ) (if (setq vpt (entget vpt) ent (cdr (assoc 340 vpt)) ) (setq lst (vpo:polyvertices ent)) (setq cen (mapcar 'list (cdr (assoc 10 vpt)) (list (/ (cdr (assoc 40 vpt)) 2.0) (/ (cdr (assoc 41 vpt)) 2.0) ) ) lst (mapcar '(lambda ( a ) (cons (mapcar 'apply a cen) '(42 . 0.0))) '((- -) (+ -) (+ +) (- +))) ) ) (if (not (LM:listclockwise-p (mapcar 'car lst))) (setq lst (reverse (mapcar '(lambda ( a b ) (cons (car a) (cons 42 (- (cddr b))))) lst (cons (last lst) lst)))) ) (if (and (numberp off) (not (equal 0.0 off 1e-8))) (cond ( (null (setq tmp (entmakex (append (list '(000 . "LWPOLYLINE") '(100 . "AcDbEntity") '(100 . "AcDbPolyline") (cons 90 (length lst)) '(070 . 1) ) (apply 'append (mapcar '(lambda ( x ) (list (cons 10 (car x)) (cdr x))) lst)) ) ) ) ) (princ "\nUnable to generate Paperspace outline for offset.") ) ( (vl-catch-all-error-p (setq ofe (vl-catch-all-apply 'vlax-invoke (list (vlax-ename->vla-object tmp) 'offset off)))) (princ (strcat "\nViewport dimensions too small to offset outline by " (rtos off) " units.")) (entdel tmp) ) ( (setq ofe (vlax-vla-object->ename (car ofe)) lst (vpo:polyvertices ofe) ) (entdel ofe) (entdel tmp) ) ) ) (setq vpe (cdr (assoc -1 vpt)) ocs (cdr (assoc 16 vpt)) ) (entmakex (append (list '(000 . "LWPOLYLINE") '(100 . "AcDbEntity") '(100 . "AcDbPolyline") (cons 90 (length lst)) '(070 . 1) '(410 . "Model") ) (if (and (setq ltp (assoc 6 dpr)) (not (tblsearch "ltype" (cdr ltp)))) (progn (princ (strcat "\n\"" (cdr ltp) "\" linetype not loaded - linetype set to \"ByLayer\".")) (subst '(6 . "BYLAYER") ltp dpr) ) dpr ) (apply 'append (mapcar '(lambda ( x ) (list (cons 10 (trans (pcs2wcs (car x) vpe) 0 ocs)) (cdr x))) lst)) (list (cons 210 ocs)) ) ) ) ;;----------------------------------------------------------------------;; (defun vpo:polyvertices ( ent ) (apply '(lambda ( foo bar ) (foo bar)) (if (= "LWPOLYLINE" (cdr (assoc 0 (entget ent)))) (list (lambda ( enx ) (if (setq enx (member (assoc 10 enx) enx)) (cons (cons (cdr (assoc 10 enx)) (assoc 42 enx)) (foo (cdr enx))) ) ) (entget ent) ) (list (lambda ( ent / enx ) (if (= "VERTEX" (cdr (assoc 0 (setq enx (entget ent))))) (cons (cons (cdr (assoc 10 enx)) (assoc 42 enx)) (foo (entnext ent))) ) ) (entnext ent) ) ) ) ) ;;----------------------------------------------------------------------;; ;; List Clockwise-p - Lee Mac ;; Returns T if the point list is clockwise oriented (defun LM:listclockwise-p ( lst ) (minusp (apply '+ (mapcar (function (lambda ( a b ) (- (* (car b) (cadr a)) (* (car a) (cadr b))) ) ) lst (cons (last lst) lst) ) ) ) ) ;; ssget - Lee Mac ;; A wrapper for the ssget function to permit the use of a custom selection prompt ;; msg - [str] selection prompt ;; arg - [lst] list of ssget arguments (defun LM:ssget ( msg arg / sel ) (princ msg) (setvar 'nomutt 1) (setq sel (vl-catch-all-apply 'ssget arg)) (setvar 'nomutt 0) (if (not (vl-catch-all-error-p sel)) sel) ) ;; PCS2WCS (gile) ;; Translates a PCS point to WCS based on the supplied Viewport ;; (PCS2WCS pt vp) is the same as (trans (trans pt 3 2) 2 0) when vp is active ;; pnt : PCS point ;; ent : Viewport ename (defun PCS2WCS ( pnt ent / ang enx mat nor scl ) (setq pnt (trans pnt 0 0) enx (entget ent) ang (- (cdr (assoc 51 enx))) nor (cdr (assoc 16 enx)) scl (/ (cdr (assoc 45 enx)) (cdr (assoc 41 enx))) mat (mxm (mapcar (function (lambda ( v ) (trans v 0 nor t))) '( (1.0 0.0 0.0) (0.0 1.0 0.0) (0.0 0.0 1.0) ) ) (list (list (cos ang) (- (sin ang)) 0.0) (list (sin ang) (cos ang) 0.0) '(0.0 0.0 1.0) ) ) ) (mapcar '+ (mxv mat (mapcar '+ (vxs pnt scl) (vxs (cdr (assoc 10 enx)) (- scl)) (cdr (assoc 12 enx)) ) ) (cdr (assoc 17 enx)) ) ) ;; Matrix Transpose - Doug Wilson ;; Args: m - nxn matrix (defun trp ( m ) (apply 'mapcar (cons 'list m)) ) ;; Matrix x Matrix - Vladimir Nesterovsky ;; Args: m,n - nxn matrices (defun mxm ( m n ) ((lambda ( a ) (mapcar '(lambda ( r ) (mxv a r)) m)) (trp n)) ) ;; Matrix x Vector - Vladimir Nesterovsky ;; Args: m - nxn matrix, v - vector in R^n (defun mxv ( m v ) (mapcar '(lambda ( r ) (apply '+ (mapcar '* r v))) m) ) ;; Vector x Scalar - Lee Mac ;; Args: v - vector in R^n, s - real scalar (defun vxs ( v s ) (mapcar '(lambda ( n ) (* n s)) v) ) ;; Start Undo - Lee Mac ;; Opens an Undo Group. (defun LM:startundo ( doc ) (LM:endundo doc) (vla-startundomark doc) ) ;; End Undo - Lee Mac ;; Closes an Undo Group. (defun LM:endundo ( doc ) (while (= 8 (logand 8 (getvar 'undoctl))) (vla-endundomark doc) ) ) ;; Active Document - Lee Mac ;; Returns the VLA Active Document Object (defun LM:acdoc nil (eval (list 'defun 'LM:acdoc 'nil (vla-get-activedocument (vlax-get-acad-object)))) (LM:acdoc) ) ;;----------------------------------------------------------------------;; (princ (strcat "\n:: VPOutline.lsp | Version 1.3 | \\U+00A9 Lee Mac " ((lambda ( y ) (if (= y (menucmd "m=$(edtime,0,yyyy)")) y (strcat y "-" (menucmd "m=$(edtime,0,yyyy)")))) "2015") " www.lee-mac.com ::" "\n:: \"vpo\" - Outline single viewport ::" "\n:: \"vpol\" - Outline all viewports in active layout ::" "\n:: \"vpoa\" - Outline all viewports in all layouts ::" ) ) (princ) ;;----------------------------------------------------------------------;; ;; End of File ;; ;;----------------------------------------------------------------------;;
16,241
Common Lisp
.l
368
34.453804
132
0.388635
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
f81050ef8a3492275e64078bbc97928e94b0937fda81e66106d47ee072d491b0
40,351
[ -1 ]
40,352
LM_BrowseForFolderV1-3.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/LM_BrowseForFolderV1-3.lsp
;; Browse for Folder - Lee Mac ;; Displays a dialog prompting the user to select a folder. ;; msg - [str] message to display at top of dialog ;; dir - [str] [optional] root directory (or nil) ;; bit - [int] bit-coded flag specifying dialog display settings ;; Returns: [str] Selected folder filepath, else nil. (defun LM:browseforfolder ( msg dir bit / err fld pth shl slf ) (setq err (vl-catch-all-apply (function (lambda ( / app hwd ) (if (setq app (vlax-get-acad-object) shl (vla-getinterfaceobject app "shell.application") hwd (vl-catch-all-apply 'vla-get-hwnd (list app)) fld (vlax-invoke-method shl 'browseforfolder (if (vl-catch-all-error-p hwd) 0 hwd) msg bit dir) ) (setq slf (vlax-get-property fld 'self) pth (vlax-get-property slf 'path) pth (vl-string-right-trim "\\" (vl-string-translate "/" "\\" pth)) ) ) ) ) ) ) (if slf (vlax-release-object slf)) (if fld (vlax-release-object fld)) (if shl (vlax-release-object shl)) (if (vl-catch-all-error-p err) (prompt (vl-catch-all-error-message err)) pth ) )
1,427
Common Lisp
.l
33
29.787879
126
0.508973
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
355065a9026f8ceaa36f18e5c56319ccc409afddfcc87e4f00b59bec0c196674
40,352
[ -1 ]
40,353
LM_BurstUpgradedV1-7.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/LM_BurstUpgradedV1-7.lsp
;;------------------------=={ Burst Upgraded }==------------------------;; ;; ;; ;; This program operates in much the same way as the familiar ;; ;; Express Tools' Burst command, however invisible block attributes ;; ;; are not displayed with the resulting exploded components. ;; ;; ;; ;; Following a valid selection of blocks to burst, the program ;; ;; converts all visible single-line & multi-line attributes into Text ;; ;; and MText respectively, before proceeding to explode the block, ;; ;; and deleting the original attribute objects. ;; ;; ;; ;; The core function accepts a selection set argument and may hence ;; ;; be called from within other custom programs to burst all blocks ;; ;; in a supplied selection set. ;; ;; ;; ;; The methods used by the program should also perform much faster & ;; ;; more efficiently than those used by the Express Tools' Burst.lsp. ;; ;;----------------------------------------------------------------------;; ;; Author: Lee Mac, Copyright © 2010 - www.lee-mac.com ;; ;;----------------------------------------------------------------------;; ;; Version 1.0 - 2010-11-25 ;; ;; ;; ;; - First release. ;; ;;----------------------------------------------------------------------;; ;; Version 1.1 - 2013-08-29 ;; ;; ;; ;; - Program entirely rewritten. ;; ;;----------------------------------------------------------------------;; ;; Version 1.2 - 2014-02-23 ;; ;; ;; ;; - Program restructured to accept selection set argument. ;; ;; - Program now also explodes non-attributed blocks. ;; ;;----------------------------------------------------------------------;; ;; Version 1.3 - 2015-10-31 ;; ;; ;; ;; - Program modified to account for non-uniformly scaled blocks. ;; ;; - Command syntax changed to 'myburst'. ;; ;;----------------------------------------------------------------------;; ;; Version 1.4 - 2018-01-06 ;; ;; ;; ;; - Program modified to retain visible constant attributes. ;; ;; - Corrected LM:usblock-p function to account for mirrored blocks. ;; ;;----------------------------------------------------------------------;; ;; Version 1.5 - 2018-07-09 ;; ;; ;; ;; - Accounted for multiline attributes whose text content occupies ;; ;; multiple group 1 & 3 DXF groups. ;; ;;----------------------------------------------------------------------;; ;; Version 1.6 - 2018-12-10 ;; ;; ;; ;; - Accounted for invisible objects created when bursting dynamic ;; ;; blocks with visibility states. ;; ;; - Fixed bug causing attributes with transparency to be removed. ;; ;; - Integrated Nested Burst program. ;; ;;----------------------------------------------------------------------;; ;; Version 1.7 - 2018-12-22 ;; ;; ;; ;; - Accounted for nested xrefs (excluding them from burst operation). ;; ;;----------------------------------------------------------------------;; (defun c:pburst nil (LM:burst nil)) (defun c:nburst nil (LM:burst t)) ;;----------------------------------------------------------------------;; (defun LM:burst ( nst / *error* ) (defun *error* ( msg ) (LM:endundo (LM:acdoc)) (if (not (wcmatch (strcase msg t) "*break,*cancel*,*exit*")) (princ (strcat "\nError: " msg)) ) (princ) ) (LM:startundo (LM:acdoc)) (LM:burstsel (LM:ssget "\nSelect blocks to burst: " (list "_:L" (append '((0 . "INSERT")) ( (lambda ( / def lst ) (while (setq def (tblnext "block" (null def))) (if (= 4 (logand 4 (cdr (assoc 70 def)))) (setq lst (vl-list* "," (cdr (assoc 2 def)) lst)) ) ) (if lst (list '(-4 . "<NOT") (cons 2 (apply 'strcat (cdr lst))) '(-4 . "NOT>"))) ) ) (if (= 1 (getvar 'cvport)) (list (cons 410 (getvar 'ctab))) '((410 . "Model")) ) ) ) ) nst ) (LM:endundo (LM:acdoc)) (princ) ) (defun LM:burstsel ( sel nst / idx ) (if (= 'pickset (type sel)) (repeat (setq idx (sslength sel)) (LM:burstobject (vlax-ename->vla-object (ssname sel (setq idx (1- idx)))) nst) ) ) ) (defun LM:burstobject ( obj nst / cmd col ent err lay lin lst qaf tmp ) (if (and (= "AcDbBlockReference" (vla-get-objectname obj)) (not (vlax-property-available-p obj 'path)) (vlax-write-enabled-p obj) (or (and (LM:usblock-p obj) (not (vl-catch-all-error-p (setq err (vl-catch-all-apply 'vlax-invoke (list obj 'explode))))) (setq lst err) ) (progn (setq tmp (vla-copy obj) ent (LM:entlast) cmd (getvar 'cmdecho) qaf (getvar 'qaflags) ) (setvar 'cmdecho 0) (setvar 'qaflags 0) (vl-cmdf "_.explode" (vlax-vla-object->ename tmp)) (setvar 'qaflags qaf) (setvar 'cmdecho cmd) (while (setq ent (entnext ent)) (setq lst (cons (vlax-ename->vla-object ent) lst)) ) lst ) ) ) (progn (setq lay (vla-get-layer obj) col (vla-get-color obj) lin (vla-get-linetype obj) ) (foreach att (vlax-invoke obj 'getattributes) (if (vlax-write-enabled-p att) (progn (if (= "0" (vla-get-layer att)) (vla-put-layer att lay) ) (if (= acbyblock (vla-get-color att)) (vla-put-color att col) ) (if (= "byblock" (strcase (vla-get-linetype att) t)) (vla-put-linetype att lin) ) ) ) (if (and (= :vlax-false (vla-get-invisible att)) (= :vlax-true (vla-get-visible att)) ) ( (if (and (vlax-property-available-p att 'mtextattribute) (= :vlax-true (vla-get-mtextattribute att))) LM:burst:matt2mtext LM:burst:att2text ) (entget (vlax-vla-object->ename att)) ) ) ) (foreach new lst (cond ( (not (vlax-write-enabled-p new))) ( (= :vlax-false (vla-get-visible new)) (vla-delete new) ) ( t (if (= "0" (vla-get-layer new)) (vla-put-layer new lay) ) (if (= acbyblock (vla-get-color new)) (vla-put-color new col) ) (if (= "byblock" (strcase (vla-get-linetype new) t)) (vla-put-linetype new lin) ) (if (= "AcDbAttributeDefinition" (vla-get-objectname new)) (progn (if (and (= :vlax-true (vla-get-constant new)) (= :vlax-false (vla-get-invisible new)) ) ( (if (and (vlax-property-available-p new 'mtextattribute) (= :vlax-true (vla-get-mtextattribute new))) LM:burst:matt2mtext LM:burst:att2text ) (entget (vlax-vla-object->ename new)) ) ) (vla-delete new) ) (if nst (LM:burstobject new nst)) ) ) ) ) (vla-delete obj) ) ) ) (defun LM:burst:removepairs ( itm lst ) (vl-remove-if '(lambda ( x ) (member (car x) itm)) lst) ) (defun LM:burst:remove1stpairs ( itm lst ) (vl-remove-if '(lambda ( x ) (if (member (car x) itm) (progn (setq itm (vl-remove (car x) itm)) t))) lst) ) (defun LM:burst:att2text ( enx ) (entmakex (append '((0 . "TEXT")) (LM:burst:removepairs '(000 002 003 070 074 100 280 440) (subst (cons 73 (cdr (assoc 74 enx))) (assoc 74 enx) enx) ) ) ) ) (defun LM:burst:matt2mtext ( enx ) (entmakex (append '((0 . "MTEXT") (100 . "AcDbEntity") (100 . "AcDbMText")) (LM:burst:remove1stpairs (if (= "ATTDEF" (cdr (assoc 0 enx))) '(001 003 007 010 040 041 050 071 072 073 210) '(001 007 010 040 041 050 071 072 073 210) ) (LM:burst:removepairs '(000 002 011 042 043 051 070 074 100 101 102 280 330 360 440) enx) ) (list (assoc 011 (reverse enx))) ) ) ) ;; Uniformly Scaled Block - Lee Mac ;; Returns T if the supplied VLA Block Reference is uniformly scaled ;; obj - [vla] VLA Block Reference (defun LM:usblock-p ( obj / s ) (if (vlax-property-available-p obj 'xeffectivescalefactor) (setq s "effectivescalefactor") (setq s "scalefactor") ) (eval (list 'defun 'LM:usblock-p '( obj ) (list 'and (list 'equal (list 'abs (list 'vlax-get-property 'obj (strcat "x" s))) (list 'abs (list 'vlax-get-property 'obj (strcat "y" s))) 1e-8 ) (list 'equal (list 'abs (list 'vlax-get-property 'obj (strcat "x" s))) (list 'abs (list 'vlax-get-property 'obj (strcat "z" s))) 1e-8 ) ) ) ) (LM:usblock-p obj) ) ;; entlast - Lee Mac ;; A wrapper for the entlast function to return the last subentity in the database (defun LM:entlast ( / ent tmp ) (setq ent (entlast)) (while (setq tmp (entnext ent)) (setq ent tmp)) ent ) ;; ssget - Lee Mac ;; A wrapper for the ssget function to permit the use of a custom selection prompt ;; msg - [str] selection prompt ;; arg - [lst] list of ssget arguments (defun LM:ssget ( msg arg / sel ) (princ msg) (setvar 'nomutt 1) (setq sel (vl-catch-all-apply 'ssget arg)) (setvar 'nomutt 0) (if (not (vl-catch-all-error-p sel)) sel) ) ;; Start Undo - Lee Mac ;; Opens an Undo Group. (defun LM:startundo ( doc ) (LM:endundo doc) (vla-startundomark doc) ) ;; End Undo - Lee Mac ;; Closes an Undo Group. (defun LM:endundo ( doc ) (while (= 8 (logand 8 (getvar 'undoctl))) (vla-endundomark doc) ) ) ;; Active Document - Lee Mac ;; Returns the VLA Active Document Object (defun LM:acdoc nil (eval (list 'defun 'LM:acdoc 'nil (vla-get-activedocument (vlax-get-acad-object)))) (LM:acdoc) ) ;;----------------------------------------------------------------------;; (vl-load-com) (princ (strcat "\n:: BurstUpgraded.lsp | Version 1.7 | \\U+00A9 Lee Mac " (menucmd "m=$(edtime,0,yyyy)") " www.lee-mac.com ::" "\n:: \"pburst\" to burst primary | \"nburst\" to burst primary + nested ::" ) ) (princ) ;;----------------------------------------------------------------------;; ;; End of File ;; ;;----------------------------------------------------------------------;;
14,210
Common Lisp
.l
310
33.054839
142
0.370368
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
cd6ee0d74431a1c5c895faa6a44d02f344af59430d842145c29f57c6d82253ab
40,353
[ 39064 ]
40,354
FieldsToText.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/FieldsToText.lsp
(defun C:CFT ()(ConvField->Text t)) (defun C:CFTAll ()(ConvField->Text nil)) (defun C:CFTSEL( / *error* Doc ss CountField) (vl-load-com) (defun *error* (msg)(princ msg)(vla-endundomark doc)(princ)) (setq Doc (vla-get-activedocument (vlax-get-acad-object))) (vla-startundomark Doc) (if (setq ss (ssget "_:L")) (progn (setq CountField 0) (foreach obj (mapcar (function vlax-ename->vla-object) (vl-remove-if (function listp) (mapcar (function cadr) (ssnamex ss)))) (setq CountField (ClearField Obj CountField)) ) (princ "\nConverting Field in ")(princ CountField) (princ " text's") ) ) (vla-endundomark Doc) (command "_.Regenall") ) (defun ClearField ( Obj CountField / txtstr att ) (cond ((and (vlax-write-enabled-p Obj) (= (vla-get-ObjectName obj) "AcDbBlockReference") (= (vla-get-HasAttributes obj) :vlax-true) ) ;_ end of and (foreach att (append (vlax-invoke obj 'Getattributes) (vlax-invoke obj 'Getconstantattributes) ) (setq txtstr (vla-get-Textstring att)) (vla-put-Textstring att "") (vla-put-Textstring att txtstr) (setq CountField (1+ CountField)) ) ;_ end of foreach ) ((and (vlax-write-enabled-p Obj) (vlax-property-available-p Obj 'TextString) ) ;_ end of and (setq txtstr (vla-get-Textstring Obj)) (vla-put-Textstring Obj "") (vla-put-Textstring Obj txtstr) (setq CountField (1+ CountField)) ) ((and (vlax-write-enabled-p Obj) ;_Table (eq (vla-get-ObjectName Obj) "AcDbTable") ) (and (vlax-property-available-p Obj 'RegenerateTableSuppressed) (vla-put-RegenerateTableSuppressed Obj :vlax-true) ) (VL-CATCH-ALL-APPLY '(lambda (col row / i j) (setq i '-1) (repeat col (setq i (1+ i) j '-1) (repeat row (setq j (1+ j)) (if (= (vla-GetCellType Obj j i) acTextCell) (vla-SetText Obj j i (vla-GetText Obj j i)) ) (setq CountField (1+ CountField)) ) ) ) (list (vla-get-Columns Obj) (vla-get-Rows Obj) ) ) (and (vlax-property-available-p Obj 'RegenerateTableSuppressed) (vla-put-RegenerateTableSuppressed Obj :vlax-false) ) ) (t nil) ) CountField ) (defun ConvField->Text ( Ask / Doc *error* ClearFieldInAllObjects ) ;;; t - Ask user nil - convert ;;; Как все поля чертежа сразу преобразовать в текст? ;;; Convert Field to Text ;;; Posted Vladimir Azarko (VVA) ;;; http://forum.dwg.ru/showthread.php?t=20190&page=2 ;;; http://forum.dwg.ru/showthread.php?t=20190 (vl-load-com) (defun *error* (msg)(princ msg) (mip:layer-status-restore) (vla-endundomark doc)(princ) ) (defun loc:msg-yes-no ( title message / WScript ret) (setq WScript (vlax-get-or-create-object "WScript.Shell")) (setq ret (vlax-invoke-method WScript "Popup" message "0" title (+ 4 48))) (vlax-release-object WScript) (= ret 6) ) (defun ClearFieldInAllObjects (Doc / txtstr tmp txt count CountField) (setq CountField 0) (vlax-for Blk (vla-get-Blocks Doc) (if (equal (vla-get-IsXref Blk) :vlax-false) ;;;kpbIc http://forum.dwg.ru/showpost.php?p=396910&postcount=30 (progn (setq count 0 txt (strcat "Changed " (vla-get-name Blk)) ) (grtext -1 txt) ;;; (terpri)(princ "=================== ")(princ txt) (if (not (wcmatch (vla-get-name Blk) "`*T*")) ;_exclude table (vlax-for Obj Blk (setq count (1+ count)) (if (zerop(rem count 10))(grtext -1 (strcat txt " : " (itoa count)))) (setq CountField (ClearField Obj CountField)) ) ;_ end of vlax-for ) ) ) ;_ end of if ) ;_ end of vlax-for (vl-cmdf "_redrawall") CountField ) (setq Doc (vla-get-activedocument (vlax-get-acad-object))) (mip:layer-status-save)(vla-startundomark Doc) (if (or (not Ask ) (if (= (getvar "DWGCODEPAGE") "ANSI_1251") (loc:msg-yes-no "Внимание" "Все поля будут преобразованы в текст !!!\nПродолжить?" ) (loc:msg-yes-no "Attension" "All fields will be transformed to the text!!!\nto Continue?" ) ) ) (progn (princ "\nConverting Field in ") (princ (ClearFieldInAllObjects Doc)) (princ " text's") ) (princ) ) (mip:layer-status-restore)(vla-endundomark Doc) (command "_.Regenall") (princ) ) (defun mip:layer-status-restore () (foreach item *MIP_LAYER_LST* (if (not (vlax-erased-p (car item))) (vl-catch-all-apply '(lambda () (vla-put-lock (car item) (cdr (assoc "lock" (cdr item)))) (vla-put-freeze (car item) (cdr (assoc "freeze" (cdr item))) ) ;_ end of vla-put-freeze ) ;_ end of lambda ) ;_ end of vl-catch-all-apply ) ;_ end of if ) ;_ end of foreach (setq *MIP_LAYER_LST* nil) ) ;_ end of defun (defun mip:layer-status-save () (setq *MIP_LAYER_LST* nil) (vlax-for item (vla-get-layers (vla-get-activedocument (vlax-get-acad-object)) ) ;_ end of vla-get-layers (setq *MIP_LAYER_LST* (cons (list item (cons "freeze" (vla-get-freeze item)) (cons "lock" (vla-get-lock item)) ) ;_ end of cons *MIP_LAYER_LST* ) ;_ end of cons ) ;_ end of setq (vla-put-lock item :vlax-false) (if (= (vla-get-freeze item) :vlax-true) (vl-catch-all-apply '(lambda () (vla-put-freeze item :vlax-false)) ) ;_ end of vl-catch-all-apply ) ;_ end of if ) ;_ end of vlax-for ) ;_ end of defun
5,923
Common Lisp
.l
180
25.733333
113
0.575087
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
464f360fa88714c33e17c3d80ad2c2e3c7f122e0c6ac500071cf3a6ff2147c42
40,354
[ -1 ]
40,355
PlineExtrim.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/PlineExtrim.lsp
(defun C:OCDD ( / en ss lst ssall bbox) (vl-load-com) (if (and (setq sset (ssget "x" '((0 . "*POLYLINE") (8 . "VPOutline")))) (setq en (ssname sset 0)) ) (progn (setq bbox (ACET-GEOM-SS-EXTENTS sset T)) (setq bbox (mapcar '(lambda(x)(trans x 0 1)) bbox)) (setq lst (ACET-GEOM-OBJECT-POINT-LIST en 1e-3)) (ACET-SS-ZOOM-EXTENTS sset) (command "_.Zoom" "0.95x") (if (null etrim)(load "extrim.lsp")) (etrim en (polar (car bbox) (angle (car bbox)(cadr bbox)) (* (distance (car bbox)(cadr bbox)) 1.1) ) ) (if ; Если после этого, снаружи полилинии остались примитивы, удалить их (and (setq ss (ssget "_CP" lst)) (setq ssall (ssget "_X" (list (assoc 410 (entget en))))) ) (progn (setq lst (vl-remove-if 'listp (mapcar 'cadr (ssnamex ss)))) (foreach e1 lst (ssdel e1 ssall)) (ACET-SS-ENTDEL ssall) ) ) ) ) )
923
Common Lisp
.l
36
21.222222
72
0.585034
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
158a002a041dc358b641cba2ef37dd4293471ff6fbf55ce4a18e4c7eed690c96
40,355
[ -1 ]
40,356
LM_DrawOrderV1-2.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/LM_DrawOrderV1-2.lsp
;; Move to Top - Lee Mac ;; Moves a set of objects to the top of the draw order. ;; obs - [lst/sel] Selection set or list of objects with same owner ;; Returns: T if successful, else nil (defun LM:movetotop ( obs / tab ) (if (and (or (= 'list (type obs)) (setq obs (LM:ss->vla obs))) (setq tab (LM:sortentstable (LM:getowner (car obs)))) ) (not (vla-movetotop tab (LM:safearrayvariant vlax-vbobject obs))) ) ) ;; Move to Bottom - Lee Mac ;; Moves a set of objects to the bottom of the draw order. ;; obs - [lst/sel] Selection set or list of objects with same owner ;; Returns: T if successful, else nil (defun LM:movetobottom ( obs / tab ) (if (and (or (= 'list (type obs)) (setq obs (LM:ss->vla obs))) (setq tab (LM:sortentstable (LM:getowner (car obs)))) ) (not (vla-movetobottom tab (LM:safearrayvariant vlax-vbobject obs))) ) ) ;; Move Above - Lee Mac ;; Moves a set of objects above a supplied object in the draw order. ;; obs - [lst/sel] Selection set or list of objects with same owner ;; obj - [vla] Object above which to move supplied objects ;; Returns: T if successful, else nil (defun LM:moveabove ( obs obj / tab ) (if (and (or (= 'list (type obs)) (setq obs (LM:ss->vla obs))) (setq tab (LM:sortentstable (LM:getowner (car obs)))) ) (not (vla-moveabove tab (LM:safearrayvariant vlax-vbobject obs) obj)) ) ) ;; Move Below - Lee Mac ;; Moves a set of objects below a supplied object in the draw order. ;; obs - [lst/sel] Selection set or list of objects with same owner ;; obj - [vla] Object below which to move supplied objects ;; Returns: T if successful, else nil (defun LM:movebelow ( obs obj / tab ) (if (and (or (= 'list (type obs)) (setq obs (LM:ss->vla obs))) (setq tab (LM:sortentstable (LM:getowner (car obs)))) ) (not (vla-movebelow tab (LM:safearrayvariant vlax-vbobject obs) obj)) ) ) ;; Swap Order - Lee Mac ;; Swaps the draw order of two objects (may require regen). ;; ob1,ob2 - [vla] Objects to swap ;; Returns: T if successful, else nil (defun LM:swaporder ( ob1 ob2 / tab ) (if (setq tab (LM:sortentstable (LM:getowner ob1))) (not (vla-swaporder tab ob1 ob2)) ) ) ;; Get Owner - Lee Mac ;; A wrapper for the objectidtoobject method & ownerid property to enable ;; compatibility with 32-bit & 64-bit systems (defun LM:getowner ( obj ) (eval (list 'defun 'LM:getowner '( obj ) (if (vlax-method-applicable-p obj 'ownerid32) (list 'vla-objectidtoobject32 (LM:acdoc) '(vla-get-ownerid32 obj)) (list 'vla-objectidtoobject (LM:acdoc) '(vla-get-ownerid obj)) ) ) ) (LM:getowner obj) ) ;; Catch Apply - Lee Mac ;; Applies a function to a list of parameters and catches any exceptions. (defun LM:catchapply ( fnc prm / rtn ) (if (not (vl-catch-all-error-p (setq rtn (vl-catch-all-apply fnc prm)))) rtn ) ) ;; Sortents Table - Lee Mac ;; Retrieves the Sortents Table object. ;; obj - [vla] Block Container Object (defun LM:sortentstable ( obj / dic ) (cond ( (LM:catchapply 'vla-item (list (setq dic (vla-getextensiondictionary obj)) "acad_sortents"))) ( (LM:catchapply 'vla-addobject (list dic "acad_sortents" "AcDbSortentsTable"))) ) ) ;; Selection Set to VLA Objects - Lee Mac ;; Converts a Selection Set to a list of VLA Objects ;; sel - [sel] Selection set (pickset) (defun LM:ss->vla ( sel / idx lst ) (if (= 'pickset (type sel)) (repeat (setq idx (sslength sel)) (setq lst (cons (vlax-ename->vla-object (ssname sel (setq idx (1- idx)))) lst)) ) ) ) ;; Safearray Variant - Lee Mac ;; Returns a populated safearray variant of a specified data type ;; typ - [int] Variant type enum (e.g. vlax-vbdouble) ;; lst - [lst] List of static type data (defun LM:safearrayvariant ( typ lst ) (vlax-make-variant (vlax-safearray-fill (vlax-make-safearray typ (cons 0 (1- (length lst)))) lst ) ) ) ;; Active Document - Lee Mac ;; Returns the VLA Active Document Object (defun LM:acdoc nil (eval (list 'defun 'LM:acdoc 'nil (vla-get-activedocument (vlax-get-acad-object)))) (LM:acdoc) ) (vl-load-com) (princ)
4,486
Common Lisp
.l
114
33.640351
106
0.626386
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
1ce303c4b53ce87a4ba92021cab9c4aad030eecf92d186a7666b51b167867007
40,356
[ 449806 ]
40,357
KG_LayoutsToDwgs.lsp
AndreyAdamenko_ACADbreakDrawingByLayouts/KG_LayoutsToDwgs.lsp
; BreakDrawingByLayouts (defun KG:BreakDwg ( / *error* DelAllLayouts CopyModelToDwg SaveToNewDwg BindAndExplodeXrefs TextToForward GetNamingType osmodeOld dwgResultFolder layDwgWasCreated layDwgName dwgLayExists vpCurI vpSs curVP modelSs namingType oldEcho ) (vl-load-com) (setq oldEcho (getvar "CMDECHO")) (setvar "CMDECHO" 0) (defun *error* (msg) (if oldEcho (setvar "CMDECHO" oldEcho)) (if osmodeOld (setvar "OSMODE" osmodeOld)) (if (not (member msg '("Function cancelled" "Функция отменена" "quit / exit abort"))) (princ (strcat "\nError: " msg "\n")) ) (exit) ) (load "LM_ViewportOutline.lsp") (load "PlineExtrim.lsp") (load "LM_Copy2DrawingsV1-3_KGedition.lsp") (load "LM_BurstUpgradedV1-7.lsp") (load "FieldsToText.lsp") (load "LM_DrawOrderV1-2.lsp") (load "LM_BrowseForFolderV1-3.lsp") (defun LM:str->lst ( str del / pos ) (if (setq pos (vl-string-search del str)) (cons (substr str 1 pos) (LM:str->lst (substr str (+ pos 1 (strlen del))) del)) (list str) ) ) (defun LM:createdirectory ( dir ) ( (lambda ( fun ) ( (lambda ( lst ) (fun (car lst) (cdr lst))) (vl-remove "" (LM:str->lst (vl-string-translate "/" "\\" dir) "\\")) ) ) (lambda ( root lst / dir ) (if lst (if (or (vl-file-directory-p (setq dir (strcat root "\\" (car lst)))) (vl-mkdir dir)) (fun dir (cdr lst)) ) ) ) ) (vl-file-directory-p dir) ) (defun DelAllLayouts (Keeper / TabName) (vlax-for Layout (vla-get-Layouts (vla-get-activedocument (vlax-get-acad-object)) ) (if (and (/= (setq TabName (strcase (vla-get-name layout))) "MODEL") (/= TabName (strcase Keeper)) ) (progn (vla-delete layout) ) ) ) ) (defun CopyModelToDwg ( dwgName / ) (c2dwg (ssget "_X" '((410 . "Model"))) (list dwgName) ) ) (defun SaveToNewDwg ( dwgName / ) (command "_.-wblock" dwgName) (if (findfile dwgName) (command "_Y") ) (command "*") (if (equal 1 (logand 1 (getvar "cmdactive"))) (command "_Y") ) ) (defun BindAndExplodeXrefs ( / insSs ) (command "_.-xref" "_b" "*") (ConvField->Text nil) (if (setq insSs (ssget "_X" '((0 . "INSERT")(410 . "Model")))) (LM:burstsel insSs T) ) ) (defun TextToForward ( / insSs ) (setq insSs (ssget "_X" '((0 . "MTEXT,TEXT")(410 . "Model")))) (LM:movetotop insSs) ) (defun GetNamingType ( / naming ) (initget "Layout File+Layout") (setq naming (getkword (strcat "\nResult naming type [Layout/File+Layout] <Layout> :"))) (if (null naming) (setq naming "Layout") ) naming ) (setq dwgResultFolder (getvar "DWGPREFIX")) (if (setq dwgResultFolder (LM:browseforfolder "The current drawing will be split into sheets.\nSpecify the folder to place them:" nil 0)) (progn (setq namingType (GetNamingType)) (setq osmodeOld (getvar "OSMODE")) (if (not (vl-file-directory-p dwgResultFolder)) (LM:createdirectory dwgResultFolder) ) (command "._undo" "_BE") (setvar "CTAB" "MODEL") (command "_.undo" "_M") ; Initial drawing state (1) (BindAndExplodeXrefs) (command "_HATCHTOBACK") (TextToForward) (command "_.undo" "_M") ; Reference Exploded (2) (foreach lay (layoutlist) (DelAllLayouts lay) (command "_.undo" "_M") ; Full sheet (3) (setvar "CTAB" lay) (setq layDwgWasCreated nil) (setq layDwgName (if (eq namingType "Layout") (strcat dwgResultFolder "\\" lay ".dwg") (strcat dwgResultFolder "\\" (vl-filename-base (getvar "DWGNAME")) "_" lay ".dwg") ) ) (setq dwgLayExists (findfile layDwgName)) (setq vpCurI -1) (setq vpSs (ssget "_X" '((0 . "VIEWPORT")(8 . "~0")))) (if vpSs (while (setq curVP (ssname vpSs (setq vpCurI (1+ vpCurI)))) (vpo:main curVP) (setvar "CTAB" "MODEL") (C:OCDD) ; Save current state of drawing (if layDwgWasCreated (CopyModelToDwg layDwgName) (progn (SaveToNewDwg layDwgName) (setq layDwgWasCreated T) ) ) (command "_.undo" "_B") (command "_.undo" "_M") ) (progn ;(setvar "CTAB" "MODEL") (if (setq modelSs (ssget "_x" '((410 . "Model")))) (command "_.Erase" modelSs "") ) ; Save current state of drawing (if layDwgWasCreated (CopyModelToDwg layDwgName) (progn (SaveToNewDwg layDwgName) (setq layDwgWasCreated T) ) ) (command "_.undo" "_B") (command "_.undo" "_M") ) ) (command "_.undo" "_B") (command "_.undo" "_B") (command "_.undo" "_M") ) (command "_.undo" "_B") (command "_.undo" "_B" "_Y") (command "._undo" "_E") (setvar "OSMODE" osmodeOld) (setvar "CMDECHO" oldEcho) (princ "Finish!\n") ) ) (princ) )
5,233
Common Lisp
.l
170
23.758824
235
0.586581
AndreyAdamenko/ACADbreakDrawingByLayouts
0
0
0
GPL-3.0
9/19/2024, 11:48:07 AM (Europe/Amsterdam)
fee9482433551a04450690e34d810ee86a5097759548884caa7b75ff6325a510
40,357
[ -1 ]
40,380
00-prelude.lisp
vlad-km_mLisa/00-prelude.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package :lilu) (make-package :lilu :use (list 'cl))) (unless (find-package :lisa) (make-package :lisa :use (list 'cl))) (unless (find-package :lisa-user) (make-package :lisa-user :use (list 'cl))) (unless (find-package :reflect) (make-package :reflect :use (list 'cl))) (unless (find-package :belief) (make-package :belief :use (list 'cl))) (unless (find-package :heap) (make-package :heap :use (list 'cl)))) (defun assert-error (form datum &rest args) (error (if datum (jscl::%%coerce-condition 'simple-error datum args) (make-condition 'simple-error :format-control "Assert failed: ~s." :format-arguments (list form))))) (defmacro assert (test &optional ignore datum &rest args) (let ((value (gensym "ASSERT-VALUE")) (name (gensym "ASSERT-BLOCK"))) `(block ,name (let ((,value ,test)) (when (not ,value) (assert-error ',test ,datum ,@args)))))) (defun equalp (x y) (typecase x (number (and (numberp y) (= x y))) (character (and (characterp y) (char-equal x y))) (hash-table (and (hash-table-p y) (eql (hash-table-count x)(hash-table-count y)) (eql (hash-table-test x)(hash-table-test y)) (block nil (if (= (hash-table-count x) 0) t (maphash (lambda (k v) (multiple-value-bind (other-v present-p) (gethash k y) (when (or (not present-p) (not (equalp v other-v))) (return nil)))) x) )))) (cons (and (consp y) (equalp (car x) (car y)) (equalp (cdr x) (cdr y)))) (vector (and (vectorp y) (let ((lex (length x))) (= lex (length y)) (dotimes (i lex t) (when (not (equalp (aref x i) (aref y i))) (return nil)))))) (array (and (arrayp y) (equalp (array-dimensions x) (array-dimensions y)) (dotimes (i (length x) t) (when (not (equalp (aref x i) (aref y i))) (return nil))))) (t (equal x y)))) (defun vector-pop (vector) (let ((element (aref vector (1- (length vector))))) (decf (fill-pointer vector)) element)) ;;; EOF
2,586
Common Lisp
.lisp
73
26.739726
60
0.535572
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
99a6ac68e49e42e5d0298e99b80a388819f6957472e27dfbb222e8f1de3c813a
40,380
[ -1 ]
40,381
05-rete.lisp
vlad-km_mLisa/05-rete.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) ;;; $Id: node-tests.lisp,v 1.24 2007/09/17 22:42:39 youngde Exp $ (defvar *node-test-table*) (defun find-test (key constructor) (let ((test (gethash key *node-test-table*))) (when (null test) (setq test (setf (gethash key *node-test-table*) (funcall constructor)))) test)) (defun clear-node-test-table () (clrhash *node-test-table*)) (defgeneric class-matches-p (instance fact class)) (defmethod class-matches-p ((instance inference-engine-object) fact class) (eq (fact-name fact) class)) (defmethod class-matches-p ((instance t) fact class) (or (eq (fact-name fact) class) (has-superclass fact class))) (defun make-class-test (class) (find-test class #'(lambda () (function (lambda (token) ;;(declare (optimize (speed 3) (debug 1) (safety 0))) (let ((fact (token-top-fact token))) (class-matches-p (find-instance-of-fact fact) fact class))))))) (defun make-simple-slot-test-aux (slot-name value negated-p) (find-test `(,slot-name ,value ,negated-p) #'(lambda () (let ((test (function (lambda (token) (equal value (get-slot-value (token-top-fact token) slot-name)))))) (if negated-p (complement test) test))))) (defun make-simple-slot-test (slot) (make-simple-slot-test-aux (pattern-slot-name slot) (pattern-slot-value slot) (pattern-slot-negated slot))) #+nul (defmacro make-variable-test (slot-name binding) `(function (lambda (tokens) (equal (get-slot-value (token-top-fact tokens) ,slot-name) (get-slot-value (token-find-fact tokens (binding-address ,binding)) (binding-slot-name ,binding)))))) (defun make-inter-pattern-test (slot) (let* ((binding (pattern-slot-slot-binding slot)) (test (function (lambda (tokens) (equal (get-slot-value (token-top-fact tokens) (pattern-slot-name slot)) (get-slot-value (token-find-fact tokens (binding-address binding)) (binding-slot-name binding))))))) (if (negated-slot-p slot) (complement test) test))) (defun maklet-predicate-test (predicate-forms bindings) (let* ((special-vars (mapcar #'binding-variable bindings)) (valuator-form '(valuator (lambda (binding) (if (pattern-binding-p binding) (token-find-fact tokens (binding-address binding)) (get-slot-value (token-find-fact tokens (binding-address binding)) (binding-slot-name binding)))))) (binding-pairs (loop for symbol-name in special-vars for binding in bindings append (list (list symbol-name (list 'funcall 'valuator (list 'quote binding)))))) (binding-form (push valuator-form binding-pairs)) (let-form (append (list binding-form) predicate-forms))) (push 'let* let-form) let-form)) (defun make-predicate-test (forms bindings &optional (negated-p nil)) (let* ((special-vars (mapcar #'binding-variable bindings)) (body (if (consp (first forms)) forms (list forms))) (test (eval `(lambda (tokens) ,(maklet-predicate-test `,body `,bindings))))) (if negated-p (complement test) test))) ;;; original make-predicate-test with PROGV #+nil (defun make-predicate-test (forms bindings &optional (negated-p nil)) (let* ((special-vars (mapcar #'binding-variable bindings)) (body (if (consp (first forms)) forms (list forms))) (predicate (compile nil `(lambda () ;;(declaim ,@special-vars) ,@body))) (test (function (lambda (tokens) (progv `(,@special-vars) `(,@(mapcar #'(lambda (binding) (if (pattern-binding-p binding) (token-find-fact tokens (binding-address binding)) (get-slot-value (token-find-fact tokens (binding-address binding)) (binding-slot-name binding)))) bindings)) (funcall predicate)))))) (if negated-p (complement test) test))) (defun maklet-pattern-predicate-test (predicate-forms bindings) (let* ((special-vars (mapcar #'binding-variable bindings)) (valuator-form '(valuator (lambda (binding) (if (pattern-binding-p binding) (token-find-fact tokens (binding-address binding)) (get-slot-value (token-top-fact tokens) (binding-slot-name binding)))))) (binding-pairs (loop for symbol-name in special-vars for binding in bindings append (list (list symbol-name (list 'funcall 'valuator (list 'quote binding)))))) (binding-form (push valuator-form binding-pairs)) (let-form (append (list binding-form) predicate-forms))) (push 'let* let-form) let-form)) (defun make-intra-pattern-predicate (forms bindings negated-p) (let* ((special-vars (mapcar #'binding-variable bindings)) (body (if (consp (first forms)) forms (list forms))) (test (eval `(lambda (tokens) ,(maklet-pattern-predicate-test `,body `,bindings))))) (if negated-p (complement test) test))) ;;; original make-intra-pattern-predicate with PROGV #+nil (defun make-intra-pattern-predicate (forms bindings negated-p) (let* ((special-vars (mapcar #'binding-variable bindings)) (body (if (consp (first forms)) forms (list forms))) (predicate (compile nil `(lambda () ;;(declare (special ,@special-vars)) ,@body))) (test (function (lambda (tokens) (progv `(,@special-vars) `(,@(mapcar #'(lambda (binding) (if (pattern-binding-p binding) (token-find-fact tokens (binding-address binding)) (get-slot-value (token-top-fact tokens) (binding-slot-name binding)))) bindings)) (funcall predicate)))))) (if negated-p (complement test) test))) (defun make-intra-pattern-constraint-test (slot) (make-intra-pattern-predicate (pattern-slot-constraint slot) (pattern-slot-constraint-bindings slot) (negated-slot-p slot))) (defun make-intra-pattern-test (slot) (let ((test (function (lambda (tokens) (equal (get-slot-value (token-top-fact tokens) (pattern-slot-name slot)) (get-slot-value (token-top-fact tokens) (binding-slot-name (pattern-slot-slot-binding slot)))))))) (if (negated-slot-p slot) (complement test) test))) (defun make-behavior (function bindings) (make-predicate-test function bindings)) ;;; File: node2-test.lisp ;;; GENERIC (defgeneric accept-token (node1 token)) (defgeneric accept-token-from-right (join-node reset-token)) (defgeneric accept-tokens-from-left (node token)) (defgeneric add-successor (node1 node1 connector)) (defgeneric clear-memories (join-node)) (defgeneric combine-tokens (token token)) (defgeneric increment-use-count (shared-node)) (defgeneric join-node-add-test (join-node test)) (defgeneric node-referenced-p (shared-node)) (defgeneric node-use-count (shared-node)) (defgeneric pass-token-to-successors (shared-node token)) (defgeneric remove-successor (node1 successor-node)) (defgeneric test-against-left-memory (node2 add-token)) (defgeneric test-against-right-memory (node2 left-tokens)) (defgeneric test-tokens (join-node left-tokens right-token)) ;;;(defgeneric accept-token (terminal-node add-token)) ;;;(defgeneric accept-token-from-left (join-node reset-token)) ;;;(defgeneric add-node-set (parent node &optional count-p )) ;;;(defgeneric add-successor (join-node successor-node connector)) ;;;(defgeneric add-successor (parent new-node connector)) ;;;(defgeneric decrement-use-count (join-node)) ;;;(defgeneric decrement-use-count (shared-node)) ;;;(defgeneric find-existing-successor (shared-node node1)) (defgeneric pass-tokens-to-successor (join-node left-tokens)) (defgeneric remove-node-from-parent (rete-network parent child)) ;;; CLASSES (defclass shared-node () ((successors :initform (make-hash-table :test #'equal) :reader shared-node-successors) (refcnt :initform 0 :accessor shared-node-refcnt))) (defclass terminal-node () ((rule :initarg :rule :initform nil :reader terminal-node-rule))) (defclass node1 (shared-node) ((test :initarg :test :reader node1-test))) (defclass join-node () ((successor :initform nil :accessor join-node-successor) (logical-block :initform nil :reader join-node-logical-block) (tests :initform (list) :accessor join-node-tests) (left-memory :initform (make-hash-table :test #'equal) :reader join-node-left-memory) (right-memory :initform (make-hash-table :test #'equal) :reader join-node-right-memory))) (defclass node2 (join-node) ()) (defclass node2-not (join-node) ()) (defclass node2-test (join-node) ()) (defclass node2-exists (join-node) ()) (defclass rete-network () ((root-nodes :initform (make-hash-table) :initarg :root-nodes :reader rete-roots) (node-test-cache :initform (make-hash-table :test #'equal) :initarg :node-test-cache :reader node-test-cache))) (defgeneric mak-hash-successor-node (node)) (defmethod mak-hash-successor-node (node) (write-to-string node)) (defmethod mak-hash-successor-node ((node shared-node)) (list 'shared-node 'successors (hash-table-count (shared-node-successors node)) 'refcnt (shared-node-refcnt node)) ) (defmethod mak-hash-successor-node ((node node1)) (list 'node1 'successors (hash-table-count (shared-node-successors node)) 'refcnt (shared-node-refcnt node)) ) (defmethod mak-hash-successor-node ((node node2)) (list 'node2 'successors (join-node-successor node) 'logical (join-node-logical-block node) 'left (hash-table-count (join-node-left-memory node)) 'right (hash-table-count (join-node-right-memory node))) ) (defmethod mak-hash-successor-node ((node node2-not)) (list 'node2-not 'successors (join-node-successor node) 'logical (join-node-logical-block node) 'left (hash-table-count (join-node-left-memory node)) 'right (hash-table-count (join-node-right-memory node)))) (defmethod mak-hash-successor-node ((node node2-test)) (list 'node2-test 'successors (join-node-successor node) 'logical (join-node-logical-block node) 'left (hash-table-count (join-node-left-memory node)) 'right (hash-table-count (join-node-right-memory node)))) (defmethod mak-hash-successor-node ((node node2-exists)) (list 'node2-exists 'successors (join-node-successor node) 'logical (join-node-logical-block node) 'left (hash-table-count (join-node-left-memory node)) 'right (hash-table-count (join-node-right-memory node)))) ;;;;;; METHODS (defmethod accept-tokens-from-left ((self node2-test) (left-tokens add-token)) (add-tokens-to-left-memory self left-tokens) (when (every #'(lambda (test) (funcall test left-tokens)) (join-node-tests self)) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defmethod accept-tokens-from-left ((self node2-test) (left-tokens remove-token)) (when (remove-tokens-from-left-memory self left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defun make-node2-test () (make-instance 'node2-test)) ;;; File: shared-node.lisp #+nil (defclass shared-node () ((successors :initform (make-hash-table :test #'equal) :reader shared-node-successors) (refcnt :initform 0 :accessor shared-node-refcnt))) (defmethod increment-use-count ((self shared-node)) (incf (shared-node-refcnt self))) #+nil (defmethod decrement-use-count ((self shared-node)) (decf (shared-node-refcnt self))) (defmethod node-use-count ((self shared-node)) (shared-node-refcnt self)) (defmethod node-referenced-p ((self shared-node)) (plusp (node-use-count self))) #+nil (defmethod pass-token-to-successors ((self shared-node) token) (loop for successor being the hash-values of (shared-node-successors self) do (funcall (successor-connector successor) (successor-node successor) token))) (defmethod pass-token-to-successors ((self shared-node) token) (loop for successor in (jscl::hash-table-values (shared-node-successors self)) do (funcall (successor-connector successor) (successor-node successor) token))) #+nil (defun shared-node-successor-nodes (shared-node) (loop for successor being the hash-values of (shared-node-successors shared-node) collect (successor-node successor))) (defun shared-node-successor-nodes (shared-node) (loop for successor in (jscl::hash-table-values (shared-node-successors shared-node)) collect (successor-node successor))) #+nil (defun shared-node-all-successors (shared-node) (loop for successor being the hash-values of (shared-node-successors shared-node) collect successor)) (defun shared-node-all-successors (shared-node) (loop for successor in (jscl::hash-table-values (shared-node-successors shared-node)) collect successor)) ;;; File: successor.lisp (defun make-successor (node connector) (cons node connector)) (defun successor-node (successor) (car successor)) (defun successor-connector (successor) (cdr successor)) (defun call-successor (successor &rest args) (apply #'funcall (successor-connector successor) (successor-node successor) args)) ;;; File: node-pair.lisp (defun make-node-pair (child parent) (cons child parent)) (defun node-pair-child (node-pair) (car node-pair)) (defun node-pair-parent (node-pair) (cdr node-pair)) ;;; File: terminal-node.lisp #+nil (defclass terminal-node () ((rule :initarg :rule :initform nil :reader terminal-node-rule))) (defmethod accept-token ((self terminal-node) (tokens add-token)) (let* ((rule (terminal-node-rule self)) (activation (make-activation rule tokens))) (add-activation (rule-engine rule) activation) (bind-rule-activation rule activation tokens) t)) (defmethod accept-token ((self terminal-node) (tokens remove-token)) (let* ((rule (terminal-node-rule self)) (activation (find-activation-binding rule tokens))) (unless (null activation) (disable-activation (rule-engine rule) activation) (unbind-rule-activation rule tokens)) t)) (defmethod accept-token ((self terminal-node) (token reset-token)) (clear-activation-bindings (terminal-node-rule self)) t) #+nil (defmethod print-object ((self terminal-node) strm) (print-unreadable-object (self strm :type t) (format strm "~A" (rule-name (terminal-node-rule self))))) (defun make-terminal-node (rule) (make-instance 'terminal-node :rule rule)) ;;; File: node1.lisp #+nil (defclass node1 (shared-node) ((test :initarg :test :reader node1-test))) (defmethod add-successor ((self node1) (new-node node1) connector) (with-slots ((successor-table successors)) self (let ((successor (gethash (node1-test new-node) successor-table))) (when (null successor) (setf successor (setf (gethash (node1-test new-node) successor-table) (make-successor new-node connector)))) (successor-node successor)))) ;;; original add-successor #+nil (defmethod add-successor ((self node1) (new-node t) connector) (print 'add-successor-setf-key) (setf (gethash `(,new-node ,connector) (shared-node-successors self)) (make-successor new-node connector)) new-node) (defun mak-hash-successor (node connector) (let ((h (list (mak-hash-successor-node node) (write-to-string connector)))) h)) (defmethod add-successor ((self node1) (new-node t) connector) (setf (gethash (mak-hash-successor new-node connector) (shared-node-successors self)) (make-successor new-node connector)) new-node) (defmethod remove-successor ((self node1) successor-node) (let ((successors (shared-node-successors self))) (maphash #'(lambda (key successor) (when (eq successor-node (successor-node successor)) (remhash key successors))) successors) successor-node)) (defmethod accept-token ((self node1) token) (if (funcall (node1-test self) token) (pass-token-to-successors self token) nil)) (defmethod accept-token ((self node1) (token reset-token)) (pass-token-to-successors self (token-push-fact token t))) #+nil (defmethod print-object ((self node1) strm) (print-unreadable-object (self strm :type t :identity t) (format strm "~S ; ~D" (node1-test self) (node-use-count self)))) (defun make-node1 (test) (make-instance 'node1 :test test)) ;;; File: join-node.lisp (defun mark-as-logical-block (join-node marker) (setf (slot-value join-node 'logical-block) marker)) (defun logical-block-p (join-node) (numberp (join-node-logical-block join-node))) (defun remember-token (memory token) (setf (gethash (hash-key token) memory) token)) (defun forget-token (memory token) (remhash (hash-key token) memory)) (defun add-tokens-to-left-memory (join-node tokens) (remember-token (join-node-left-memory join-node) tokens)) (defun add-token-to-right-memory (join-node token) (remember-token (join-node-right-memory join-node) token)) (defun remove-tokens-from-left-memory (join-node tokens) (forget-token (join-node-left-memory join-node) tokens)) (defun remove-token-from-right-memory (join-node token) (forget-token (join-node-right-memory join-node) token)) (defun left-memory-count (join-node) (hash-table-count (join-node-left-memory join-node))) (defun right-memory-count (join-node) (hash-table-count (join-node-right-memory join-node))) (defmethod test-tokens ((self join-node) left-tokens right-token) (token-push-fact left-tokens (token-top-fact right-token)) (prog1 (every #'(lambda (test) (funcall test left-tokens)) (join-node-tests self)) (token-pop-fact left-tokens))) (defmethod pass-tokens-to-successor ((self join-node) left-tokens) (call-successor (join-node-successor self) left-tokens)) (defmethod combine-tokens ((left-tokens token) (right-token token)) (token-push-fact (replicate-token left-tokens) (token-top-fact right-token))) (defmethod combine-tokens ((left-tokens token) (right-token t)) (token-push-fact (replicate-token left-tokens) right-token)) (defmethod add-successor ((self join-node) successor-node connector) (setf (join-node-successor self) (make-successor successor-node connector))) (defmethod join-node-add-test ((self join-node) test) (push test (join-node-tests self))) (defmethod clear-memories ((self join-node)) (clrhash (join-node-left-memory self)) (clrhash (join-node-right-memory self))) (defmethod accept-tokens-from-left ((self join-node) (left-tokens reset-token)) (clear-memories self) (pass-tokens-to-successor self left-tokens)) (defmethod accept-token-from-right ((self join-node) (left-tokens reset-token)) nil) #+nil (defmethod print-object ((self join-node) strm) (print-unreadable-object (self strm :type t :identity t) (format strm "left ~S ; right ~S ; tests ~S" (left-memory-count self) (right-memory-count self) (length (join-node-tests self))))) ;;; File: node2.lisp #+nil (defmethod test-against-right-memory ((self node2) left-tokens) (loop for right-token being the hash-values of (join-node-right-memory self) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) (defmethod test-against-right-memory ((self node2) left-tokens) (loop for right-token in (jscl::hash-table-values (join-node-right-memory self)) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) #+nil (defmethod test-against-left-memory ((self node2) (right-token add-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) (defmethod test-against-left-memory ((self node2) (right-token add-token)) (loop for left-tokens in (jscl::hash-table-values (join-node-left-memory self)) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) #+nil (defmethod test-against-left-memory ((self node2) (right-token remove-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) right-token))))) (defmethod test-against-left-memory ((self node2) (right-token remove-token)) (loop for left-tokens in (jscl::hash-table-values (join-node-left-memory self)) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) right-token))))) (defmethod accept-tokens-from-left ((self node2) (left-tokens add-token)) (add-tokens-to-left-memory self left-tokens) (test-against-right-memory self left-tokens)) (defmethod accept-token-from-right ((self node2) (right-token add-token)) (add-token-to-right-memory self right-token) (test-against-left-memory self right-token)) (defmethod accept-tokens-from-left ((self node2) (left-tokens remove-token)) (when (remove-tokens-from-left-memory self left-tokens) (test-against-right-memory self left-tokens))) (defmethod accept-token-from-right ((self node2) (right-token remove-token)) (when (remove-token-from-right-memory self right-token) (test-against-left-memory self right-token))) (defun make-node2 () (make-instance 'node2)) ;;; File: node2-not.lisp #+nil (defmethod test-against-right-memory ((self node2-not) left-tokens) (loop for right-token being the hash-values of (join-node-right-memory self) do (when (test-tokens self left-tokens right-token) (token-increment-not-counter left-tokens))) (unless (token-negated-p left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defmethod test-against-right-memory ((self node2-not) left-tokens) (loop for right-token in (jscl::hash-table-values (join-node-right-memory self)) do (when (test-tokens self left-tokens right-token) (token-increment-not-counter left-tokens))) (unless (token-negated-p left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) #+nil (defmethod test-against-left-memory ((self node2-not) (right-token add-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (test-tokens self left-tokens right-token) (token-increment-not-counter left-tokens) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) self))))) (defmethod test-against-left-memory ((self node2-not) (right-token add-token)) (loop for left-tokens in (jscl::hash-table-values (join-node-left-memory self)) do (when (test-tokens self left-tokens right-token) (token-increment-not-counter left-tokens) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) self))))) #+nil (defmethod test-against-left-memory ((self node2-not)(right-token remove-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (and (test-tokens self left-tokens right-token) (not (token-negated-p (token-decrement-not-counter left-tokens)))) (pass-tokens-to-successor self (combine-tokens left-tokens self))))) (defmethod test-against-left-memory ((self node2-not)(right-token remove-token)) (loop for left-tokens in (jscl::hash-table-values (join-node-left-memory self)) do (when (and (test-tokens self left-tokens right-token) (not (token-negated-p (token-decrement-not-counter left-tokens)))) (pass-tokens-to-successor self (combine-tokens left-tokens self))))) (defmethod accept-tokens-from-left ((self node2-not) (left-tokens add-token)) (add-tokens-to-left-memory self left-tokens) (test-against-right-memory self left-tokens)) (defmethod accept-tokens-from-left ((self node2-not) (left-tokens remove-token)) (when (remove-tokens-from-left-memory self left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defmethod accept-token-from-right ((self node2-not) (right-token add-token)) (add-token-to-right-memory self right-token) (test-against-left-memory self right-token)) (defmethod accept-token-from-right ((self node2-not) (right-token remove-token)) (when (remove-token-from-right-memory self right-token) (test-against-left-memory self right-token))) (defun make-node2-not () (make-instance 'node2-not)) ;;; File: node2-test.lisp (defmethod accept-tokens-from-left ((self node2-test) (left-tokens add-token)) (add-tokens-to-left-memory self left-tokens) (when (every #'(lambda (test) (funcall test left-tokens)) (join-node-tests self)) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defmethod accept-tokens-from-left ((self node2-test) (left-tokens remove-token)) (when (remove-tokens-from-left-memory self left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens self)))) (defun make-node2-test () (make-instance 'node2-test)) ;;; File: node2-exists.lisp #+nil (defmethod test-against-right-memory ((self node2-exists) (left-tokens add-token)) (loop for right-token being the hash-values of (join-node-right-memory self) do (when (test-tokens self left-tokens right-token) (token-increment-exists-counter left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) (defmethod test-against-right-memory ((self node2-exists) (left-tokens add-token)) (maphash (lambda (ignore right-token) (when (test-tokens self left-tokens right-token) (token-increment-exists-counter left-tokens) (pass-tokens-to-successor self (combine-tokens left-tokens right-token)))) (join-node-right-memory self))) #+nil (defmethod test-against-right-memory ((self node2-exists) (left-tokens remove-token)) (loop for right-token being the hash-values of (join-node-right-memory self) do (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) (defmethod test-against-right-memory ((self node2-exists) (left-tokens add-token)) (maphash (lambda (ignore right-token) (when (test-tokens self left-tokens right-token) (pass-tokens-to-successor self (combine-tokens left-tokens right-token)))) (join-node-right-memory self))) #+nil (defmethod test-against-left-memory ((self node2-exists) (right-token add-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (and (test-tokens self left-tokens right-token) (= (token-increment-exists-counter left-tokens) 1)) (pass-tokens-to-successor self (combine-tokens left-tokens right-token))))) (defmethod test-against-left-memory ((self node2-exists) (right-token add-token)) (maphash (lambda (ignore left-tokens) (when (and (test-tokens self left-tokens right-token) (= (token-increment-exists-counter left-tokens) 1)) (pass-tokens-to-successor self (combine-tokens left-tokens right-token)))) (join-node-left-memory self))) #+nil (defmethod test-against-left-memory ((self node2-exists) (right-token remove-token)) (loop for left-tokens being the hash-values of (join-node-left-memory self) do (when (test-tokens self left-tokens right-token) (token-decrement-exists-counter left-tokens) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) right-token))))) (defmethod test-against-left-memory ((self node2-exists) (right-token remove-token)) (maphash (lambda (ignore left-tokens) (when (test-tokens self left-tokens right-token) (token-decrement-exists-counter left-tokens) (pass-tokens-to-successor self (combine-tokens (make-remove-token left-tokens) right-token)))) (join-node-left-memory self))) (defmethod accept-tokens-from-left ((self node2-exists) (left-tokens add-token)) (add-tokens-to-left-memory self left-tokens) (test-against-right-memory self left-tokens)) (defmethod accept-token-from-right ((self node2-exists) (right-token add-token)) (add-token-to-right-memory self right-token) (test-against-left-memory self right-token)) (defmethod accept-tokens-from-left ((self node2-exists) (left-tokens remove-token)) (when (remove-tokens-from-left-memory self left-tokens) (test-against-right-memory self left-tokens))) (defmethod accept-token-from-right ((self node2-exists) (right-token remove-token)) (when (remove-token-from-right-memory self right-token) (test-against-left-memory self right-token))) (defun make-node2-exists () (make-instance 'node2-exists)) ;;; File: rete-compiler.lisp (defvar *root-nodes* nil) (defvar *rule-specific-nodes* nil) (defvar *leaf-nodes* nil) (defvar *logical-block-marker*) (defun set-leaf-node (node address) (setf (aref *leaf-nodes* address) node)) (defun leaf-node () (aref *leaf-nodes* (1- (length *leaf-nodes*)))) (defun left-input (address) (aref *leaf-nodes* (1- address))) (defun right-input (address) (aref *leaf-nodes* address)) (defun logical-block-marker () *logical-block-marker*) #+nil (defclass rete-network () ((root-nodes :initform (make-hash-table) :initarg :root-nodes :reader rete-roots) (node-test-cache :initform (make-hash-table :test #'equal) :initarg :node-test-cache :reader node-test-cache))) (defun record-node (node parent) (when (typep parent 'shared-node) (increment-use-count parent)) (push (make-node-pair node parent) *rule-specific-nodes*) node) (defmethod remove-node-from-parent ((self rete-network)(parent t) child) (remhash (node1-test child) (rete-roots self))) (defmethod remove-node-from-parent ((self rete-network)(parent shared-node) child) (remove-successor parent child)) (defun make-root-node (class) (let* ((test (make-class-test class)) (root (gethash test *root-nodes*))) (when (null root) (setf root (make-node1 test)) (setf (gethash test *root-nodes*) root)) (record-node root t))) #+nil (defmethod add-successor ((parent t) new-node connector) (print (list 'add-successor-t new-node)) ;;(declare (ignore connector)) new-node) ;;; bug: the method never call (defmethod add-successor (parent new-node connector) new-node) ;;; method with bug: (defmethod add-successor :around ((parent shared-node) new-node connector) (record-node (call-next-method) parent)) (defun make-intra-pattern-node (slot) (let ((test (cond ((simple-slot-p slot) (make-simple-slot-test slot)) ((constrained-slot-p slot) (make-intra-pattern-constraint-test slot)) (t (make-intra-pattern-test slot))))) (make-node1 test))) #+nil (defun distribute-token (rete-network token) (loop for root-node being the hash-values of (rete-roots rete-network) do (accept-token root-node token))) (defun distribute-token (rete-network token) (loop for root-node in (jscl::hash-table-values (rete-roots rete-network)) do (accept-token root-node token))) (defmethod make-rete-network (&rest args) (apply #'make-instance 'rete-network args)) ;;; The following functions serve as "connectors" between any two ;;; nodes. PASS-TOKEN connects two pattern (one-input) nodes, or a join node ;;; to a terminal node; ENTER-JOIN-NETWORK-FROM-LEFT connects a pattern node ;;; to a join node; ENTER-JOIN-NETWORK-FROM-RIGHT also connects a pattern node ;;; to a join node; both PASS-TOKENS-ON-LEFT and PASS-TOKEN-ON-RIGHT connect ;;; two join nodes. (defun pass-token (node token) (accept-token node token)) (defun pass-tokens-on-left (node2 tokens) (accept-tokens-from-left node2 tokens)) (defun pass-token-on-right (node2 token) (accept-token-from-right node2 token)) (defun enter-join-network-from-left (node2 tokens) (pass-tokens-on-left node2 (replicate-token tokens))) (defun enter-join-network-from-right (node2 token) (pass-token-on-right node2 (replicate-token token))) ;;; end connector functions ;;; "The alpha memory nodes and tests" (defun add-intra-pattern-nodes (patterns) (dolist (pattern patterns) (cond ((test-pattern-p pattern) (set-leaf-node t (parsed-pattern-address pattern))) (t (let ((node (make-root-node (parsed-pattern-class pattern))) (address (parsed-pattern-address pattern))) (set-leaf-node node address) (dolist (slot (parsed-pattern-slots pattern)) (when (intra-pattern-slot-p slot) (setf node (add-successor node (make-intra-pattern-node slot) #'pass-token)) (set-leaf-node node address)))))))) (defun add-join-node-tests (join-node pattern) (labels ((add-simple-join-node-test (slot) (unless (= (binding-address (pattern-slot-slot-binding slot)) (parsed-pattern-address pattern)) (join-node-add-test join-node (make-inter-pattern-test slot)))) (add-slot-constraint-test (slot) (join-node-add-test join-node (make-predicate-test (pattern-slot-constraint slot) (pattern-slot-constraint-bindings slot) (negated-slot-p slot)))) (add-test-pattern-predicate () (join-node-add-test join-node (make-predicate-test (parsed-pattern-test-forms pattern) (parsed-pattern-test-bindings pattern)))) (add-generic-pattern-tests () (dolist (slot (parsed-pattern-slots pattern)) (cond ((simple-bound-slot-p slot) (add-simple-join-node-test slot)) ((constrained-slot-p slot) (add-slot-constraint-test slot)))))) (if (test-pattern-p pattern) (add-test-pattern-predicate) (add-generic-pattern-tests)) join-node)) (defun make-join-node (pattern) (let ((join-node (cond ((negated-pattern-p pattern) (make-node2-not)) ((test-pattern-p pattern) (make-node2-test)) ((existential-pattern-p pattern) (make-node2-exists)) (t (make-node2))))) (when (eql (parsed-pattern-address pattern) (logical-block-marker)) (mark-as-logical-block join-node (logical-block-marker))) join-node)) (defun make-left-join-connection (join-node node) (if (typep node 'shared-node) (add-successor node join-node #'enter-join-network-from-left) (add-successor node join-node #'pass-tokens-on-left)) join-node) (defun make-right-join-connection (join-node node) (if (typep node 'shared-node) (add-successor node join-node #'enter-join-network-from-right) (add-successor node join-node #'pass-token-on-right)) join-node) ;;; "The beta memory nodes and tests" (defun add-inter-pattern-nodes (patterns) (dolist (pattern (rest patterns)) (let ((join-node (make-join-node pattern)) (address (parsed-pattern-address pattern))) (add-join-node-tests join-node pattern) (make-left-join-connection join-node (left-input address)) (make-right-join-connection join-node (right-input address)) (set-leaf-node join-node address)))) (defun add-terminal-node (rule) (add-successor (leaf-node) (make-terminal-node rule) #'pass-token)) ;;; addresses a problem reported by Andrew Philpot on 9/6/2007 (defun copy-node-test-table (src) (let ((target (make-hash-table :test #'equal))) (maphash (lambda (key value) (setf (gethash key target) value)) src) target)) (defun compile-rule-into-network (rete-network patterns rule) (let ((*root-nodes* (rete-roots rete-network)) (*rule-specific-nodes* (list)) (*leaf-nodes* (make-array (length patterns))) (*logical-block-marker* (rule-logical-marker rule)) (*node-test-table* (node-test-cache rete-network))) (add-intra-pattern-nodes patterns) (add-inter-pattern-nodes patterns) (add-terminal-node rule) (attach-rule-nodes rule (nreverse *rule-specific-nodes*)) (setf (slot-value rete-network 'root-nodes) *root-nodes*) rete-network)) (defun merge-rule-into-network (to-network patterns rule &key (loader nil)) (let ((from-network (compile-rule-into-network (make-rete-network :node-test-cache (copy-node-test-table (node-test-cache to-network))) patterns rule))) (when loader (funcall loader from-network)) (attach-rule-nodes rule (merge-networks from-network to-network)) to-network)) ;;; File: tms.lisp (defmethod pass-tokens-to-successor :before ((self join-node) (left-tokens remove-token)) (when (logical-block-p self) (schedule-dependency-removal (make-dependency-set left-tokens (join-node-logical-block self))))) ;;; File: network-ops.lisp #+nil (defun add-token-to-network (rete-network token-ctor) (loop for root-node being the hash-values of (rete-roots rete-network) do (accept-token root-node (funcall token-ctor)))) (defun add-token-to-network (rete-network token-ctor) (maphash (lambda (ignore root-node) (accept-token root-node (funcall token-ctor))) (rete-roots rete-network))) (defun add-fact-to-network (rete-network fact) (add-token-to-network rete-network #'(lambda () (make-add-token fact)))) (defun remove-fact-from-network (rete-network fact) (add-token-to-network rete-network #'(lambda () (make-remove-token fact)))) (defun reset-network (rete-network) (add-token-to-network rete-network #'(lambda () (make-reset-token t)))) #+nil (defmethod decrement-use-count ((node join-node)) 0) #+nil (defmethod decrement-use-count ((node terminal-node)) 0) (defun decrement-use-count (node) (typecase node (join-node 0) (terminal-node 0) (shared-node (decf (shared-node-refcnt node))) (t (error "WTF ~a node?" node)))) (defun remove-rule-from-network (rete-network rule) (labels ((remove-nodes (nodes) (if (endp nodes) rule (let ((node (node-pair-child (first nodes))) (parent (node-pair-parent (first nodes)))) (when (zerop (decrement-use-count node)) (remove-node-from-parent rete-network parent node)) (remove-nodes (rest nodes)))))) (remove-nodes (rule-node-list rule)))) #+nil (defmethod find-existing-successor ((parent shared-node) (node node1)) (gethash (node1-test node) (shared-node-successors parent))) #+nil (defmethod find-existing-successor (parent node) (declare (ignore parent node)) nil) (defun find-existing-successor (parent node) (typecase parent (shared-node (typecase node (node1 (gethash (node1-test node) (shared-node-successors parent))) (t nil)) (t nil)))) (defvar *node-set* nil) #+nil (defmethod add-node-set ((parent shared-node) node &optional (count-p nil)) (when count-p (increment-use-count parent)) (push (make-node-pair node parent) *node-set*)) #+nil (defmethod add-node-set ((parent join-node) node &optional count-p) (declare (ignore node count-p)) nil) #+nil (defmethod add-node-set (parent node &optional count-p) (declare (ignore count-p)) (push (make-node-pair node parent) *node-set*)) (defun add-node-set (parent node &optional (count-p nil)) (typecase parent (shared-node (when count-p (increment-use-count parent)) (push (make-node-pair node parent) *node-set*)) (join-node nil) (t (push (make-node-pair node parent) *node-set*)))) (defun merge-networks (from-rete to-rete) (labels ((find-root-node (network node) (gethash (node1-test node) (rete-roots network))) (collect-node-sets (parent children) (if (endp children) parent (let ((child (first children))) (add-node-set parent child) (when (typep child 'shared-node) (collect-node-sets child (shared-node-successor-nodes child))) (collect-node-sets parent (rest children))))) (add-new-root (network root) (setf (gethash (node1-test root) (rete-roots network)) root) (add-node-set t root) (collect-node-sets root (shared-node-successor-nodes root))) (merge-successors (parent successors) (if (endp successors) parent (let* ((new-successor (first successors)) (existing-successor (find-existing-successor parent (successor-node new-successor)))) (cond ((null existing-successor) (add-successor parent (successor-node new-successor) (successor-connector new-successor)) (add-node-set parent (successor-node new-successor))) (t (add-node-set parent (successor-node existing-successor) t) (merge-successors (successor-node existing-successor) (shared-node-all-successors (successor-node new-successor))))) (merge-successors parent (rest successors))))) (merge-root-node (new-root) (let ((existing-root (find-root-node to-rete new-root))) (cond ((null existing-root) (add-new-root to-rete new-root)) (t (add-node-set t existing-root) (merge-successors existing-root (shared-node-all-successors new-root))))))) (let ((*node-set* (list))) (maphash (lambda (ignore new-root) (merge-root-node new-root)) (rete-roots from-rete)) (nreverse *node-set*)))) ;;; File: network-crawler.lisp #+nil (defun show-network (rete-network &optional (strm *terminal-io*)) (labels ((get-roots () (loop for node being the hash-values of (rete-roots rete-network) collect node)) (get-successors (shared-node) (loop for s being the hash-values of (shared-node-successors shared-node) collect (successor-node s))) (get-successor (join-node) (list (successor-node (join-node-successor join-node)))) (trace-nodes (nodes &optional (level 0)) (unless (null nodes) (let* ((node (first nodes)) (string (format nil "~S" node))) ;; bug: unreleased format syntax (format strm "~V<~A~>~%" (+ level (length string)) string) (typecase node (shared-node (trace-nodes (get-successors node) (+ level 3))) (join-node (trace-nodes (get-successor node) (+ level 3))) (terminal-node nil)) (trace-nodes (rest nodes) level))))) (trace-nodes (get-roots)))) ;;; EOF
46,563
Common Lisp
.lisp
1,008
37.878968
113
0.644121
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
7fe25bc5075547be5006d046828ff4675be22ce7ed044d536492a9a2cfa023ed
40,381
[ -1 ]
40,382
01-utils.lisp
vlad-km_mLisa/01-utils.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; File: compose.lisp ;;; Description: Utilities used to compose anonymous functions. ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) #+nil (defun build-lambda-expression (forms) (labels ((compose-body (forms &optional (body nil)) (if (null forms) body (compose-body (rest forms) (nconc body `(,(first forms))))))) `(lambda () (progn ,@(compose-body forms))))) #+nil (defmacro compile-function (forms) "Build and compile an anonymous function, using the body provided in FORMS." `(compile nil (build-lambda-expression ,forms))) ;;; File: utils.lisp (in-package :lilu) ;;; This version of FIND-BEFORE courtesy of Bob Bane, Global Science and ;;; Technology... ;;;"Returns both that portion of SEQUENCE that occurs before ITEM and ;;; the rest of SEQUENCE anchored at ITEM, or NIL otherwise." (defun find-before (item sequence &key (test #'eql)) (labels ((find-item (obj seq test val valend) (let ((item (first seq))) (cond ((null seq) (values nil nil)) ((funcall test obj item) (values val seq)) (t (let ((newend `(,item))) (nconc valend newend) (find-item obj (rest seq) test val newend))))))) (if (funcall test item (car sequence)) (values nil sequence) (let ((head (list (car sequence)))) (find-item item (cdr sequence) test head head))))) ;;; "Returns that portion of SEQUENCE that occurs after ITEM, or NIL ;;; otherwise." (defun find-after (item sequence &key (test #'eql)) (cond ((null sequence) (values nil)) ((funcall test item (first sequence)) (rest sequence)) (t (find-after item (rest sequence) :test test)))) (defun find-if-after (predicate sequence) (cond ((null sequence) (values nil)) ((funcall predicate (first sequence)) (rest sequence)) (t (find-if-after predicate (rest sequence))))) (export '(lilu::find-before lilu::find-after lilu::find-if-after)) ;;; Courtesy of Paul Graham... (defun flatten (x) (labels ((rec (x acc) (cond ((null x) acc) ((atom x) (cons x acc)) (t (rec (car x) (rec (cdr x) acc)))))) (rec x nil))) (export '(lilu::flatten)) (in-package :cl-user) #+nil (defun lsthash (func ht) "Applies FUNC to each entry in hashtable HT and, if FUNC so indicates, appends the object to a LIST. If NIL is an acceptable object, then FUNC should return two values; NIL and T." (let ((seq (list))) (maphash #'(lambda (key val) (multiple-value-bind (obj use-p) (funcall func key val) (unless (and (null obj) (not use-p)) (push obj seq)))) ht) (values seq))) #+nil (defun collect (predicate list) (let ((collection (list))) (dolist (obj list) (when (funcall predicate obj) (push obj collection))) (nreverse collection))) ;;; All code below courtesy of the PORT module, CLOCC project. ;;; ;;; Conditions ;;; ;;; (:documentation "An error in the user code.") #+nil (define-condition code (error) ((proc :initform nil :reader code-proc :initarg :proc) (mesg :initform nil :reader code-mesg :initarg :mesg) (args :initform nil :reader code-args :initarg :args)) ;;(:documentation "An error in the user code.") (:report (lambda (cc out) (apply #'format out "[~s]~@[ ~?~]" (code-proc cc)(code-mesg cc)(code-args cc))))) ;;; An error in a case statement. ;;; This carries the function name which makes the error message more useful. #+nil (define-condition case-error (code) ((mesg :reader code-mesg :initform "`~s' evaluated to `~s', not one of [~@{`~s'~^ ~}]"))) ;;; "Your implementation does not support this functionality." #+nil (define-condition not-implemented (code) ((mesg :reader code-mesg :initform "not implemented for ~a [~a]") (args :type list :reader code-args :initform (list (lisp-implementation-type) (lisp-implementation-version))))) ;;; ;;; Extensions ;;; #+nil (defmacro mk-arr (type init &optional len) "Make array with elements of TYPE, initializing." (if len `(make-array ,len :element-type ,type :initial-element ,init) `(make-array (length ,init) :element-type ,type :initial-contents ,init))) (in-package :lilu) (defmacro with-gensyms (syms &body body) "Bind symbols to gensyms. First sym is a string - `gensym' prefix. Inspired by Paul Graham, <On Lisp>, p. 145." `(let (,@(mapcar (lambda (sy) `(,sy (gensym ,(car syms)))) (cdr syms))) ,@body)) (defmacro map-in (fn seq &rest seqs) "`map-into' the first sequence, evaluating it once. (map-in F S) == (map-into S F S)" (with-gensyms ("MI-" mi) `(let ((,mi ,seq)) (map-into ,mi ,fn ,mi ,@seqs)))) (export '(lilu::with-gensym lilu::map-in)) (in-package :cl-user) #+nil (defparameter +eof+ (list '+eof+) "*The end-of-file object. To be passed as the third arg to `read' and checked against using `eq'.") ;;; bug: #+nil (defun eof-p (stream) "Return T if the stream has no more data in it." (null (peek-char nil stream nil nil))) ;;; todo: bug: #+nil (defun string-tokens (string &key (start 0) max) "Read from STRING repeatedly, starting with START, up to MAX tokens. Return the list of objects read and the final index in STRING. Binds `*package*' to the keyword package, so that the bare symbols are read as keywords." ;;(declare (type (or null fixnum) max) (type fixnum start)) (let ((*package* (find-package :keyword))) (if max (do ((beg start) obj res (num 0 (1+ num))) ((= max num) (values (nreverse res) beg)) ;;(declare (fixnum beg num)) ;; bug: setf values (setf (values obj beg) (read-from-string string nil +eof+ :start beg)) (if (eq obj +eof+) (return (values (nreverse res) beg)) (push obj res))) ;; bug: concatenate (read-from-string (jscl::concat "(" string ")") t nil :start start)))) #+nil (defun required-argument () "A useful default for required arguments and DEFSTRUCT slots." (error "A required argument was not supplied.")) (in-package :lilu) (defmacro compose (&rest functions) "Macro: compose functions or macros of 1 argument into a lambda. E.g., (compose abs (dl-val zz) 'key) ==> (lambda (yy) (abs (funcall (dl-val zz) (funcall key yy))))" (labels ((rec (xx yy) (let ((rr (list (car xx) (if (cdr xx) (rec (cdr xx) yy) yy)))) (if (consp (car xx)) (cons 'funcall (if (eq (caar xx) 'quote) (cons (cadar xx) (cdr rr)) rr)) rr)))) (with-gensyms ("COMPOSE-" arg) (let ((ff (rec functions arg))) `(lambda (,arg) ,ff))))) (export '(lilu::compose)) (in-package :cl-user) ;;; EOF
7,386
Common Lisp
.lisp
189
32.518519
94
0.6036
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
97dbe6978b5f9424428eff799bf30d0f2fabdc5f1645651a43ef23b2c7517acc
40,382
[ -1 ]
40,383
03-reflect.lisp
vlad-km_mLisa/03-reflect.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; File: reflect.lisp ;;; Description: Wrapper functions that provide the MOP functionality needed ;;; by LISA, hiding implementation-specific details. ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) (in-package :reflect) (defun class-slots* (obj) (class-slots (typecase obj (symbol (find-class obj)) (standard-class obj) (standard-object (find-class (class-name (class-of obj)))) (t (class-of obj))))) (defun slot-name (slot) (slot-definition-name slot)) (defun slot-alloc (slot) (slot-definition-allocation slot)) (defun slot-one-initarg (slot) (slot-definition-initargs slot)) ;;; "Return the list of slots of a CLASS. ;;; CLASS can be a symbol, a class object (as returned by `class-of') ;;; or an instance of a class. ;;; If the second optional argument ALL is non-NIL (default), ;;; all slots are returned, otherwise only the slots with ;;; :allocation type :instance are returned." (defun class-slot-list (class &optional (all t)) ;;(unless (class-finalized-p class)(finalize-inheritance class)) (mapcan (if all (lilu:compose list slot-name) (lambda (slot) (when (eq (slot-alloc slot) :instance) (list (slot-name slot))))) (class-slots* class))) ;;; "Return the list of initargs of a CLASS. ;;;CLASS can be a symbol, a class object (as returned by `class-of') ;;;or an instance of a class. ;;;If the second optional argument ALL is non-NIL (default), ;;;initargs for all slots are returned, otherwise only the slots with ;;;:allocation type :instance are returned." (defun class-slot-initargs (class &optional (all t)) (mapcan (if all (lilu:compose list slot-one-initarg) (lambda (slot) (when (eq (slot-alloc slot) :instance) (list (slot-one-initarg slot))))) (class-slots* class))) ;;; note: (defun ensure-class* (name &key (direct-superclasses '())) (eval `(defclass ,name ,direct-superclasses ()))) (defun is-standard-classp (class) (or (eq (class-name class) 'standard-object) (eq (class-name class) t))) (defun find-direct-superclasses (class) (remove-if #'is-standard-classp (class-direct-superclasses class))) (defun class-all-superclasses (class-or-symbol) (labels ((find-superclasses (class-list superclass-list) (let ((class (first class-list))) (if (or (null class-list)(is-standard-classp class)) superclass-list (find-superclasses (find-direct-superclasses class) (find-superclasses (rest class-list) (pushnew class superclass-list))))))) (let ((class (if (symbolp class-or-symbol) (find-class class-or-symbol) class-or-symbol))) (nreverse (find-superclasses (find-direct-superclasses class) nil))))) (export '(reflect::class-slot-list reflect::class-slot-initargs reflect::find-direct-superclasses reflect::class-all-superclasses)) (in-package :cl-user) ;;; EOF
3,294
Common Lisp
.lisp
70
40.857143
131
0.664686
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
ca04fb2ed2a6ea4a55274584e588ce790a50a2e94c33a307ef6b3ec0c7230013
40,383
[ -1 ]
40,384
04-core.lisp
vlad-km_mLisa/04-core.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) (defvar *active-rule* nil) (defvar *active-engine* nil) (defvar *active-tokens* nil) (defvar *active-context* nil) (defvar *ignore-this-instance*) (defmacro with-auto-notify ((var instance) &body body) `(let* ((,var ,instance) (*ignore-this-instance* ,var)) ,@body)) (defun active-context () *active-context*) (defun active-tokens () *active-tokens*) (defun active-rule () *active-rule*) (defun active-engine () *active-engine*) (defun in-rule-firing-p () (not (null (active-rule)))) ;;;(defgeneric make-rete-network (&rest args &key &allow-other-keys)) (defgeneric (setf slot-value-of-instance) (new-value object slot-name)) (defgeneric activation-priority (self)) (defgeneric add-activation (rete activation)) ;;;(defgeneric add-activation (strategy activation)) (defgeneric adjust-belief (rete fact belief-factor)) (defgeneric assert-fact (rete fact &key belief)) (defgeneric assert-fact-aux (self fact)) (defgeneric conflict-set (self)) (defgeneric disable-activation (rete activation)) (defgeneric equals (a b)) (defgeneric find-activation (self rule token)) ;;;(defgeneric find-activation (strategy rule token)) (defgeneric find-all-activations (self rule)) ;;;(defgeneric find-all-activations (strategy rule)) (defgeneric find-rule-in-context (self rule-name)) (defgeneric fire-activation (self)) (defgeneric fire-rule (self tokens)) (defgeneric forget-rule (self rule-name)) (defgeneric get-all-activations (self)) (defgeneric get-next-activation (self)) (defgeneric hash-key (self)) (defgeneric insert-activation (self activation)) (defgeneric list-activations (self)) ;;;(defgeneric list-activations (strategy)) (defgeneric lookup-activation (self rule tokens)) (defgeneric lookup-activations (priority-queue-mixin rule)) (defgeneric mark-clos-instance-as-changed (rete instance &optional (slot-id nil))) (defgeneric modify-fact (rete fact &rest slot-changes)) (defgeneric next-activation (self)) ;;;(defgeneric next-activation (strategy)) (defgeneric remove-activations (self)) ;;;(defgeneric remove-activations (strategy)) (defgeneric remove-rule-from-context (self rule-name)) (defgeneric reset-activations (self)) (defgeneric reset-engine (rete)) (defgeneric retract (fact-object)) (defgeneric retract-fact (rete fact-id)) (defgeneric run-engine (rete &optional (step -1))) (defgeneric slot-value-of-instance (object slot-name)) (defgeneric make-add-token (fact)) (defgeneric make-remove-token (token)) (defgeneric make-reset-token (fact)) ;;; bug: (defgeneric make-rete-network (&rest args &key &allow-other-keys)) ;;;(defgeneric add-activation (self activation)) (defvar *consider-taxonomy-when-reasoning* nil) (defvar *allow-duplicate-facts* t) (defvar *use-fancy-assert* t) (defun consider-taxonomy () *consider-taxonomy-when-reasoning*) (defun (setf consider-taxonomy) (new-value) (setq *consider-taxonomy-when-reasoning* new-value)) (defun allow-duplicate-facts () *allow-duplicate-facts*) (defun (setf allow-duplicate-facts) (new-value) (setq *allow-duplicate-facts* new-value)) (defun use-fancy-assert () *use-fancy-assert*) (defun (setf use-fancy-assert) (new-value) (setq *use-fancy-assert* new-value)) (defclass inference-engine-object () ()) (defvar *clear-handlers* (list)) (defmacro register-clear-handler (tag func) `(eval-when (:load-toplevel) (unless (assoc ,tag *clear-handlers* :test #'string=) (setf *clear-handlers* (acons ,tag ,func *clear-handlers*))))) (defun clear-system-environment () (mapc #'(lambda (assoc) (funcall (cdr assoc))) *clear-handlers*) t) (defun clear-environment-handlers () (setf *clear-handlers* nil)) (defun variable-p (obj) (and (symbolp obj) (eq (aref (symbol-name obj) 0) #\?))) (defmacro starts-with-? (sym) `(eq (aref (symbol-name ,sym) 0) #\?)) (defmacro variablep (sym) `(variable-p ,sym)) (defmacro quotablep (obj) `(and (symbolp ,obj) (not (starts-with-? ,obj)))) (defmacro literalp (sym) `(or (and (symbolp ,sym) (not (variablep ,sym)) (not (null ,sym))) (numberp ,sym) (stringp ,sym))) (defmacro multifieldp (val) `(and (listp ,val) (eq (first ,val) 'quote))) (defmacro slot-valuep (val) `(or (literalp ,val) (consp ,val) (variablep ,val))) (defmacro constraintp (constraint) `(or (null ,constraint) (literalp ,constraint) (consp ,constraint))) (defun make-default-inference-engine () (when (null *active-engine*) (setf *active-engine* (make-inference-engine))) *active-engine*) #+nil (defun use-default-engine () (warn "USE-DEFAULT-ENGINE is deprecated. LISA now automatically creates a default instance of the inference engine at load time.") (when (null *active-engine*) (setf *active-engine* (make-inference-engine))) *active-engine*) ;;; "Returns the currently-active inference engine. Usually only invoked by code ;;; running within the context of WITH-INFERENCE-ENGINE." (defun current-engine (&optional (errorp t)) (when errorp (assert (not (null *active-engine*)) (*active-engine*) "The current inference engine has not been established.")) *active-engine*) (defun inference-engine (&rest args) (apply #'current-engine args)) ;;; "Evaluates BODY within the context of the inference engine ENGINE. This ;;; macro is MP-safe." (defmacro with-inference-engine ((engine) &body body) `(let ((*active-engine* ,engine)) (progn ,@body))) (register-clear-handler "environment" #'(lambda () (setf *active-engine* (make-inference-engine)) (setf *active-context* (find-context (inference-engine) :initial-context)))) ;;; File: conditions.lisp #+nil (define-condition duplicate-fact (error) ((existing-fact :reader duplicate-fact-existing-fact :initarg :existing-fact)) (:report (lambda (condition strm) (format strm "Lisa detected an attempt to assert a duplicate for: ~S" (duplicate-fact-existing-fact condition))))) #+nil (define-condition parsing-error (error) ((text :initarg :text :initform nil :reader text) (location :initarg :location :initform nil :reader location)) (:report (lambda (condition strm) (format strm "Parsing error: ~A" (text condition))))) #+nil (define-condition slot-parsing-error (parsing-error) ((slot-name :initarg :slot-name :initform nil :reader slot-name)) (:report (lambda (condition strm) (format strm "Slot parsing error: slot ~A, pattern location ~A" (slot-name condition) (location condition)) (when (text condition) (format strm " (~A)" (text condition)))))) #+nil (define-condition class-parsing-error (parsing-error) ((class-name :initarg :class-name :initform nil :reader class-name)) (:report (lambda (condition strm) (format strm "Class parsing error: ~A, ~A" (class-name condition) (text condition))))) #+nil (define-condition rule-parsing-error (parsing-error) ((rule-name :initarg :rule-name :initform nil :reader rule-name)) (:report (lambda (condition strm) (format strm "Rule parsing error: rule name ~A, pattern location ~A" (rule-name condition) (location condition)) (when (text condition) (format strm " (~A)" (text condition)))))) ;;; File: deffacts.lisp ;;; "This class represents 'autoloaded' facts that are asserted automatically ;;; as part of an inference engine reset." (defclass deffacts () ((name :initarg :name :reader deffacts-name) (fact-list :initarg :fact-list :initform nil :reader deffacts-fact-list))) #+nil (defmethod print-object ((self deffacts) strm) (print-unreadable-object (self strm :type t :identity t) (format strm "~S ; ~S" (deffacts-name self) (deffacts-fact-list self)))) (defun make-deffacts (name facts) (make-instance 'deffacts :name name :fact-list (copy-list facts))) ;;; File: fact.lisp ;;; "This class represents all facts in the knowledge base." (defclass fact () ((name :initarg :name :reader fact-name) (id :initform -1 :accessor fact-id) (slot-table :reader fact-slot-table :initform (make-hash-table :test #'equal)) (belief :initarg :belief :initform nil :accessor belief-factor) (clos-instance :reader fact-clos-instance) (shadows :initform nil :reader fact-shadowsp) (meta-data :reader fact-meta-data))) (defmethod equals ((fact-1 fact) (fact-2 fact)) (and (eq (fact-name fact-1) (fact-name fact-2)) (equalp (fact-slot-table fact-1) (fact-slot-table fact-2)))) (defmethod hash-key ((self fact)) (let ((key (list))) (maphash #'(lambda (slot value) (push value key)) (fact-slot-table self)) (push (fact-name self) key) key)) (defmethod slot-value-of-instance ((object t) slot-name) (slot-value object slot-name)) (defmethod (setf slot-value-of-instance) (new-value (object t) slot-name) (setf (slot-value object slot-name) new-value)) (defun fact-symbolic-id (fact) (format nil "F-~D" (fact-id fact))) ;;; "Assigns a new value to a slot in a fact and its associated CLOS ;;; instance. SLOT-NAME is a symbol; VALUE is the new value for the ;;; slot." (defun set-slot-value (fact slot-name value) (with-auto-notify (object (find-instance-of-fact fact)) (setf (slot-value-of-instance object slot-name) value) (initialize-slot-value fact slot-name value))) ;;; "Sets the value of a slot in a fact's slot table. FACT is a FACT instance; ;;; SLOT-NAME is a symbol; VALUE is the slot's new value." (defun initialize-slot-value (fact slot-name value) (setf (gethash slot-name (fact-slot-table fact)) value) fact) ;;; "Assigns to a slot the value from the corresponding slot in the fact's CLOS ;;; instance. FACT is a FACT instance; META-FACT is a META-FACT instance; ;;; INSTANCE is the fact's CLOS instance; SLOT-NAME is a symbol representing the ;;; affected slot." (defun set-slot-from-instance (fact instance slot-name) (initialize-slot-value fact slot-name (slot-value-of-instance instance slot-name))) ;;; "Returns a list of slot name / value pairs for every slot in a fact. FACT is ;;; a fact instance." (defun get-slot-values (fact) (let ((slots (list))) (maphash #'(lambda (slot value) (push (list slot value) slots)) (fact-slot-table fact)) slots)) ;;; "Returns the value associated with a slot name. FACT is a FACT instance; ;;; SLOT-NAME is a SLOT-NAME instance." (defgeneric get-slot-value (self slot-name)) #+nil (defmethod get-slot-value ((self fact) (slot-name (eql :object))) (fact-clos-instance self)) (defmethod get-slot-value ((self fact) (slot-name symbol)) (cond ((keywordp slot-name) (ecase slot-name (:object (fact-clos-instance self)) (:belief (belief-factor self)))) (t (gethash slot-name (fact-slot-table self))))) ;;; "Retrieves the CLOS instance associated with a fact. FACT is a FACT ;;; instance." (defun find-instance-of-fact (fact) (fact-clos-instance fact)) ;;; Corrected version courtesy of Aneil Mallavarapu... (defun has-superclass (fact symbolic-name) ; fix converts symbolic-name to a class-object (find (find-class symbolic-name) (get-superclasses (fact-meta-data fact)))) (defun synchronize-with-instance (fact &optional (effective-slot nil)) ;;; "Makes a fact's slot values and its CLOS instance's slot values match. If a ;;; slot identifier is provided then only that slot is synchronized. FACT ;;; is a FACT instance; EFFECTIVE-SLOT, if supplied, is a symbol representing ;;; the CLOS instance's slot." (let ((instance (find-instance-of-fact fact)) (meta (fact-meta-data fact))) (flet ((synchronize-all-slots () (mapc #'(lambda (slot-name) (set-slot-from-instance fact instance slot-name)) (get-slot-list meta))) (synchronize-this-slot () (set-slot-from-instance fact instance effective-slot))) (if (null effective-slot) (synchronize-all-slots) (synchronize-this-slot))) fact)) (defun reconstruct-fact (fact) `(,(fact-name fact) ,@(get-slot-values fact))) #+nil (defmethod print-object ((self fact) strm) (print-unreadable-object (self strm :type nil :identity t) (format strm "~A ; id ~D" (fact-name self) (fact-id self)))) ;;; "Initializes a FACT instance. SLOTS is a list of slot name / value pairs, ;;; where (FIRST SLOTS) is a symbol and (SECOND SLOT) is the slot's ;;; value. INSTANCE is the CLOS instance to be associated with this FACT; if ;;; INSTANCE is NIL then FACT is associated with a template and a suitable ;;; instance must be created; otherwise FACT is bound to a user-defined class." #+nil (defmethod initialize-instance :after ((self fact) &key (slots nil) (instance nil)) (with-slots ((slot-table slot-table) (meta-data meta-data)) self (setf meta-data (find-meta-fact (fact-name self))) (mapc #'(lambda (slot-name) (setf (gethash slot-name slot-table) nil)) (get-slot-list meta-data)) (if (null instance) (initialize-fact-from-template self slots meta-data) (initialize-fact-from-instance self instance meta-data)) self)) (defmethod initialize-instance :after ((self fact) &rest all-keys) (let ((slots (jscl::get-keyword-from all-keys :slots nil)) (instance (jscl::get-keyword-from all-keys :instance nil))) (with-slots ((slot-table slot-table) (meta-data meta-data)) self (setf meta-data (find-meta-fact (fact-name self))) (mapc #'(lambda (slot-name) (setf (gethash slot-name slot-table) nil)) (get-slot-list meta-data)) (if (null instance) (initialize-fact-from-template self slots meta-data) (initialize-fact-from-instance self instance meta-data)) self))) (defun initialize-fact-from-template (fact slots meta-data) ;;; "Initializes a template-bound FACT. An instance of the FACT's associated ;;; class is created and the slots of both are synchronized from the SLOTS ;;; list. FACT is a FACT instance; SLOTS is a list of symbol/value pairs." (let ((instance (make-instance (find-class (get-class-name meta-data) nil)))) (assert (not (null instance)) nil "No class was found corresponding to fact name ~S." (fact-name fact)) (setf (slot-value fact 'clos-instance) instance) (mapc #'(lambda (slot-spec) (let ((slot-name (first slot-spec)) (slot-value (second slot-spec))) (set-slot-value fact slot-name slot-value))) slots) fact)) (defun initialize-fact-from-instance (fact instance meta-data) ;;; "Initializes a fact associated with a user-created CLOS instance. The fact's ;;; slot values are taken from the CLOS instance. FACT is a FACT instance; ;;; INSTANCE is the CLOS instance associated with this fact." (mapc #'(lambda (slot-name) (set-slot-from-instance fact instance slot-name)) (get-slot-list meta-data)) (setf (slot-value fact 'clos-instance) instance) (setf (slot-value fact 'shadows) t) fact) (defun make-fact (name &rest slots) ;;; "The default constructor for class FACT. NAME is the symbolic fact name as ;;; used in rules; SLOTS is a list of symbol/value pairs." (make-instance 'fact :name name :slots slots)) (defun make-fact-from-instance (name clos-instance) ;;; "A constructor for class FACT that creates an instance bound to a ;;; user-defined CLOS instance. NAME is the symbolic fact name; CLOS-INSTANCE is ;;; a user-supplied CLOS object." (make-instance 'fact :name name :instance clos-instance)) (defun make-fact-from-template (fact) ;;; "Creates a FACT instance using another FACT instance as a ;;; template. Basically a clone operation useful for such things as asserting ;;; DEFFACTS." (apply #'make-fact (fact-name fact) (mapcar #'(lambda (slot-name) (list slot-name (get-slot-value fact slot-name))) (get-slot-list (fact-meta-data fact))))) ;;; File: watches.lisp (defvar *assert-fact* nil) (defvar *retract-fact* nil) (defvar *enable-activation* nil) (defvar *disable-activation* nil) (defvar *fire-rule* nil) (defvar *watches* nil) (defvar *trace-output* *standard-output*) (defun watch-activation-detail (activation direction) (format *trace-output* "~A Activation: ~A : ~A~%" direction (rule-default-name (activation-rule activation)) (activation-fact-list activation)) (values)) (defun watch-enable-activation (activation) (watch-activation-detail activation "==>")) (defun watch-disable-activation (activation) (watch-activation-detail activation "<==")) (defun watch-rule-firing (activation) (let ((rule (activation-rule activation))) (format *trace-output* "FIRE ~D: ~A ~A~%" (rete-firing-count (rule-engine rule)) (rule-default-name rule) (activation-fact-list activation)) (values))) (defun watch-fact-detail (fact direction) (format *trace-output* "~A ~A ~S~%" direction (fact-symbolic-id fact) (reconstruct-fact fact)) (values)) (defun watch-assert (fact) (watch-fact-detail fact "==>")) (defun watch-retract (fact) (watch-fact-detail fact "<==")) (defun watch-event (event) (ecase event (:facts (setq *assert-fact* #'watch-assert) (setq *retract-fact* #'watch-retract)) (:activations (setq *enable-activation* #'watch-enable-activation) (setq *disable-activation* #'watch-disable-activation)) (:rules (setq *fire-rule* #'watch-rule-firing)) (:all (watch-event :facts) (watch-event :activations) (watch-event :rules))) (unless (eq event :all) (pushnew event *watches*)) event) (defun unwatch-event (event) (ecase event (:facts (setf *assert-fact* nil) (setf *retract-fact* nil)) (:activations (setf *enable-activation* nil) (setf *disable-activation* nil)) (:rules (setf *fire-rule* nil)) (:all (unwatch-event :facts) (unwatch-event :activations) (unwatch-event :rules))) (unless (eq event :all) (setf *watches* ;; bug: function delete undefined !!! (delete event *watches*))) event) (defun watches () *watches*) (defmacro trace-assert (fact) `(unless (null *assert-fact*) (funcall *assert-fact* ,fact))) (defmacro trace-retract (fact) `(unless (null *retract-fact*) (funcall *retract-fact* ,fact))) (defmacro trace-enable-activation (activation) `(unless (null *enable-activation*) (funcall *enable-activation* ,activation))) (defmacro trace-disable-activation (activation) `(unless (null *disable-activation*) (funcall *disable-activation* ,activation))) (defmacro trace-firing (activation) `(unless (null *fire-rule*) (funcall *fire-rule* ,activation))) ;;; File: activation.lisp (defvar *activation-timestamp* 0) ;;; "Represents a rule activation." (defclass activation () ((rule :initarg :rule :initform nil :reader activation-rule) (tokens :initarg :tokens :initform nil :reader activation-tokens) (timestamp :initform (incf *activation-timestamp*) :reader activation-timestamp) (eligible :initform t :accessor activation-eligible))) (defmethod activation-priority ((self activation)) (rule-salience (activation-rule self))) (defmethod fire-activation ((self activation)) (trace-firing self) (fire-rule (activation-rule self) (activation-tokens self))) (defun eligible-p (activation) (activation-eligible activation)) (defun inactive-p (activation) (not (eligible-p activation))) (defun activation-fact-list (activation &key (detailp nil)) (token-make-fact-list (activation-tokens activation) :detailp detailp)) #+nil (defmethod print-object ((self activation) strm) (let ((tokens (activation-tokens self)) (rule (activation-rule self))) (print-unreadable-object (self strm :identity t :type t) (format strm "(~A ~A ; salience = ~D)" (rule-name rule) (mapcar #'fact-symbolic-id (token-make-fact-list tokens)) (rule-salience rule))))) (defmethod hash-key ((self activation)) (hash-key (activation-tokens self))) (defun make-activation (rule tokens) (make-instance 'activation :rule rule :tokens tokens)) ;;; $Header: /cvsroot/lisa/lisa/src/core/heap.lisp,v 1.4 2007/09/17 22:42:39 youngde Exp $ ;;; Copyright (c) 2002, 2003 Gene Michael Stover. ;;; Adapted for Lisa: 4/3/2006. ;;; Adapted for JSCL 2021 @vlad-km (in-package :heap) (defstruct (heap :named (:type list)) less-fn order a max-count) (defun default-search-predicate (heap obj) (declare (ignore heap) (ignore obj)) t) ;;; "Private. Move the HOLE down until it's in a location suitable for X. ;;; Return the new index of the hole." (defun percolate-down (heap hole x) (do ((a (heap-a heap)) (less (heap-less-fn heap)) (child (lesser-child heap hole) (lesser-child heap hole))) ((or (>= child (fill-pointer a)) (funcall less x (aref a child))) hole) (setf (aref a hole) (aref a child) hole child))) ;;; "Private. Moves the HOLE until it's in a location suitable for holding ;;; X. Does not actually bind X to the HOLE. Returns the new ;;; index of the HOLE. The hole itself percolates down; it's the X ;;; that percolates up." (defun percolate-up (heap hole x) (let ((d (heap-order heap)) (a (heap-a heap)) (less (heap-less-fn heap))) (setf (aref a 0) x) (do ((i hole parent) (parent (floor (/ hole d)) (floor (/ parent d)))) ((not (funcall less x (aref a parent))) i) (setf (aref a i) (aref a parent))))) (defvar *heap* nil) ;;; "Initialize the indicated heap. If INITIAL-CONTENTS is a non-empty ;;; list, the heap's contents are intiailized to the values in that ;;; list; they are ordered according to LESS-FN. INITIAL-CONTENTS must ;;; be a list or NIL." (defun heap-init (heap less-fn &key (order 2) (initial-contents nil)) (setf *heap* heap) (setf (heap-less-fn heap) less-fn (heap-order heap) order (heap-a heap) (make-array 2 :initial-element nil :adjustable t :fill-pointer 1) (heap-max-count heap) 0) (when initial-contents (dolist (i initial-contents) (vector-push-extend i (heap-a heap))) (loop for i from (floor (/ (length (heap-a heap)) order)) downto 1 do (let* ((tmp (aref (heap-a heap) i)) (hole (percolate-down heap i tmp))) (setf (aref (heap-a heap) hole) tmp))) (setf (heap-max-count heap) (length (heap-a heap)))) heap) (defun create-heap (less-fn &key (order 2) (initial-contents nil)) (heap-init (make-heap) less-fn :order order :initial-contents initial-contents)) ;;; "Remove all elements from the heap, leaving it empty. Faster ;;;(& more convenient) than calling HEAP-REMOVE until the heap is ;;;empty." (defun heap-clear (heap) (setf (fill-pointer (heap-a heap)) 1) nil) (defun heap-count (heap) (1- (fill-pointer (heap-a heap)))) ;;; "Returns non-NIL if & only if the heap contains no items." (defun heap-empty-p (heap) (= (fill-pointer (heap-a heap)) 1)) ;;; "Insert a new element into the heap. Return the element (which probably ;;; isn't very useful)." (defun heap-insert (heap x) (let ((a (heap-a heap))) ;; Append a hole for the new element. (vector-push-extend nil a) ;; Move the hole from the end towards the front of the ;; queue until it is in the right position for the new ;; element. (setf (aref a (percolate-up heap (1- (fill-pointer a)) x)) x))) ;;; "Return the index of the element which satisfies the predicate FNP. ;;; If there is no such element, return the fill pointer of HEAP's array A." (defun heap-find-idx (heap fnp) (do* ((a (heap-a heap)) (fp (fill-pointer a)) (i 1 (1+ i))) ((or (>= i fp) (funcall fnp heap (aref a i))) i))) ;;; "Remove the minimum (first) element in the heap & return it. It's ;;; an error if the heap is already empty. (Should that be an error?)" (defun heap-remove (heap &optional (fn #'default-search-predicate)) (let ((a (heap-a heap)) (i (heap-find-idx heap fn))) (cond ((< i (fill-pointer a)) ;; We found an element to remove. (let ((x (aref a i)) (last-object (vector-pop a))) (setf (aref a (percolate-down heap i last-object)) last-object) x)) (t nil)))) ;; Nothing to remove (defun heap-find (heap &optional (fn #'default-search-predicate)) (let ((a (heap-a heap)) (i (heap-find-idx heap fn))) (cond ((< i (fill-pointer a)) ; We found an element to remove. (aref a i)) (t nil)))) #+nil (defun heap-collect (heap &optional (fn #'default-search-predicate)) (if (heap-empty-p heap) nil (loop for obj across (heap-a heap) when (funcall fn heap obj) collect obj))) (defun heap-collect (heap &optional (fn #'default-search-predicate)) (let ((vec (heap-a heap))) (if (heap-empty-p heap) nil (loop for i from 1 below (fill-pointer vec) with obj = (aref vec i) when (funcall fn heap obj) collect obj)))) ;;; "Return the first element in the heap, but don't remove it. It'll ;;; be an error if the heap is empty. (Should that be an error?)" (defun heap-peek (heap) (aref (heap-a heap) 1)) ;;; "Return the index of the lesser child. If there's one child, ;;; return its index. If there are no children, return ;;; (FILL-POINTER (HEAP-A HEAP))." (defun lesser-child (heap parent) (let* ((a (heap-a heap)) (left (* parent (heap-order heap))) (right (1+ left)) (fp (fill-pointer a))) (cond ((>= left fp) fp) ((= right fp) left) ((funcall (heap-less-fn heap) (aref a left) (aref a right)) left) (t right)))) (export '(heap::create-heap heap::heap-clear heap::heap-collect heap::heap-count heap::heap-empty-p heap::heap-find heap::heap-insert heap::heap-peek heap::heap-remove)) (in-package :cl-user) ;;; File: strategies.lisp ;;; Description: Classes that implement the various default conflict ;;; resolution strategies for Lisa's RETE implementation. ;;; "Serves as the base class for all classes implementing conflict ;;; resolution strategies." (defclass strategy () ()) (defclass priority-queue-mixin () ((heap :initarg :heap :reader heap))) (defclass indexed-priority-list () ((priority-vector :reader get-priority-vector) (inodes :initform '() :accessor get-inodes) (delta :accessor get-delta) (insertion-function :initarg :insertion-function :reader get-insertion-function))) ;;; (:documentation ;;; "Utility class that implements an indexed priority 'queue' to manage ;;; activations. Employed by various types of conflict resolution strategies, ;;; particularly DEPTH-FIRST-STRATEGY and BREADTH-FIRST-STRATEGY.")) (defmethod initialize-instance :after ((self indexed-priority-list) &key (priorities 500)) (setf (slot-value self 'priority-vector) (make-array (1+ priorities) :initial-element nil)) (setf (slot-value self 'delta) (/ priorities 2))) (defmethod reset-activations ((self priority-queue-mixin)) (heap:heap-clear (heap self))) (defmethod insert-activation ((self priority-queue-mixin) activation) (heap:heap-insert (heap self) activation)) (defmethod lookup-activation ((self priority-queue-mixin) rule tokens) (heap:heap-find (heap self) #'(lambda (heap activation) (and (equal (hash-key activation) (hash-key tokens)) (eq (activation-rule activation) rule))))) (defmethod lookup-activations ((self priority-queue-mixin) rule) (heap:heap-collect (heap self) #'(lambda (heap activation) (and activation (eq rule (activation-rule activation)))))) (defmethod get-next-activation ((self priority-queue-mixin)) (heap:heap-remove (heap self))) (defmethod get-all-activations ((self priority-queue-mixin)) (heap:heap-collect (heap self) (lambda (heap activation) activation))) ;;; "A base class for all LISA builtin conflict resolution strategies." (defclass builtin-strategy (strategy priority-queue-mixin) ()) (defmethod add-activation ((self builtin-strategy) activation) (insert-activation self activation)) ;;; bug: (defmethod find-activation ((self builtin-strategy) rule token) (assert nil nil "Why are we calling FIND-ACTIVATION?")) (defmethod find-all-activations ((self builtin-strategy) rule) (lookup-activations self rule)) (defmethod next-activation ((self builtin-strategy)) (get-next-activation self)) (defmethod remove-activations ((self builtin-strategy)) (reset-activations self)) (defmethod list-activations ((self builtin-strategy)) (get-all-activations self)) ;;; "A depth-first conflict resolution strategy." (defclass depth-first-strategy (builtin-strategy) ()) (defun make-depth-first-strategy () (make-instance 'depth-first-strategy :heap (heap:create-heap #'(lambda (a b) (cond ((> (activation-priority a) (activation-priority b)) a) ((and (= (activation-priority a) (activation-priority b)) (> (activation-timestamp a) (activation-timestamp b))) a) (t nil)))))) ;;; "A breadth-first conflict resolution strategy." (defclass breadth-first-strategy (builtin-strategy) ()) (defun make-breadth-first-strategy () (make-instance 'breadth-first-strategy :heap (heap:create-heap #'(lambda (a b) (cond ((> (activation-priority a) (activation-priority b)) a) ((and (= (activation-priority a) (activation-priority b)) (< (activation-timestamp a) (activation-timestamp b))) a) (t nil)))))) ;;; File: context.lisp (defclass context () ((name :initarg :name :reader context-name) (rules :initform (make-hash-table :test #'equal) :reader context-rules) (strategy :initarg :strategy :reader context-strategy))) #+nil (defmethod print-object ((self context) strm) (print-unreadable-object (self strm :type t) (if (initial-context-p self) (format strm "~S" "The Initial Context") (format strm "~A" (context-name self))))) (defmethod find-rule-in-context ((self context) (rule-name string)) (values (gethash rule-name (context-rules self)))) (defmethod find-rule-in-context ((self context) (rule-name symbol)) (values (gethash (symbol-name rule-name) (context-rules self)))) (defun add-rule-to-context (context rule) (setf (gethash (symbol-name (rule-name rule)) (context-rules context)) rule)) (defmethod conflict-set ((self context)) (context-strategy self)) (defmethod remove-rule-from-context ((self context) (rule-name symbol)) (remhash (symbol-name rule-name) (context-rules self))) (defmethod remove-rule-from-context ((self context) (rule t)) (remove-rule-from-context self (rule-name rule))) (defun clear-activations (context) (remove-activations (context-strategy context))) (defun context-activation-list (context) (list-activations (context-strategy context))) #+nil (defun context-rule-list (context) (loop for rule being the hash-values of (context-rules context) collect rule)) (defun context-rule-list (context) (let ((collection)) (maphash (lambda (nothing rule) (push rule collection)) (context-rules context)) (reverse collection))) (defun clear-context (context) (clear-activations context) (clrhash (context-rules context))) (defun initial-context-p (context) (string= (context-name context) "INITIAL-CONTEXT")) (defun make-context-name (defined-name) (typecase defined-name (symbol (symbol-name defined-name)) (string defined-name) (otherwise (error "The context name must be a string designator.")))) (defmacro with-context (context &body body) `(let ((*active-context* ,context)) ,@body)) (defmacro with-rule-name-parts ((context short-name long-name) symbolic-name &body body) (let ((qualifier (gensym)) (rule-name (gensym))) `(let* ((,rule-name (symbol-name ,symbolic-name)) (,qualifier (position #\. ,rule-name)) (,context (if ,qualifier (subseq ,rule-name 0 ,qualifier) (symbol-name :initial-context))) (,short-name (if ,qualifier (subseq ,rule-name (1+ ,qualifier)) ,rule-name)) (,long-name (if ,qualifier ,rule-name (jscl::concat ,context "." ,short-name)))) ,@body))) (defun make-context (name &key (strategy nil)) (make-instance 'context :name (make-context-name name) :strategy (if (null strategy) (make-breadth-first-strategy) strategy))) ;;; File: rule.lisp ;;; "Represents production rules after they've been analysed by the language ;;; parser." (defclass rule () ((short-name :initarg :short-name :initform nil :reader rule-short-name) (qualified-name :reader rule-name) (comment :initform nil :initarg :comment :reader rule-comment) (salience :initform 0 :initarg :salience :reader rule-salience) (context :initarg :context :reader rule-context) (auto-focus :initform nil :initarg :auto-focus :reader rule-auto-focus) (behavior :initform nil :initarg :behavior :accessor rule-behavior) (binding-set :initarg :binding-set :initform nil :reader rule-binding-set) (node-list :initform nil :reader rule-node-list) (activations :initform (make-hash-table :test #'equal) :accessor rule-activations) (patterns :initform (list) :initarg :patterns :reader rule-patterns) (actions :initform nil :initarg :actions :reader rule-actions) (logical-marker :initform nil :initarg :logical-marker :reader rule-logical-marker) (belief-factor :initarg :belief :initform nil :reader belief-factor) (active-dependencies :initform (make-hash-table :test #'equal) :reader rule-active-dependencies) (engine :initarg :engine :initform nil :reader rule-engine))) (defmethod fire-rule ((self rule) tokens) (let ((*active-rule* self) (*active-engine* (rule-engine self)) (*active-tokens* tokens)) (unbind-rule-activation self tokens) (funcall (rule-behavior self) tokens))) (defun rule-default-name (rule) (if (initial-context-p (rule-context rule)) (rule-short-name rule) (rule-name rule))) (defun bind-rule-activation (rule activation tokens) (setf (gethash (hash-key tokens) (rule-activations rule)) activation)) (defun unbind-rule-activation (rule tokens) (remhash (hash-key tokens) (rule-activations rule))) (defun clear-activation-bindings (rule) (clrhash (rule-activations rule))) (defun find-activation-binding (rule tokens) (gethash (hash-key tokens) (rule-activations rule))) (defun attach-rule-nodes (rule nodes) (setf (slot-value rule 'node-list) nodes)) (defun compile-rule-behavior (rule actions) (with-accessors ((behavior rule-behavior)) rule (unless behavior (setf (rule-behavior rule) (make-behavior (rule-actions-actions actions) (rule-actions-bindings actions)))))) (defmethod conflict-set ((self rule)) (conflict-set (rule-context self))) #+nil (defmethod print-object ((self rule) strm) (print-unreadable-object (self strm :type t) (format strm "~A" (if (initial-context-p (rule-context self)) (rule-short-name self) (rule-name self))))) (defun compile-rule (rule patterns actions) (compile-rule-behavior rule actions) (add-rule-to-network (rule-engine rule) rule patterns) rule) (defun logical-rule-p (rule) (numberp (rule-logical-marker rule))) (defun auto-focus-p (rule) (rule-auto-focus rule)) (defun find-any-logical-boundaries (patterns) (flet ((ensure-logical-blocks-are-valid (addresses) (assert (and (= (first (last addresses)) 1) (eq (parsed-pattern-class (first patterns)) 'initial-fact)) nil "Logical patterns must appear first within a rule.") ;; BUG FIX - FEB 17, 2004 - Aneil Mallavarapu ;; - replaced: ;; (reduce #'(lambda (first second) ;; arguments need to be inverted because address values are PUSHed ;; onto the list ADDRESSES, and therefore are in reverse order (reduce #'(lambda (second first) (assert (= second (1+ first)) nil "All logical patterns within a rule must be contiguous.") second) addresses :from-end t))) (let ((addresses (list))) (dolist (pattern patterns) (when (logical-pattern-p pattern) (push (parsed-pattern-address pattern) addresses))) (unless (null addresses) (ensure-logical-blocks-are-valid addresses)) (first addresses)))) (defmethod initialize-instance :after ((self rule) &rest initargs) (with-slots ((qual-name qualified-name)) self (setf qual-name (intern (format nil "~A.~A" (context-name (rule-context self)) (rule-short-name self)))))) (defun make-rule (name engine patterns actions &key (doc-string nil) (salience 0) (context (active-context)) (auto-focus nil) (belief nil) (compiled-behavior nil)) (flet ((make-rule-binding-set () (remove-duplicates (loop for pattern in patterns append (parsed-pattern-binding-set pattern))))) (compile-rule (make-instance 'rule :short-name name :engine engine :patterns patterns :actions actions :behavior compiled-behavior :comment doc-string :belief belief :salience salience :context (if (null context) (find-context (inference-engine) :initial-context) (find-context (inference-engine) context)) :auto-focus auto-focus :logical-marker (find-any-logical-boundaries patterns) :binding-set (make-rule-binding-set)) patterns actions))) (defun copy-rule (rule engine) (let ((initargs `(:doc-string ,(rule-comment rule) :salience ,(rule-salience rule) :context ,(if (initial-context-p (rule-context rule)) nil (context-name (rule-context rule))) :compiled-behavior ,(rule-behavior rule) :auto-focus ,(rule-auto-focus rule)))) (with-inference-engine (engine) (apply #'make-rule (rule-short-name rule) engine (rule-patterns rule) (rule-actions rule) initargs)))) ;;; File: pattern.lisp ;;; Description: Structures here collectively represent patterns after they've ;;; been analysed by the language parser. This is the canonical representation ;;; of parsed patterns that Rete compilers are intended to see. ;;; Represents the canonical form of a slot within a pattern analysed by the ;;; DEFRULE parser. NAME is the slot identifier; VALUE is the slot's value, ;;; and its type can be one of (symbol number string list) or a LISA variable; ;;; SLOT-BINDING is the binding object, present if VALUE is a LISA variable; ;;; NEGATED is non-NIL if the slot occurs within a NOT form; ;;; INTRA-PATTERN-BINDINGS is a list of binding objects, present if all of the ;;; variables used by the slot reference bindings within the slot's pattern; ;;; CONSTRAINT, if not NIL, represents a constraint placed on the slot's ;;; value. CONSTRAINT should only be non-NIL if VALUE is a variable, and can ;;; be one of the types listed for VALUE or a CONS representing arbitrary ;;; Lisp code; CONSTRAINT-BINDINGS is a list of binding objects that are ;;; present if the slot has a constraint. ;;; "Represents the canonical form of a slot within a pattern analysed by the ;;; DEFRULE parser." (defstruct pattern-slot (name nil :type symbol) (value nil) (slot-binding nil :type list) (negated nil :type symbol) (intra-pattern-bindings nil :type symbol) (constraint nil) (constraint-bindings nil :type list)) ;;; PARSED-PATTERN represents the canonical form of a pattern analysed by the ;;; language parser. CLASS is the name, or head, of the pattern, as a symbol; ;;; SLOTS is a list of PATTERN-SLOT objects representing the analysed slots of ;;; the pattern; ADDRESS is a small integer representing the pattern's ;;; position within the rule form, starting at 0; PATTERN-BINDING, if not NIL, ;;; is the variable to which a fact matching the pattern will be bound during ;;; the match process; TEST-BINDINGS is a list of BINDING objects present if ;;; the pattern is a TEST CE; BINDING-SET is the set of variable bindings used ;;; by the pattern; TYPE is one of (:GENERIC :NEGATED :TEST :OR) and indicates ;;; the kind of pattern represented; SUB-PATTERNS, if non-NIL, is set for an ;;; OR CE and is a list of PARSED-PATTERN objects that represent the branches ;;; within the OR; LOGICAL, if non-NIL, indicates this pattern participates in ;;; truth maintenance. ;;; "Represents the canonical form of a pattern analysed by the DEFRULE parser." ;;; todo: as defclass (defstruct parsed-pattern (class nil :type symbol) (slots nil) (address 0 :type integer) (pattern-binding nil) (test-bindings nil :type list) (binding-set nil :type list) (logical nil :type symbol) (sub-patterns nil :type list) (type :generic :type symbol)) ;;; todo: as defclass (defstruct rule-actions (bindings nil :type list) (actions nil :type list)) (defun generic-pattern-p (pattern) (eq (parsed-pattern-type pattern) :generic)) (defun existential-pattern-p (pattern) (eq (parsed-pattern-type pattern) :existential)) (defun test-pattern-p (pattern) (eq (parsed-pattern-type pattern) :test)) (defun test-pattern-predicate (pattern) (parsed-pattern-slots pattern)) (defun negated-pattern-p (pattern) (eq (parsed-pattern-type pattern) :negated)) (defun parsed-pattern-test-forms (pattern) (assert (test-pattern-p pattern) nil "This pattern is not a test pattern: ~S" pattern) (parsed-pattern-slots pattern)) (defun simple-slot-p (pattern-slot) (not (variablep (pattern-slot-value pattern-slot)))) (defun intra-pattern-slot-p (pattern-slot) (or (simple-slot-p pattern-slot) (pattern-slot-intra-pattern-bindings pattern-slot))) (defun constrained-slot-p (pattern-slot) (not (null (pattern-slot-constraint pattern-slot)))) (defun simple-bound-slot-p (pattern-slot) (and (variablep (pattern-slot-value pattern-slot)) (not (constrained-slot-p pattern-slot)))) (defun negated-slot-p (pattern-slot) (pattern-slot-negated pattern-slot)) (defun bound-pattern-p (parsed-pattern) (not (null (parsed-pattern-pattern-binding parsed-pattern)))) (defun compound-pattern-p (parsed-pattern) (not (null (parsed-pattern-sub-patterns parsed-pattern)))) (defun logical-pattern-p (parsed-pattern) (parsed-pattern-logical parsed-pattern)) ;;; File: rule-parser.lisp ;;; Description: The Lisa rule parser, completely rewritten for release 3.0. (defconstant *rule-separator* '=>) (defvar *binding-table*) (defvar *current-defrule*) (defvar *current-defrule-pattern-location*) (defvar *in-logical-pattern-p* nil) (defvar *special-initial-elements* '(not exists logical)) (defvar *conditional-elements-table* '((exists . parse-exists-pattern) (not . parse-not-pattern) (test . parse-test-pattern) (or . parse-or-pattern))) (defun extract-rule-headers (body) (if (stringp (first body)) (values (first body) (rest body)) (values nil body))) ;;; "Supports the parsing of embedded DEFRULE forms." (defun fixup-runtime-bindings (patterns) (labels ((fixup-bindings (part result) (let* ((token (first part)) (new-token token)) (cond ((null part) (return-from fixup-bindings (nreverse result))) ((and (variablep token) (boundp token)) (setf new-token (symbol-value token))) ((consp token) (setf new-token (fixup-bindings token nil)))) (fixup-bindings (rest part) (push new-token result))))) (fixup-bindings patterns nil))) (defun preprocess-left-side (lhs) (when (or (null lhs) (find (caar lhs) *special-initial-elements*)) (push (list 'initial-fact) lhs)) (if (active-rule) (fixup-runtime-bindings lhs) lhs)) (defun find-conditional-element-parser (symbol) (let ((parser (assoc symbol *conditional-elements-table*))) (if parser (cdr parser) 'parse-generic-pattern))) (defun logical-element-p (pattern) (eq (first pattern) 'logical)) (defmacro with-slot-components ((slot-name slot-value constraint) form &body body) `(progn (unless (consp ,form) (error 'slot-parsing-error :slot-name ',slot-name :location *current-defrule-pattern-location*)) (let ((,slot-name (first ,form)) (,slot-value (second ,form)) (,constraint (third ,form))) ,@body))) #+nil (defun make-binding-set () (loop for binding being the hash-values of *binding-table* collect binding)) (defun make-binding-set () (reverse (jscl::hash-table-values *binding-table*))) ;;; "Given a variable, either retrieve the binding object for it or create a new one." (defun find-or-set-slot-binding (var slot-name location) (multiple-value-bind (binding existsp) (gethash var *binding-table*) (unless existsp (setf binding (setf (gethash var *binding-table*) (make-binding var location slot-name)))) (values binding existsp))) ;;; "Given a variable, retrieve the binding object for it." (defun find-slot-binding (var &key (errorp t)) (let ((binding (gethash var *binding-table*))) (when errorp (assert binding nil "Missing slot binding for variable ~A" var)) binding)) (defun set-pattern-binding (var location) (assert (not (gethash var *binding-table*)) nil "This is a duplicate pattern binding: ~A" var) (setf (gethash var *binding-table*) (make-binding var location :pattern))) (defun collect-bindings (forms &key (errorp t)) (let ((bindings (list))) (dolist (obj (lilu:flatten forms)) (when (variablep obj) (let ((binding (find-slot-binding obj :errorp errorp))) (unless (null binding) (push binding bindings))))) (nreverse bindings))) (defmacro with-rule-components (((doc-string lhs rhs) rule-form) &body body) (let ((remains (gensym))) `(let ((*binding-table* (make-hash-table))) (multiple-value-bind (,doc-string ,remains) (extract-rule-headers ,rule-form) (multiple-value-bind (,lhs ,rhs) (parse-rule-body ,remains) ,@body))))) (defun collect-constraint-bindings (constraint) (let ((bindings (list))) (dolist (obj (lilu:flatten constraint)) (when (variablep obj) (pushnew (find-slot-binding obj) bindings :key #'first))) bindings)) ;;; the parsing code itself... ;;; "Parses a single slot constraint, eg. (slot-name ?var 1) or (slot-name ?var (equal ?var 1))" (defun parse-one-slot-constraint (var constraint-form) (let ((head (first constraint-form)) (args (second constraint-form))) (cond ((eq head 'not) (values `(equal ,var ,@(if (symbolp args) `(',args) args)) `(,(find-slot-binding var)) t)) (t (values constraint-form (collect-constraint-bindings constraint-form) nil))))) ;;; "Is the slot value a Lisa variable?" (defun slot-value-is-variable-p (value) (variable-p value)) ;;; "Is the slot value a simple constraint?" (defun slot-value-is-atom-p (value) (and (atom value) (not (slot-value-is-variable-p value)))) ;;; "Is the slot value a simple negated constraint?" (defun slot-value-is-negated-atom-p (value) (and (consp value) (eq (first value) 'not) (slot-value-is-atom-p (second value)))) (defun slot-value-is-negated-variable-p (value) (and (consp value) (eq (first value) 'not) (variable-p (second value)))) ;;; "Is every variable in a pattern 'local'; i.e. does not reference a binding in a previous pattern?" (defun intra-pattern-bindings-p (bindings location) (every #'(lambda (b) (= location (binding-address b))) bindings)) ;;; "Parses a single raw pattern slot" (defun parse-one-slot (form location) (with-slot-components (slot-name slot-value constraint) form (cond ((slot-value-is-atom-p slot-value) ;; eg. (slot-name "frodo") (make-pattern-slot :name slot-name :value slot-value)) ((slot-value-is-negated-variable-p slot-value) ;; eg. (slot-name (not ?value)) (let ((binding (find-or-set-slot-binding (second slot-value) slot-name location))) (make-pattern-slot :name slot-name :value (second slot-value) :negated t :slot-binding binding))) ((slot-value-is-negated-atom-p slot-value) ;; eg. (slot-name (not "frodo")) (make-pattern-slot :name slot-name :value (second slot-value) :negated t)) ((and (slot-value-is-variable-p slot-value) (not constraint)) ;; eg. (slot-name ?value) (let ((binding (find-or-set-slot-binding slot-value slot-name location))) (make-pattern-slot :name slot-name :value slot-value :slot-binding binding :intra-pattern-bindings (intra-pattern-bindings-p (list binding) location)))) ((and (slot-value-is-variable-p slot-value) constraint) ;; eg. (slot-name ?value (equal ?value "frodo")) (let ((binding (find-or-set-slot-binding slot-value slot-name location))) (multiple-value-bind (constraint-form constraint-bindings negatedp) (parse-one-slot-constraint slot-value constraint) (make-pattern-slot :name slot-name :value slot-value :slot-binding binding :negated negatedp :constraint constraint-form :constraint-bindings constraint-bindings :intra-pattern-bindings (intra-pattern-bindings-p (list* binding constraint-bindings) location))))) (t (error 'rule-parsing-error :rule-name *current-defrule* :location *current-defrule-pattern-location* :text "malformed slot"))))) (defun parse-rule-body (body) (let ((location 0) (patterns (list))) (labels ((parse-lhs (pattern-list) (let ((pattern (first pattern-list)) (*current-defrule-pattern-location* location)) (unless (listp pattern) (error 'rule-parsing-error :text "pattern is not a list" :rule-name *current-defrule* :location *current-defrule-pattern-location*)) (cond ((null pattern-list) (unless *in-logical-pattern-p* (nreverse patterns))) ;; logical CEs are "special"; they don't have their own parser. ((logical-element-p pattern) (let ((*in-logical-pattern-p* t)) (parse-lhs (rest pattern)))) (t (push (funcall (find-conditional-element-parser (first pattern)) pattern (1- (incf location))) patterns) (parse-lhs (rest pattern-list)))))) (parse-rhs (actions) (make-rule-actions :bindings (collect-bindings actions :errorp nil) :actions actions))) (multiple-value-bind (lhs remains) (lilu:find-before *rule-separator* body :test #'eq) (unless remains (error 'rule-parsing-error :text "missing rule separator")) (values (parse-lhs (preprocess-left-side lhs)) (parse-rhs (lilu:find-after *rule-separator* remains :test #'eq))))))) ;;; The conditional element parsers... (defun parse-generic-pattern (pattern location &optional pattern-binding) (let ((head (first pattern))) (unless (symbolp head) (error 'rule-parsing-error :rule-name *current-defrule* :location *current-defrule-pattern-location* :text "the head of a pattern must be a symbol")) (cond ((variable-p head) (set-pattern-binding head location) (parse-generic-pattern (second pattern) location head)) (t (let ((slots (loop for slot-decl in (rest pattern) collect (parse-one-slot slot-decl location)))) (make-parsed-pattern :type :generic :pattern-binding pattern-binding :slots slots :binding-set (make-binding-set) :logical *in-logical-pattern-p* :address location :class head)))))) (defun parse-test-pattern (pattern location) (flet ((extract-test-pattern () (let ((form (rest pattern))) (unless (and (listp form) (= (length form) 1)) (error 'rule-parsing-error :rule-name *current-defrule* :location *current-defrule-pattern-location* :text "TEST takes a single Lisp form as argument")) form))) (let* ((form (extract-test-pattern)) (bindings (collect-bindings form))) (make-parsed-pattern :test-bindings bindings :type :test :slots form :pattern-binding nil :binding-set (make-binding-set) :logical *in-logical-pattern-p* :address location)))) (defun parse-exists-pattern (pattern location) (let ((pattern (parse-generic-pattern (second pattern) location))) (setf (parsed-pattern-type pattern) :existential) pattern)) (defun parse-not-pattern (pattern location) (let ((pattern (parse-generic-pattern (second pattern) location))) (setf (parsed-pattern-type pattern) :negated) pattern)) (defun parse-or-pattern (pattern location) (let ((sub-patterns (mapcar #'(lambda (pat) (parse-generic-pattern pat location)) (cdr pattern)))) (make-parsed-pattern :sub-patterns sub-patterns :type :or))) ;;; High-level rule definition interfaces... (defun define-rule (name body &key (salience 0) (context nil) (auto-focus nil) (belief nil)) (let ((*current-defrule* name)) (with-rule-components ((doc-string lhs rhs) body) (make-rule name (inference-engine) lhs rhs :doc-string doc-string :salience salience :context context :belief belief :auto-focus auto-focus)))) (defun redefine-defrule (name body &key (salience 0) (context nil) (belief nil) (auto-focus nil)) (define-rule name body :salience salience :context context :belief belief :auto-focus auto-focus)) ;;; File: fact-parser.lisp (defun create-template-class-slots (class-name slot-list) (labels ((determine-default (default-form) (unless (and (consp default-form) (eq (first default-form) 'default) (= (length default-form) 2)) (error 'class-parsing-error :class-name class-name :text "malformed DEFAULT keyword")) (second default-form)) (build-one-slot (template) (destructuring-bind (keyword slot-name &optional default) template (unless (eq keyword 'slot) (error 'class-parsing-error :class-name class-name :text "unrecognized keyword: ~A" keyword)) `(,slot-name :initarg ,(intern (symbol-name slot-name) 'keyword) :initform ,(if (null default) nil (determine-default default)) :reader ,(intern (format nil "~S-~S" class-name slot-name)))))) (mapcar #'build-one-slot slot-list))) (defun redefine-deftemplate (class-name body) (let ((class (gensym))) `(let ((,class (defclass ,class-name (inference-engine-object) ,@(list (create-template-class-slots class-name body))))) ,class))) (defun bind-logical-dependencies (fact) (add-logical-dependency (inference-engine) fact (make-dependency-set (active-tokens) (rule-logical-marker (active-rule)))) fact) (defun parse-and-insert-instance (instance &key (belief nil)) (ensure-meta-data-exists (class-name (class-of instance))) (let ((fact (make-fact-from-instance (class-name (class-of instance)) instance))) (when (and (in-rule-firing-p) (logical-rule-p (active-rule))) (bind-logical-dependencies fact)) (assert-fact (inference-engine) fact :belief belief))) (defun parse-and-retract-instance (instance engine) (retract-fact engine instance)) (defun show-deffacts (deffact) (format t "~S~%" deffact) (values deffact)) (defun parse-and-insert-deffacts (name body) (let ((deffacts (gensym))) `(let ((,deffacts (list))) (dolist (fact ',body) (let ((head (first fact))) (ensure-meta-data-exists head) (push (apply #'make-fact head (rest fact)) ,deffacts))) (add-autofact (inference-engine) (make-deffacts ',name (nreverse ,deffacts)))))) ;;; File: language.lisp ;;; Description: Code that implements the Lisa programming language. (defmacro defrule (name (&key (salience 0) (context nil) (belief nil) (auto-focus nil)) &body body) (let ((rule-name (gensym))) `(let ((,rule-name ,@(if (consp name) `(,name) `(',name)))) (redefine-defrule ,rule-name ',body :salience ,salience :context ,context :belief ,belief :auto-focus ,auto-focus)))) (defun undefrule (rule-name) (with-rule-name-parts (context short-name long-name) rule-name (forget-rule (inference-engine) long-name))) (defmacro deftemplate (name (&key) &body body) (redefine-deftemplate name body)) (defmacro defcontext (context-name &optional (strategy nil)) `(unless (find-context (inference-engine) ,context-name nil) (register-new-context (inference-engine) (make-context ,context-name :strategy ,strategy)))) (defmacro undefcontext (context-name) `(forget-context (inference-engine) ,context-name)) (defun focus-stack () (rete-focus-stack (inference-engine))) (defun focus (&rest args) (if (null args) (current-context (inference-engine)) (dolist (context-name (reverse args) (focus-stack)) (push-context (inference-engine) (find-context (inference-engine) context-name))))) (defun refocus () (pop-context (inference-engine))) (defun contexts () (let ((contexts (retrieve-contexts (inference-engine)))) (dolist (context contexts) (format t "~S~%" context)) (format t "For a total of ~D context~:P.~%" (length contexts)) (values))) (defun dependencies () (maphash #'(lambda (dependent-fact dependencies) (format *trace-output* "~S:~%" dependent-fact) (format *trace-output* " ~S~%" dependencies)) (rete-dependency-table (inference-engine))) (values)) (defun expand-slots (body) (mapcar #'(lambda (pair) (destructuring-bind (name value) pair `(list (identity ',name) (identity ,@(if (quotablep value) `(',value) `(,value)))))) body)) (defmacro assert> ((name &body body) &key (belief nil)) (let ((fact (gensym)) (fact-object (gensym))) `(let ((,fact-object ,@(if (or (consp name) (variablep name)) `(,name) `(',name)))) (if (typep ,fact-object 'standard-object) (parse-and-insert-instance ,fact-object :belief ,belief) (progn (ensure-meta-data-exists ',name) (let ((,fact (make-fact ',name ,@(expand-slots body)))) (when (and (in-rule-firing-p) (logical-rule-p (active-rule))) (bind-logical-dependencies ,fact)) (assert-fact (inference-engine) ,fact :belief ,belief))))))) (defmacro deffacts (name (&key &allow-other-keys) &body body) (parse-and-insert-deffacts name body)) (defun engine () (active-engine)) (defun rule () (active-rule)) (defun assert-instance (instance) (parse-and-insert-instance instance)) (defun retract-instance (instance) (parse-and-retract-instance instance (inference-engine))) (defun facts () (let ((facts (get-fact-list (inference-engine)))) (dolist (fact facts) (format t "~S~%" fact)) (format t "For a total of ~D fact~:P.~%" (length facts)) (values))) (defun rules (&optional (context-name nil)) (let ((rules (get-rule-list (inference-engine) context-name))) (dolist (rule rules) (format t "~S~%" rule)) (format t "For a total of ~D rule.~%" (length rules)) (values))) (defun agenda (&optional (context-name nil)) (let ((activations (get-activation-list (inference-engine) context-name))) (dolist (activation activations) (format t "~S~%" activation)) (format t "For a total of ~D activation~:P.~%" (length activations)) (values))) (defun reset () (reset-engine (inference-engine))) (defun clear () (clear-system-environment)) (defun run (&optional (contexts nil)) (unless (null contexts) (apply #'focus contexts)) (run-engine (inference-engine))) (defun walk (&optional (step 1)) (run-engine (inference-engine) step)) (defmethod retract ((fact-object fact)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object number)) (retract-fact (inference-engine) fact-object)) (defmethod retract ((fact-object t)) (parse-and-retract-instance fact-object (inference-engine))) (defmacro modify (fact &body body) `(modify-fact (inference-engine) ,fact ,@(expand-slots body))) (defun watch (event) (watch-event event)) (defun unwatch (event) (unwatch-event event)) (defun watching () (let ((watches (watches))) (format *trace-output* "Watching ~A~%" (if watches watches "nothing")) (values))) (defun halt () (halt-engine (inference-engine))) (defun mark-instance-as-changed (instance &key (slot-id nil)) (mark-clos-instance-as-changed (inference-engine) instance slot-id)) ;;; File: tms-support.lisp ;;; Description: Support functions for LISA's Truth Maintenance System (TMS). (defvar *scheduled-dependencies*) (define-symbol-macro scheduled-dependencies *scheduled-dependencies*) (defun add-logical-dependency (rete fact dependency-set) (setf (gethash dependency-set (rete-dependency-table rete)) (push fact (gethash dependency-set (rete-dependency-table rete))))) (defun find-logical-dependencies (rete dependency-set) (gethash dependency-set (rete-dependency-table rete))) (defun make-dependency-set (tokens marker) (let ((dependencies (list))) (loop for i from 1 to marker do (push (token-find-fact tokens i) dependencies)) (nreverse dependencies))) (defun schedule-dependency-removal (dependency-set) (push dependency-set scheduled-dependencies)) (defmacro with-truth-maintenance ((rete) &body body) (let ((rval (gensym))) `(let* ((*scheduled-dependencies* (list)) (,rval (progn ,@body))) (dolist (dependency scheduled-dependencies) (with-accessors ((table rete-dependency-table)) ,rete (dolist (dependent-fact (gethash dependency table) (remhash dependency table)) (retract-fact ,rete dependent-fact)))) ,rval))) ;;; File: rete.lisp ;;; Description: Class representing the inference engine itself. ;;;(error "EQUALP") (defclass rete () ((fact-table :initform (make-hash-table :test #'equal) :accessor rete-fact-table) (fact-id-table :initform (make-hash-table :test #'equal) :accessor fact-id-table) (instance-table :initform (make-hash-table) :reader rete-instance-table) (rete-network :initform (make-rete-network) :reader rete-network) (next-fact-id :initform -1 :accessor rete-next-fact-id) (autofacts :initform (list) :accessor rete-autofacts) (meta-data :initform (make-hash-table) :reader rete-meta-data) (dependency-table :initform (make-hash-table :test #'equal) :accessor rete-dependency-table) (contexts :initform (make-hash-table :test #'equal) :reader rete-contexts) (focus-stack :initform (list) :accessor rete-focus-stack) (halted :initform nil :accessor rete-halted) (firing-count :initform 0 :accessor rete-firing-count))) (defmethod initialize-instance :after ((self rete) &rest initargs) ;;(declare (ignore initargs)) (register-new-context self (make-context :initial-context)) (reset-focus-stack self) self) ;;; FACT-META-OBJECT represents data about facts. Every Lisa fact is backed by ;;; a CLOS instance that was either defined by the application or internally ;;; by Lisa (via DEFTEMPLATE). (defstruct fact-meta-object (class-name nil :type symbol) (slot-list nil :type list) (superclasses nil :type list)) (defun register-meta-object (rete key meta-object) (setf (gethash key (rete-meta-data rete)) meta-object)) (defun find-meta-object (rete symbolic-name) (gethash symbolic-name (rete-meta-data rete))) (defun rete-fact-count (rete) (hash-table-count (rete-fact-table rete))) (defun find-rule (rete rule-name) (with-rule-name-parts (context-name short-name long-name) rule-name (find-rule-in-context (find-context rete context-name) long-name))) (defun add-rule-to-network (rete rule patterns) (flet ((load-facts (network) (maphash #'(lambda (key fact) ;;(declare (ignore key)) (add-fact-to-network network fact)) (rete-fact-table rete)))) (when (find-rule rete (rule-name rule)) (forget-rule rete rule)) (if (zerop (rete-fact-count rete)) (compile-rule-into-network (rete-network rete) patterns rule) (merge-rule-into-network (rete-network rete) patterns rule :loader #'load-facts)) (add-rule-to-context (rule-context rule) rule) rule)) (defmethod forget-rule ((self rete) (rule-name symbol)) (flet ((disable-activations (rule) (mapc #'(lambda (activation) (setf (activation-eligible activation) nil)) (find-all-activations (context-strategy (rule-context rule)) rule)))) (let ((rule (find-rule self rule-name))) (assert (not (null rule)) nil "The rule named ~S is not known to be defined." rule-name) (remove-rule-from-network (rete-network self) rule) (remove-rule-from-context (rule-context rule) rule) (disable-activations rule) rule))) (defmethod forget-rule ((self rete) (rule rule)) (forget-rule self (rule-name rule))) (defmethod forget-rule ((self rete) (rule-name string)) (forget-rule self (find-symbol rule-name))) #+nil (defun remember-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (setf (gethash (hash-key fact) fact-table) fact) (setf (gethash (fact-id fact) id-table) fact))) ;;; make (1) from 1 for hash-table (defgeneric hash-id (instance)) (defmethod hash-id ((instance fact)) (list (fact-id instance))) #+nil (defun remember-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (setf (gethash (hash-key fact) fact-table) fact) (setf (gethash (string (fact-id fact)) id-table) fact))) (defun remember-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (setf (gethash (hash-key fact) fact-table) fact) (setf (gethash (hash-id fact) id-table) fact))) #+nil (defun forget-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (remhash (hash-key fact) fact-table) (remhash (fact-id fact) id-table))) #+nil (defun forget-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (remhash (hash-key fact) fact-table) (remhash (string (fact-id fact)) id-table))) (defun forget-fact (rete fact) (with-accessors ((fact-table rete-fact-table) (id-table fact-id-table)) rete (remhash (hash-key fact) fact-table) (remhash (hash-id fact) id-table))) #+nil (defun find-fact-by-id (rete fact-id) (gethash fact-id (fact-id-table rete))) ;;; bug: string (defun find-fact-by-id (rete fact-id) (gethash (string fact-id) (fact-id-table rete))) (defun find-fact-by-name (rete fact-name) (gethash fact-name (rete-fact-table rete))) (defun forget-all-facts (rete) (clrhash (rete-fact-table rete)) (clrhash (fact-id-table rete))) #+nil (defun get-fact-list (rete) (delete-duplicates (sort (loop for fact being the hash-values of (rete-fact-table rete) collect fact) #'(lambda (f1 f2) (< (fact-id f1) (fact-id f2)))))) ;;; note: very bottleneck (defun get-fact-list (rete) (remove-duplicates (sort (jscl::hash-table-values (rete-fact-table rete)) #'(lambda (f1 f2) (< (fact-id f1) (fact-id f2)))))) (defun duplicate-fact-p (rete fact) (let ((f (gethash (hash-key fact) (rete-fact-table rete)))) (if (and f (equals f fact)) f nil))) (defmacro ensure-fact-is-unique (rete fact) (let ((existing-fact (gensym))) `(unless *allow-duplicate-facts* (let ((,existing-fact (gethash (hash-key ,fact) (rete-fact-table ,rete)))) (unless (or (null ,existing-fact) (not (equals ,fact ,existing-fact))) (error (make-condition 'duplicate-fact :existing-fact ,existing-fact))))))) (defmacro with-unique-fact ((rete fact) &body body) (let ((body-fn (gensym)) (existing-fact (gensym))) `(flet ((,body-fn () ,@body)) (if *allow-duplicate-facts* (,body-fn) (let ((,existing-fact (duplicate-fact-p ,rete ,fact))) (if (not ,existing-fact) (,body-fn) (error (make-condition 'duplicate-fact :existing-fact ,existing-fact)))))))) (defun next-fact-id (rete) (incf (rete-next-fact-id rete))) (defun add-autofact (rete deffact) (pushnew deffact (rete-autofacts rete) :key #'deffacts-name)) (defun remove-autofacts (rete) (setf (rete-autofacts rete) nil)) (defun assert-autofacts (rete) (mapc #'(lambda (deffact) (mapc #'(lambda (fact) (assert-fact rete (make-fact-from-template fact))) (deffacts-fact-list deffact))) (rete-autofacts rete))) (defmethod assert-fact-aux ((self rete) fact) (with-truth-maintenance (self) (setf (fact-id fact) (next-fact-id self)) (remember-fact self fact) (trace-assert fact) (add-fact-to-network (rete-network self) fact) (when (fact-shadowsp fact) (register-clos-instance self (find-instance-of-fact fact) fact))) fact) (defmethod adjust-belief (rete fact (belief-factor number)) (with-unique-fact (rete fact) (setf (belief-factor fact) belief-factor))) (defmethod adjust-belief (rete fact (belief-factor t)) (when (in-rule-firing-p) (let ((rule-belief (belief-factor (active-rule))) (facts (token-make-fact-list *active-tokens*))) (setf (belief-factor fact) (belief:adjust-belief facts rule-belief (belief-factor fact)))))) (defmethod assert-fact ((self rete) fact &key belief) (let ((duplicate (duplicate-fact-p self fact))) (cond (duplicate (adjust-belief self duplicate belief)) (t (adjust-belief self fact belief) (assert-fact-aux self fact))) (if duplicate duplicate fact))) (defmethod retract-fact ((self rete) (fact fact)) (with-truth-maintenance (self) (forget-fact self fact) (trace-retract fact) (remove-fact-from-network (rete-network self) fact) (when (fact-shadowsp fact) (forget-clos-instance self (find-instance-of-fact fact))) fact)) (defmethod retract-fact ((self rete) (instance standard-object)) (let ((fact (find-fact-using-instance self instance))) (assert (not (null fact)) nil "This CLOS instance is unknown to LISA: ~S" instance) (retract-fact self fact))) (defmethod retract-fact ((self rete) (fact-id integer)) (let ((fact (find-fact-by-id self fact-id))) (and (not (null fact)) (retract-fact self fact)))) (defmethod modify-fact ((self rete) fact &rest slot-changes) (retract-fact self fact) (mapc #'(lambda (slot) (set-slot-value fact (first slot) (second slot))) slot-changes) (assert-fact self fact) fact) #+nil (defun clear-contexts (rete) (loop for context being the hash-values of (rete-contexts rete) do (clear-activations context))) (defun clear-contexts (rete) (maphash (lambda (nothing context) (clear-activations context)) (rete-contexts rete))) (defun clear-focus-stack (rete) (setf (rete-focus-stack rete) (list))) (defun initial-context (rete) (find-context rete :initial-context)) (defun reset-focus-stack (rete) (setf (rete-focus-stack rete) (list (initial-context rete)))) (defun set-initial-state (rete) (forget-all-facts rete) (clear-contexts rete) (reset-focus-stack rete) (setf (rete-next-fact-id rete) -1) (setf (rete-firing-count rete) 0) t) (defmethod reset-engine ((self rete)) (reset-network (rete-network self)) (set-initial-state self) (assert> (initial-fact)) (assert-autofacts self) t) #+nil (defun get-rule-list (rete &optional (context-name nil)) (if (null context-name) (loop for context being the hash-values of (rete-contexts rete) append (context-rule-list context)) (context-rule-list (find-context rete context-name)))) (defun get-rule-list (rete &optional (context-name nil)) (if (null context-name) (loop for context in (jscl::hash-table-values (rete-contexts rete)) append (context-rule-list context)) (context-rule-list (find-context rete context-name)))) #+nil (defun get-activation-list (rete &optional (context-name nil)) (if (not context-name) (loop for context being the hash-values of (rete-contexts rete) for activations = (context-activation-list context) when activations nconc activations) (context-activation-list (find-context rete context-name)))) (defun get-activation-list (rete &optional (context-name nil)) (if (not context-name) (loop for context in (jscl::hash-table-values (rete-contexts rete)) for activations = (context-activation-list context) when activations nconc activations) (context-activation-list (find-context rete context-name)))) (defun find-fact-using-instance (rete instance) (gethash instance (rete-instance-table rete))) (defun register-clos-instance (rete instance fact) (setf (gethash instance (rete-instance-table rete)) fact)) (defun forget-clos-instance (rete instance) (remhash instance (rete-instance-table rete))) (defun forget-clos-instances (rete) (clrhash (rete-instance-table rete))) (defmethod mark-clos-instance-as-changed ((self rete) instance &optional (slot-id nil)) (let ((fact (find-fact-using-instance self instance)) (network (rete-network self))) (cond ((null fact) (warn "This instance is not known to Lisa: ~S." instance)) (t (remove-fact-from-network network fact) (synchronize-with-instance fact slot-id) (add-fact-to-network network fact))) instance)) (defun find-context (rete defined-name &optional (errorp t)) (let ((context (gethash (make-context-name defined-name) (rete-contexts rete)))) (if (and (null context) errorp) (error "There's no context named: ~A" defined-name) context))) (defun register-new-context (rete context) (setf (gethash (context-name context) (rete-contexts rete)) context)) (defun forget-context (rete context-name) (let ((context (find-context rete context-name))) (dolist (rule (context-rule-list context)) (forget-rule rete rule)) (remhash context-name (rete-contexts rete)) context)) (defun current-context (rete) (first (rete-focus-stack rete))) (defun next-context (rete) (with-accessors ((focus-stack rete-focus-stack)) rete (pop focus-stack) (setf *active-context* (first focus-stack)))) (defun starting-context (rete) (first (rete-focus-stack rete))) (defun push-context (rete context) (push context (rete-focus-stack rete)) (setf *active-context* context)) (defun pop-context (rete) (next-context rete)) #+nil (defun retrieve-contexts (rete) (loop for context being the hash-values of (rete-contexts rete) collect context)) (defun retrieve-contexts (rete) (loop for context in (jscl::hash-table-values (rete-contexts rete)) collect context)) (defmethod add-activation ((self rete) activation) (let ((rule (activation-rule activation))) (trace-enable-activation activation) (add-activation (conflict-set rule) activation) (when (auto-focus-p rule) (push-context self (rule-context rule))))) (defmethod disable-activation ((self rete) activation) (when (eligible-p activation) (trace-disable-activation activation) (setf (activation-eligible activation) nil)) activation) (defmethod run-engine ((self rete) &optional (step -1)) (with-context (starting-context self) (setf (rete-halted self) nil) (do ((count 0)) ((or (= count step) (rete-halted self)) count) (let ((activation (next-activation (conflict-set (active-context))))) (cond ((null activation) (next-context self) (when (null (active-context)) (reset-focus-stack self) (halt-engine self))) ((eligible-p activation) (incf (rete-firing-count self)) (fire-activation activation) (incf count))))))) (defun halt-engine (rete) (setf (rete-halted rete) t)) (defun make-rete () (make-instance 'rete)) (defun make-inference-engine () (make-rete)) (defun copy-network (engine) (let ((new-engine (make-inference-engine))) (mapc #'(lambda (rule) (copy-rule rule new-engine)) (get-rule-list engine)) new-engine)) #+nil (defun make-query-engine (source-rete) (let* ((query-engine (make-inference-engine))) (loop for fact being the hash-values of (rete-fact-table source-rete) do (remember-fact query-engine fact)) query-engine)) (defun make-query-engine (source-rete) (let* ((query-engine (make-inference-engine))) (maphash (lambda (ignore fact) (remember-fact query-engine fact)) (rete-fact-table source-rete)) query-engine)) ;;; File: belief-interface.lisp (defmethod belief:belief-factor ((self fact)) (belief-factor self)) (defmethod belief:belief-factor ((self rule)) (belief-factor self)) ;;; File: meta.lisp ;;; Description: Meta operations that LISA uses to support the manipulation of ;;; facts and instances. (defun get-class-name (meta-object) (fact-meta-object-class-name meta-object)) (defun get-slot-list (meta-object) (fact-meta-object-slot-list meta-object)) (defun get-superclasses (meta-object) (fact-meta-object-superclasses meta-object)) ;;; "Locates the META-FACT instance associated with SYMBOLIC-NAME. If ERRORP is ;;; non-nil, signals an error if no binding is found." (defun find-meta-fact (symbolic-name &optional (errorp t)) (let ((meta-fact (find-meta-object (inference-engine) symbolic-name))) (when errorp (assert (not (null meta-fact)) nil "This fact name does not have a registered meta class: ~S" symbolic-name)) meta-fact)) ;;; Corrected version courtesy of Aneil Mallavarapu... (defun acquire-meta-data (actual-name) (labels ((build-meta-object (class all-superclasses) ; NEW LINE (AM 9/19/03) (let* ((class-name (class-name class)) (meta-data (make-fact-meta-object :class-name class-name :slot-list (reflect:class-slot-list class) :superclasses all-superclasses))) ; new line (AM 9/19/03) (register-meta-object (inference-engine) class-name meta-data) meta-data)) (examine-class (class-object) (let ((superclasses (if *consider-taxonomy-when-reasoning* (reflect:class-all-superclasses class-object) ; NEW LINE (AM 9/19/03) nil))) (build-meta-object class-object superclasses) (dolist (super superclasses) (examine-class super))))) (examine-class (find-class actual-name)))) ;;; Corrected version courtesy of Aneil Mallavarapu... (defun import-class-specification (class-name) (labels ((import-class-object (class-object) ; defined this internal function (let ((class-symbols (list class-name))) (dolist (slot-name (reflect:class-slot-list class-object)) (push slot-name class-symbols)) (import class-symbols) (when *consider-taxonomy-when-reasoning* (dolist (ancestor (reflect:find-direct-superclasses class-object)) (import-class-object ancestor))) ; changed to import-class-object class-object))) (import-class-object (find-class class-name)))) (defun ensure-meta-data-exists (class-name) (flet ((ensure-class-definition () (loop (when (find-class class-name nil) (acquire-meta-data class-name) (return)) (error "LISA doesn't know about the template named by (~S)." class-name) ))) (let ((meta-data (find-meta-object (inference-engine) class-name))) (when (null meta-data) (ensure-class-definition) (setf meta-data (find-meta-object (inference-engine) class-name))) meta-data))) ;;; File: binding.lisp (defstruct (binding (:type list) (:constructor %make-binding)) variable address slot-name) (defun make-binding (var address slot-name) (%make-binding :variable var :address address :slot-name slot-name)) (defun pattern-binding-p (binding) (eq (binding-slot-name binding) :pattern)) ;;; File: token.lisp (defclass token () ((facts :initform (make-array 0 :adjustable t :fill-pointer 0) :accessor token-facts) (not-counter :initform 0 :accessor token-not-counter) (exists-counter :initform 0 :accessor token-exists-counter) (hash-code :initform (list) :accessor token-hash-code) (contents :initform nil :reader token-contents))) (defclass add-token (token) ()) (defclass remove-token (token) ()) (defclass reset-token (token) ()) (defun token-increment-exists-counter (token) (incf (token-exists-counter token))) (defun token-decrement-exists-counter (token) (assert (plusp (token-exists-counter token)) nil "The EXISTS join node logic is busted.") (decf (token-exists-counter token))) (defun token-increment-not-counter (token) (values token (incf (token-not-counter token)))) (defun token-decrement-not-counter (token) (assert (plusp (token-not-counter token)) nil "The negated join node logic is busted.") (values token (decf (token-not-counter token)))) (defun token-negated-p (token) (plusp (token-not-counter token))) (defun token-make-fact-list (token &key (detailp t) (debugp nil)) (let* ((facts (list)) (vector (token-facts token)) (length (length vector))) (dotimes (i length) (let ((fact (aref vector i))) (if debugp (push fact facts) (when (typep fact 'fact) (push (if detailp fact (fact-symbolic-id fact)) facts))))) (nreverse facts))) (defun token-fact-count (token) (length (token-facts token))) (defun token-find-fact (token address) (aref (slot-value token 'facts) address)) (defun token-top-fact (token) (with-slots ((fact-vector facts)) token (aref fact-vector (1- (length fact-vector))))) (defun token-push-fact (token fact) (with-accessors ((fact-vector token-facts) (hash-code token-hash-code)) token (vector-push-extend fact fact-vector) (push fact hash-code) token)) ;;; bug: bug: bug: (pop hash-code) ;;; see (defmethod hash-key ((self token)) ;;; below (defun token-pop-fact (token) (with-accessors ((fact-vector token-facts) (hash-code token-hash-code)) token (unless (zerop (fill-pointer fact-vector)) (pop hash-code) (aref fact-vector (decf (fill-pointer fact-vector)))))) (defun replicate-token (token &key (token-class nil)) (let ((new-token (make-instance (if token-class (find-class token-class) (class-of token))))) (with-slots ((existing-fact-vector facts)) token (let ((length (length existing-fact-vector))) (dotimes (i length) (token-push-fact new-token (aref existing-fact-vector i))))) new-token)) #+nil (defmethod hash-key ((self token)) (token-hash-code self)) ;;; bug: bug: bug: ;;; self => add-token ;;; (token-hash-code self) => (list fact) (defmethod hash-key ((self token)) (let* ((key (list)) (facts (token-hash-code self)) (fact (car facts))) (maphash #'(lambda (slot value) (push value key)) (fact-slot-table fact)) (push (fact-name fact) key) key)) (defmethod make-add-token ((fact fact)) (token-push-fact (make-instance 'add-token) fact)) (defmethod make-remove-token ((fact fact)) (token-push-fact (make-instance 'remove-token) fact)) (defmethod make-remove-token ((token token)) (replicate-token token :token-class 'remove-token)) (defmethod make-reset-token ((fact t)) (token-push-fact (make-instance 'reset-token) t)) ;;; File: retrieve.lisp ;;; "Holds the results of query firings.") (defvar *query-result* nil) ;;; LISA (ASSERT) => (ASSERT>) ;;; "Runs a query (RULE instance), and returns both the value of *QUERY-RESULT* ;;; and the query name itself." (defun run-query (query-rule) (let ((*query-result* (list))) (assert> (query-fact)) (run) *query-result*)) ;;; "Defines a new query identified by the symbol NAME." (defmacro defquery (name &body body) `(define-rule ,name ',body)) ;;; Queries fired by RETRIEVE collect their results in the special variable ;;; *QUERY-RESULT*. As an example, one firing of this query, ;;; ;;; (retrieve (?x ?y) ;;; (?x (rocky (name ?name))) ;;; (?y (hobbit (name ?name)))) ;;; ;;; will produce a result similar to, ;;; ;;; (((?X . #<ROCKY @ #x7147b70a>) (?Y . #<HOBBIT @ #x7147b722>))) (defmacro retrieve ((&rest varlist) &body body) (flet ((make-query-binding (var) `(cons ',var ,var))) (let ((query-name (gensym)) (query (gensym))) `(with-inference-engine ((make-query-engine (inference-engine))) (let* ((,query-name (gensym)) (,query (defquery ',query-name (query-fact) ,@body => (push (list ,@(mapcar #'(lambda (var) var) varlist)) *query-result*)))) (run-query ,query)))))) ;;; "For each variable/instance pair in a query result, invoke BODY with VAR ;;; bound to the query variable and VALUE bound to the instance." (defmacro with-simple-query ((var value) query &body body) (let ((result (gensym))) `(let ((,result ,query)) (dolist (match ,result) (dolist (binding match) (let ((,var (car binding)) (,value (cdr binding))) ,@body)))))) ;;; EOF
92,309
Common Lisp
.lisp
2,159
35.471051
109
0.638039
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
90c466bf0ca11409253788d4cab80be611643910746a052c52d9ffce89111680
40,384
[ -1 ]
40,385
06-config.lisp
vlad-km_mLisa/06-config.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; File: config.lisp ;;; Description: User-customisable configuration settings for LISA. It is ;;; expected that developers will edit this file as they see fit. ;;; The reference guide has complete details, but: ;;; * Setting USE-FANCY-ASSERT enables the #? dispatch macro character. ;;; * Setting ALLOW-DUPLICATE-FACTS disables duplicate fact checking during ;;; assertions. ;;; * Setting CONSIDER-TAXONOMY instructs LISA to consider a CLOS instance's ;;; ancestors during pattern matching. ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) (eval-when (:load-toplevel) (setf (use-fancy-assert) t) (setf (allow-duplicate-facts) t) (setf (consider-taxonomy) t)) ;;; File: epilogue.lisp (deftemplate initial-fact ()) (deftemplate query-fact ()) ;;; This macro is courtesy of Paul Werkowski. A very nice idea. #+nil (defmacro define-lisa-lisp () (flet ((externals-of (pkg) (loop for s being each external-symbol in pkg collect s))) (let* ((lisa-externs (externals-of "LISA")) (lisa-shadows (intersection (package-shadowing-symbols "LISA") lisa-externs)) (cl-externs (externals-of "COMMON-LISP"))) `(defpackage "LISA-LISP" (:use "COMMON-LISP") (:shadowing-import-from "LISA" ,@lisa-shadows) (:import-from "LISA" ,@(set-difference lisa-externs lisa-shadows)) (:export ,@cl-externs) (:export ,@lisa-externs))))) #+nil (eval-when (:load-toplevel :execute) (make-default-inference-engine) (setf *active-context* (initial-context (inference-engine))) (define-lisa-lisp) (when (use-fancy-assert) (set-dispatch-macro-character #\# #\? #'(lambda (strm subchar arg) (declare (ignore subchar arg)) (list 'identity (read strm t nil t))))) (pushnew :lisa *features*)) (eval-when (:compile-top-level :load-toplevel :execute) (make-default-inference-engine) (setf *active-context* (initial-context (inference-engine))) (pushnew :lisa *features*)) ;;; EOF
2,287
Common Lisp
.lisp
53
38.320755
76
0.675506
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
289992ba85f16512813235d096d05d68982a4e58f22ae874fd1d2c8c8a578905
40,385
[ -1 ]
40,386
02-belief.lisp
vlad-km_mLisa/02-belief.lisp
;;; -*- mode:lisp; coding:utf-8 -*- ;;; This file is part of LISA, the Lisp-based Intelligent Software ;;; Agents platform. ;;; Copyright (C) 2000 David E. Young ([email protected]) ;;; Modification for JSCL under Electron platform ;;; Copyright (C) 2021 Vladimir K. Mezentsev (@vlad-km) ;;; File: belief.lisp ;;; Description: Common interfaces to Lisa's belief-system interface. (in-package :belief) ;;; The principal interface by which outside code hooks objects that support some kind of belief-factor ;;; interface into this library. (defgeneric belief-factor (obj)) (defgeneric adjust-belief (objects rule-belief &optional old-belief)) (defgeneric belief->english (belief-factor)) ;;; File: null-belief-system.lisp ;;; interface into the generic belief system. (defmethod belief-factor ((obj t)) nil) (defmethod adjust-belief ((objects t) (rule-belief t) &optional (old-belief nil)) nil) (defmethod belief->english ((belief t)) nil) (defconstant +true+ 1.0) (defconstant +false+ -1.0) (defconstant +unknown+ 0.0) (defun certainty-factor-p (number) (<= +false+ number +true+)) (deftype certainty-factor () `(and (real) (satisfies certainty-factor-p))) (defun true-p (cf) (check-type cf certainty-factor) (> cf +unknown+)) (defun false-p (cf) (check-type cf certainty-factor) (< cf +unknown+)) (defun unknown-p (cf) (check-type cf certainty-factor) (= cf +unknown+)) (defun cf-combine (a b) (check-type a certainty-factor) (check-type b certainty-factor) (cond ((and (plusp a) (plusp b)) (+ a b (* -1 a b))) ((and (minusp a) (minusp b)) (+ a b (* a b))) (t (/ (+ a b) (- 1 (min (abs a) (abs b))))))) ;;; "Combines the certainty factors of objects matched within a single rule." (defun conjunct-cf (objects) (let ((conjuncts (loop for obj in objects for cf = (belief-factor obj) if cf collect cf))) (if conjuncts (apply #'min conjuncts) nil))) (defgeneric recalculate-cf (objects rule-cf old-cf)) (defmethod recalculate-cf (objects (rule-cf number) (old-cf number)) (let* ((combined-cf (conjunct-cf objects)) (new-cf (if combined-cf (* rule-cf combined-cf) rule-cf))) (cf-combine old-cf new-cf))) (defmethod recalculate-cf (objects (rule-cf number) (old-cf t)) (let* ((combined-cf (conjunct-cf objects)) (new-cf (if combined-cf combined-cf rule-cf)) (factor (if combined-cf rule-cf 1.0))) (* new-cf factor))) (defmethod recalculate-cf (objects (rule-cf t) (old-cf t)) (let* ((combined-cf (conjunct-cf objects))) (if combined-cf (* combined-cf 1.0) nil))) (defun cf->english (cf) (cond ((= cf 1.0) "certain evidence") ((> cf 0.8) "strongly suggestive evidence") ((> cf 0.5) "suggestive evidence") ((> cf 0.0) "weakly suggestive evidence") ((= cf 0.0) "no evidence either way") ((< cf 0.0) (jscl::concat (cf->english (- cf)) " against the conclusion")))) (defmethod adjust-belief (objects (rule-belief number) &optional (old-belief nil)) (recalculate-cf objects rule-belief old-belief)) (defmethod adjust-belief (objects (rule-belief t) &optional old-belief) ;;;(declare (ignore objects old-belief)) nil) (defmethod belief->english ((cf number)) (cf->english cf)) (export '(belief::ADJUST-BELIEF belief::BELIEF->ENGLISH belief::BELIEF-FACTOR belief::FALSE-P belief::TRUE-P belief::UKNOWN-P)) (in-package :cl-user) ;;; EOF
3,559
Common Lisp
.lisp
92
34.076087
103
0.655804
vlad-km/mLisa
0
0
4
GPL-3.0
9/19/2024, 11:48:23 AM (Europe/Amsterdam)
f40317b1802fd9a1cc0e9e0b946d4edf251468bd57fc819acfcea63db7ba9004
40,386
[ -1 ]
40,409
tutorial.lisp
L0ren2_lisp_tut/tutorial.lisp
; Du kommst einfach nicht dahinter, wie LISP funktioniert aber du interessierst dich aus irgendeinem Grund dafür? ; Hier gibts einige kleine Goodies, die dich in die Lage versetzen, lisp besser zu lernen. Unten gibt es ein paar gute Lernquellen. ; Die restliche Datei ist einfach dazu da, Anfängern ein bisschen unter die Arme zu greifen. ; Viel Spaß. ;;; Falls nicht schon bekannt, LISP steht für "List processing language" weil die häufigste Datenstruktur die Liste ist. (list 1 2 3) ;(1 2 3) ; Zahlen evaluieren zu sich selbst. 4 ;4 ; Brüche werden gekürzt aber nicht als Dezimalbruch dargestellt. (/ 4 6); Präfixnotation, keine Infixnotation (also (/ 2 3) statt (2 / 3)) ;2/3 2 / 3 ; bei Brüchen klappt auch Infix ;2/3 ;;; Processing von listen: von links nach rechts, das 0-te Element wird aber als letztes evaluiert (+ 1 2 3) ; Erst evaluiert die 1 zu sich selbst, dann die 2, dann die 3 und dann wird die + funktion mit 1,2 und 3 als Argumente aufgerufen. ;6 #| Dies ist ein mehrzeiliger Kommentar. #| Mehrzeiliger Kommentar kann genestet werden, KP wofür das gut sein soll, aber there you go. |# ; Kombination mit einzeiligen Kommentaren ist möglich. |# ;;; Es gibt viele verschiedene Wege, Variablen anzulegen. Wir erstellen eine dummy Funktion, damit die Variablen nicht das globale scope zumüllen: (defun dummy-vars () (defconstant my-const 42) ; Erstellt eine Konstante; Konstanten können nicht geändert werden. (defvar my-var 69) ; Bindet die Variable my-var an den Wert 69. (defparameter my-var2 420) ; Bindet den "Parameter" an den Wert 420. (setq my-var3 3.14) ; Bindet die Variable my-var3 an den Wert 3.14. (setf my-var4 42) ; Bindet ... whatever you get it (let ((a 1337)) ; let ist interessant: es erstellt ein Scope, in dem a gültig ist. (+ a 1) ; Hier kommt 1338 raus. ) ; Ab hier ist a nicht mehr zugrifbar. (let ((a 1) (b 2)) ; Mit let lassen sich Variablen auch weniger anstrengend erstellen: es sind mehrere möglich. (+ a b) ) (let* ((a 1) (b 2) (c (+ a b))) ; Mit let* (Ja die haben das echt so genannt :p) ist es möglich, in der Zuweisungsliste die definierten Variablen (+ a b c) ; zum definieren anderer Variablen zu nutzen. MIT let GEHT DAS NICHT. ) ; hier wird 6 evaluiert ; außerdem machen die Klammern das ganze recht schnell unschön. Am besten einfach Klammern beim lesen weitestgehend ignorieren. ;;; defvar und defparameter haben kleine unterschiede: (defvar a 10) ; defvar erzeugt hier eine Variable. ;A a ;10 (defvar a 42) ; defvar kann eine Variable nicht überschreiben. ;A a ;10 (defparameter b 10) ; defparameter weist 10 zu b. ;B b ;10 (defparameter b 20) ; defparameter weist 20 zu b. ;B b ;20 ;;; setq und setf haben auch kleine Unterschiede. Welche das sind, kann hier ;;; https://stackoverflow.com/questions/869529/difference-between-set-setq-and-setf-in-common-lisp ;;; nachgelesen werden. Prinzipiell kann immer setf verwendet werden, vergiss also einfach, dass es setq gibt, wenn du selber lisp programmierst. ) #| Wenn du das liest, solltest du eine Pause machen, das war jetzt schon recht viel Zeug. Am besten liest du das alles nochmal nach, wenn es dir zu viel auf einmal war. Bis jetzt haben wir uns nicht an Konventionen gehalten. Das ist schlecht. Wir ändern das nun: Globale Variablen haben spezielle Namen, damit man direkt sieht, dass sie global sind: *globale-var*: die * zeigen, dass das Ding echt special ist, globale vars haben ein großes fuck-up potential. Konstanten haben eine ähnliche form: +const-var+ Klammern werden nicht wie bisher organisiert (nicht so wie in anderen Sprachen normalerweise, mehr im nächsten bsp) |# ;;; Klammern Organisation (defun some-function (param-A param-B) (let ((c 4)) (+ param-A param-B c))) ; Ende der Funktion ; Die schließenden Klammern werden hinten angestaut, die interessieren eh niemand. Die Funktionen werden dann entsprechend eingerückt, wie in Python. ; Nur dass es nicht verpflichtend ist... lisp ist eigentlich Python nur mit Klammern xD. ;;; Das wars auch schon mit Konventionen. Machen wir weiter mit call-by-value: ;;; Es gibt nur Call-By-Value. (defvar *a* 42) ;*a* *a* ;42 (defun ch (a) (defvar a 69)) ;CH (ch *a*) ;69 *a* ;42 ;;; Let überschreibt nur innerhalb der Funktion (man nennt das überdecken oder overshadowing) *a* ;42 (defun fun () ; Anstatt einer leeren Parameterliste kann auch nil geschrieben werden. (let ((*a* 69) (b 42)) (+ *a* b))) ;111 *a* ;42 ;;; setf kann defvar-deklarierte und defparameter-deklarierte variablen überschreiben, das ist aber nur von dauer, wenn in globalem scope (setf *a* 69) ;69 *a* ;69 (setf *a* 42) ;42 *a* ;42 ;;; quote verhindert die evaluierung eines symbols, einer liste, etc (quote *a*) ;*a* *a* ;42 (quote (list a b c)) ;(LIST A B C) ;;; quote braucht man so oft, dass es eine einfachere syntax gibt: '*a* , es sind keine klammern nötig '*a* ;*a* ;;; sei vorsichtig: quote verletzt die standardevaluierungsregeln von lisp: die eval regeln sind wie weiter oben genannt: ;;; von links nach rechts, das 0-te element aber als letztes (quote *a*) ;kann mit den normalen regeln nie zu *a* auswerten, da *a* selbst ja zuerst mal zu 42 evaluiert werden würde. ;;; wenn dann die quote funktion darauf angewandt würde, würde das ja das gleiche sein wie '42, da kommt aber 42 raus. ;;; quote ist eine sogenannte "special-form", d.h. es ist quasi eine funktion aber sie darf von den standard regeln abweichen. #| kommen wir nun zu brauchbaren teilen der sprache bzw. der programmierung. da du nun die meisten regeln kennst, können wir jetzt den richtig krassen shit machen. |# ; mit defun kannst du funktionen definieren. die verhalten sich so wie die funktionen in den meisten anderen programmiersprachen. (defun fun-2 nil nil) ; lisp hat etwa 800 vordefinierte funktionen, viele davon sind sehr nützlich, alle kannst du selber implementieren. ; viele der bereits definierten lisp funktionen werden aber schneller sein, als deine eigenen, da diese schon gut optimiert sind. ; eine der wichtigen funktionen ist map. in lisp heißt map mapcar. mapcar nimmt als parameter eine funktion und eine liste ; und returned eine neue liste, in der alle elemente der alten liste drin sind, aber die funktion wurde auf jedes der parameter angewandt. (defun quadriere (x) (* x x)) ; das hier sollte mittlerweile sinn machen :) (mapcar (function quadriere) (quote (1 2 3))) ;(1 4 9) ; mit function kannst du eine funktion als parameter übergeben. function ist ähnlich wie quote, ; es gibt die tatsächliche funktion mit rein, ohne die funktion selbst auszuwerten. ; weil es immer so anstrengend ist, function zu schreiben, gibt es auch hier eine short version: #' ; man kann mapcar also auch so aufrufen: (mapcar #'quadriere '(1 2 3)) ;(1 4 9) #| an dieser stelle kannst du wieder eine pause einlegen, du solltest aber unbedingt "mapcar", "function", "#'", "quote" und "'" verstanden haben. wenn das alles noch nicht so wirklich sinn macht, lies dir einfach den letzten abschnitt hier nochmal durch. |# ;;; "warum heißt mapcar nicht einfach map" könntest du dich fragen. schließlich müsstest du nur die hälfte der buchstaben tippen, wenn es nur map hieße. ; es hat tatsächlich einen grund, dass es nicht nur map heißt. listen sind aus sogenannten cons-zellen aufgebaut. zu cons zellen gibts gratis ne funktion dazu. ; diese funktion heißt cons. mit cons kannst du eine cons-zelle bilden. als parameter gibst du der cons funktion einfach 2 dinge: den "car" und den "cdr" (wird cudar gesprochen) ; car bezeichnet das erste element der cons zelle , cdr den rest (nicht das 2. element sondern den rest :O) ; mit cons zellen kannst du listen bilden. ; ; cons zelle cons zelle 2 nil ; +----+----+ +----+----+ ; | 69 | ------>| 42 | -------> nil ; +----+----+ +----+----+ ; car cdr car cdr ; ; dafür kennst du schon eine kurzschreibweise: (list 69 42) ;(69 42) ; ; du kannst list immer auch durch cons ersetzen: (cons 69 (cons 42 nil)) ;(69 42) ; ; car und cdr heißen aus historischen gründen so. ich gehe nicht weiter darauf ein. ; wenn der cdr einer cons zelle nicht auf den car einer anderen cons zelle oder auf nil zeigt, sondern z.b. auf eine weitere zahl, dann sieht das so aus: ; cons zelle ; +----+----+ ; | 69 | 42 | ; +----+----+ ; car cdr ; um das exakt darzustellen, hat lisp nochmal eine extra syntax: (cons 69 42) ;(69 . 42) ; wird dottet-pair genannt ; ; um wieder auf den anfang des blocks zurückzukommen, mapcar heißt mapcar, weil es map ist und aus der liste alle cars nimmt. ; ; du bist nicht gezwungen, car und cdr zu nutzen, es gibt die deutlich modernere schreibweise first und rest. #| du kennst nun: - syntax von lisp - funktionen - listen und cons-zellen - mapcar (eine funktion höherer ordnung) |# ;;; wir machen an dieser stelle weiter mit mehr funktionen höherer ordnung und warum die dinger höherer ordnung sind. (reduce #'+ '(1 2 3 4)) ;10 ;fällt dir auf, was diese funktion macht? versuch erst zu erraten was hier geschieht. ;;; die funktion reduce nimmt wieder eine funktion und eine liste und wendet dann die funktion auf alle elemente der liste an. also im prinzip wie mapcar. ; der unterschied ist aber dass mapcar mit sogenannten unären funktionen arbeitet und reduce mit binären, d.h. die funktion die du mapcar füttern kannst, muss auf ; einem einzelnen element operieren, während reduce auch mit + klar kommt. + braucht mindestens 2 args, sonst macht es keinen sinn. ; was reduce intern macht ist: es hat eine variable intern. dann nimmt es das erste car aus der liste und benutzt die funktion die du reduce gegeben hast. ; als argumente für die funktion nimmt reduce einfach die interne variable und das car und das ergebnis wird in der internen variablen gespeichert. ; als nächstes nimmt reduce das 2. car aus der liste und nutzt wieder die funktion etc. ; somit wird aus (reduce #'+ '(1 2 3 4)) dann 1 + 2 + 3 + 4 = 10 ; map und reduce sind sehr häufig nutzbare konzepte, die du in vielen algorithmen anwenden kannst. ; so kannst du etwa 70% der algorithmen der standard library in c++ (Stand 2020) mit reduce implementieren. das ist kein scherz. ; ; aber warum heißten map und reduce funktionen höherer ordnung? ; weil sie funktionen als parameter nehmen und sich die eigene funktionalität je nach gegebener funktion massiv unterscheidet. #| du weißt nun auch, was genau funktionen höherer ordnung sind. und wie man sie verwendet. als nächstes kannst du versuchen, dir einige eigene funktionen höherer ordnung selbst auszudenken. das ist eine super übung. |# ; Bleiben wir noch mal eben bei Funktionen. Hier hast du eine typische Funktion, welche ein gutes Beispiel für die Optimierungen von Compilern ; bietet. Die Funktion ist die Fakultätsfunktion, die Fakultät von 5 ist 5 * 4 * 3 * 2 * 1 = 120. Die Fakultät von 4 ist 4*3*2*1=24 ; Fakultätsrechnen ist in vielen Bereichen der Mathematik gar nicht wegzudenken. Die typische Schreibweise ist 5!. ; Kommt dir bekannt vor? Hier ist die Funktion: (defun fakulty (n) (if (< n 2) 1 (* n (fakulty (- n 1))))) ; Der Nachteil dieser Implentierung ist, dass das Programm immer n Stackframes benötigt, da sich die Funktion immer n-mal selbst aufruft. ; Bei großen Zahlen für n stürzt so das Programm ab, denn die Größe des Stacks ist begrenzt. Du kannst mal ausprobieren, wie groß der Stack ; bei deinem Computer ist, bei mir stürzt das programm ab, wenn ich für n 996 einsetze. ; Hier ist eine bessere Version der fakulty methode: (defun fakulty (n &optional (old_n 1)) (if (< n 2) old_n (fakulty (- n 1) (* old_n n)))) ; Das sieht jetzt schon viel komplizierter aus, aber es ist (fast) das gleiche Programm. ; Die Änderungen sind: wir haben jetzt einen optionalen Parameter (old_n). Dieser wird auf 1 gesetzt, wenn wir ihn nicht angeben. ; Anstatt am ende n * fakulty (n - 1) zu schreiben, haben wir die multiplikation in das old_n des nächsten Funktionsaufrufs ausgelagert. ; Bei n < 2 geben wir nicht 1 zurück, sondern old_n, welches das Endergebnis beinhaltet. ; Die MASSIVEN Vorteile die wir dabei jetzt haben, sind vor allem unsere Compileroptimierungen (ja LISP hat einen compiler). ; Dazu können wir mit (compile 'fakulty) die Funktion compilieren, wir bekommen dann eine Version der Funktion fakulty, welche ; den Stack viel besser nutzt als die alte Version. Sie braucht nur ein einziges Stackframe. ; Das funktioniert, indem der Compiler merkt, dass wir einen sogenannten Akkumulator verwenden (old_n). ; Der Compiler merkt hier, dass wir die alten Stackframes nicht brauchen, und entfernt diese für uns. ; Die short und takeaway-lesson dabei ist folgende: Benutze einen Akkumulator (für Rekursive Funktionen), wann immer du kannst. ;;; als nächstes großes thema stehen noch makros auf dem plan. ; makros sind funktionen, die funktionen generieren. das hört sich spoopy an aber ist relativ ez. ; lisp hat keine while schleife. es hat sowas ähnliches, ist aber ziemlich wonky das zu nutzen. ; was wir haben, ist das hier: (setf x 0) (loop while (< x 10) do (format t "~d " x) (setf x (+ x 1))) ;0 1 2 3 4 5 6 7 8 9 ;nil ; was wir viel lieber hätten ist aber das hier: #| (setf x 0) (while (< x 10) (format "~d " x) (setf x (+ x 1))) |# ; das loop und das do sind so oldfashioned, wir neumodischen programmierer finden das doof und man kann ja viel syntax sparen und so... ; und lisp lässt uns nicht hängen: es gibt zum glück makros, die uns genau das ermöglichen. ; makros schreibt man fast wie funktionen: (defmacro while (test &body body) #| hier kommt der eigentliche code hin |# ) ; sieht so weit schon stark aus wie eine funktion, nicht wahr? ; &body ist ähnlich wie &optional (das hatten wir schon weiter oben), aber anstatt optionale parameter zu markieren, ist es einfach der rest in der parameterliste. ; unsere gewünschte while funktion hat auch 3 parameter: einmal den test, dann die funktion format, dann die funktion setf. wir können so beliebig viele parameter reinwerfen. #| (defmacro while (test &body body) (list 'loop 'while test 'do body)) |# ; sowas in der art wollen wir ja, das wird aber leider noch nicht funktionieren, da body noch als liste gesehen wird. in unserem fall ist body gleich wie ; ((format t "~d " x) (setf x (+ x 1))) ; was wir brauchen ist das hier als body: ; (progn (format t "~d " x) (setf x (+ x 1))) ; progn macht einfach dass alles in dem block als separates statement ausgeführt wird. ; irgendwie müssen wir also das progn vor das format in die liste rein kriegen. fällt dir was ein? ; hier ist die lösung: wir können cons dafür benutzen: (defmacro while (test &body body) (list 'loop 'while test 'do (cons 'progn body))) ; damit sollten wir jetzt endlich unsere while schleife benutzen können, so wie wir wollen. #| (setf y 0) (while (< y 10) (format "~d " y) (setf y (+ y 1))) |# ; probier am besten selbst aus, ob das so klappt (ich hab das natürlich selbst schon getestet und es funktioniert ^^). ; wenn das alles für dich nachvollziehbar war, dann herzlichen glühstrumpf, du bist fertig mit dem tutorial. wenn du lisp komisch aber iwie cool findest, dann gehts dir ; genau wie allen anderen, die beschlossen haben, mit lisp weiter zu machen. ab hier kommst du recht gut alleine zurecht. ; solltest du probleme haben, einfach nochmal lesen, so wie immer. du kannst mir auch auf discord fragen stellen. Den Kontakt findest du ganz unten. ; das tut soll dich im prinzip auch nur soweit bringen, dass du einigermaßen zurecht kommst. es ist auch nicht schlimm, wenn du sagst, bah lisp ist ja eklig. ; dann ist es einfach nix für dich. aber du solltest trotzdem respektieren, dass lisp die älteste programmiersprache ist, die immer noch ernsthaft genutzt wird. ; außerdem kamen aus lisp sehr viele konzepte, die später wieder verwendet wurden: ; erstmals in lisp wurden eingeführt: #| dynamische typisierung garbage collection rekursion makros in dieser art |# ; durch das makro system ist lisp in der lage, sich der aufgabe anzupassen, was es theoretisch zu der besten sprache macht, die man gut können kann. ; Leider ist lisp aber nicht weit genug verbreitet, dass es sich wirklich lohnt, die gesamte sprache zu erlernen. ; Mehr infos zu lisp findest du auf ; https://lisp-lang.org/ ; http://www.gigamonkeys.com/book/ ; https://github.com/norvig/paip-lisp ; das sind zumindest die ressourcen, die ich verwendet habe. wenn ich was vergessen haben sollte, sag mir einfach bescheid. Kontakt ist gaaaanz unten ; ; hilfe kannst du immer hier bekommen: ; https://stackoverflow.com/ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Kontakt: L0ren22#7274 (Discord) ; cheers :)
17,023
Common Lisp
.lisp
309
52.724919
177
0.746043
L0ren2/lisp_tut
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
1e29ee64fd0e6bad8f510cb195e4aa2ce0f1bf8b0da32961a172174aa003f27e
40,409
[ -1 ]
40,426
operators.lisp
retq_SimpleSyntaxLISP/src/operators.lisp
(in-package :cl-syntax) (eval-when (:compile-toplevel :load-toplevel :execute) (defun package-syntax-name (package) (intern *standard-package-syntax-name* package))) (defun get-options (name) "Get the options list for name, if it is available." (get (cond ((typep name 'syntax) nil) ((and (typep name 'package-designator) (find-package name)) (package-syntax-name name)) (t name)) :options)) (defmacro defsyntax (name &body options) `(progn (setf (get ',name :options) ',options) (defvar ,name (defreadtable ,name ,@options)))) (defmacro define-package-syntax (&body (package . options)) (unless (typep package 'package-designator) (push package options) (setq package *package*)) `(defsyntax ,(package-syntax-name package) ,@options)) (defun find-syntax (name) (declare (syntax-designator name)) (cond ((typep name 'syntax) name) ((and (typep name 'package-designator) (find-package name)) (find-readtable (package-syntax-name name))) (t (find-readtable name)))) (defun %use-syntax (names) (declare (type (or syntax-designator (proper-list syntax-designator)) names)) (unless (listp names) (setq names (list names))) (setq *readtable* (copy-readtable)) (loop for name in names for syntax = (find-syntax name) for options = (get-options name) if (assoc :fuze (if (consp (car options)) options (cdr options))) do (handler-bind ((named-readtables:reader-macro-conflict (lambda (_) (declare (ignore _)) (invoke-restart 'continue)))) (merge-readtables-into *readtable* syntax) ) else do (merge-readtables-into *readtable* syntax) ) (when (find-package :swank) (named-readtables::%frob-swank-readtable-alist *package* *readtable*))) (defmacro use-syntax (name) `(eval-when (:compile-toplevel :load-toplevel :execute) (%use-syntax ,name)))
2,027
Common Lisp
.lisp
51
33
76
0.640934
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
83b0aadfab45d0ba0fca6c44759a8267dbd9235205d0d899dd9d0dab2efe1e5b
40,426
[ 372042 ]
40,427
types.lisp
retq_SimpleSyntaxLISP/src/types.lisp
(in-package :cl-syntax) (deftype syntax () 'readtable) (deftype syntax-designator () '(or syntax package-designator named-readtable-designator))
163
Common Lisp
.lisp
6
23.166667
35
0.716129
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
e647931c4c599f037758f874a4dbb80bfbf7cb11e23cc714b008ccdd14d9f3ac
40,427
[ 326264 ]
40,428
packages.lisp
retq_SimpleSyntaxLISP/src/packages.lisp
(in-package :cl-user) (defpackage :cl-syntax (:nicknames :syntax) (:use :cl :named-readtables) (:import-from :trivial-types #:package-designator #:proper-list) (:export #:syntax #:syntax-designator #:defsyntax #:define-package-syntax #:find-syntax #:use-syntax))
359
Common Lisp
.lisp
13
19.230769
36
0.556522
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
b49e8f0b7b1eaab1d6320f5d16827a8c224230f9420b3b01d8f1503fecff8786
40,428
[ 287578 ]
40,429
markup.lisp
retq_SimpleSyntaxLISP/contrib/markup.lisp
(in-package :cl-user) (syntax:define-package-syntax :cl-markup (:merge :standard) (:dispatch-macro-char #\# #\M #'cl-markup::markup-reader))
146
Common Lisp
.lisp
4
34.25
60
0.702128
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
50a87b940a9d6172b556fc176f73b3613005064c1f321b6bede277531e9525e0
40,429
[ 251989 ]
40,430
anonfun.lisp
retq_SimpleSyntaxLISP/contrib/anonfun.lisp
(in-package :cl-user) (syntax:define-package-syntax :cl-anonfun (:merge :standard) (:dispatch-macro-char #\# #\% #'cl-anonfun::fn-reader))
144
Common Lisp
.lisp
4
33.75
57
0.690647
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
a71682de02174f190a7ed8a2fb55dbef2c04428bb7c890a6e2d443aa2b58fbac
40,430
[ 325252 ]
40,431
fare-quasiquote.lisp
retq_SimpleSyntaxLISP/contrib/fare-quasiquote.lisp
(in-package :fare-quasiquote) (syntax:defsyntax fare-quasiquote-mixin (:macro-char #\` #'read-read-time-backquote) (:macro-char #\, #'read-comma) (:macro-char #\# :dispatch) (:dispatch-macro-char #\# #\( #'read-hash-paren)) (syntax:define-package-syntax :fare-quasiquote (:fuze :standard fare-quasiquote-mixin))
326
Common Lisp
.lisp
8
38
51
0.702532
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
89da490752b44a35ba5cae0fcf81548e784eb49db9e1e58f1639188765e7b22a
40,431
[ 337887 ]
40,432
clsql.lisp
retq_SimpleSyntaxLISP/contrib/clsql.lisp
(in-package :cl-user) (syntax:define-package-syntax :clsql (:merge :standard) (:macro-char #\[ #'clsql-sys::sql-reader-open) (:macro-char #\] (cl:get-macro-character #\))))
180
Common Lisp
.lisp
5
33.6
49
0.666667
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
d35c0a5dbc54fde05b5fb58a5b5bfcf2be711af5dfb617a98fd984b0925ce75a
40,432
[ 206179 ]
40,433
interpol.lisp
retq_SimpleSyntaxLISP/contrib/interpol.lisp
(in-package :cl-user) (syntax:define-package-syntax :cl-interpol (:merge :standard) (:dispatch-macro-char #\# #\? #'cl-interpol::interpol-reader))
152
Common Lisp
.lisp
4
35.75
64
0.707483
retq/SimpleSyntaxLISP
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
07a3dd2952663b1c439fc676b15e7e96605d48ba968f44b01344000abecc463b
40,433
[ 215646 ]
40,457
ast.lisp
psteeve_tsinco/src/ast.lisp
(in-package :tsinco.ast) (defgeneric get-compiler-options (script-reference-host)) (defgeneric get-source-file (script-reference-host file-name)) (defgeneric get-source-file-by-path (script-reference-host path)) (defgeneric get-current-directory (script-reference-host)) (defgeneric get-root-file-names (program) (:documentation "Get a list of root file names that where passed to a \"createProgram\"")) (defgeneric get-source-files (program) (:documentation "Get a list of files in the program.")) (defgeneric emit (program &key target-source-file? write-file? cancellation-token? emit-only-dts-files? custom-transformers? )) (defgeneric get-options-diagnostics (program cancellation-token?)) (defgeneric get-global-diagnostics (program cancellation-token?)) (defgeneric get-syntactic-diagnostics (program &key source-file? cancellation-token?)) (defgeneric get-semantic-diagnostics (program &key source-file? cancellation-token?)) (defgeneric get-declaration-diagnostics (program &key source-file? cancellation-token?)) (defgeneric get-config-file-parsing-diagnostics (program)) (defgeneric get-type-checker (program)) (defgeneric is-source-file-from-external-library (program)) (defgeneric is-source-file-from-default-library (program)) (defgeneric get-project-references (program)) (defgeneric get-resolved-project-references (program))
1,819
Common Lisp
.lisp
33
39.636364
92
0.597973
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
2c113e22e955de3add5f20be2ac11465c650eb9ed6b4ba72cbece135a388847a
40,457
[ -1 ]
40,458
keywords-type-node.lisp
psteeve_tsinco/src/keywords-type-node/keywords-type-node.lisp
(in-package :tsinco.keywords-type-node) (defmacro define-keyword-type-node (types) `(progn ,@(mapcar #'(lambda (x) `(defclass ,x (keyword-type-node) ((kind :initarg :kind :initform ,(st-utils:as-keyword x) :reader kind)))) types))) (define-keyword-type-node (any-keyword unknown-keyword number-keyword big-int-keyword object-keyword boolean-keyword string-keyword symbol-keyword this-keyword void-keyword undefined-keyword null-keyword never-keyword))
902
Common Lisp
.lisp
22
19.545455
63
0.396571
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
c1588c809d99b7c9ffb91e5a55a63061b4e1a551da879cbac23a34fac4f2cf69
40,458
[ -1 ]
40,459
example.lisp
psteeve_tsinco/src/examples/example.lisp
(defvar *source-file* '(:source-file :pos 0 :end 21 :statements ((:expression-statement :pos 0 :end 21 :expression (:call-expression :pos 0 :end 20 :expression (:property-access-expression :pos 0 :end 11 :name (:identifier :pos 8 :end 11 :escaped-text "log") :expression (:identifier :pos 0 :end 7 :escaped-text "console")) :arguments (:node-array :pos 12 :end 26 :node-list ((:string-literal :pos 12 :end 26 :text "hello, world")))))) :end-of-file-token (:end-of-file-token :pos 28 :end 28) :filename "astExplorer.tsx" :text "console.log('hello, world');"))
1,325
Common Lisp
.lisp
35
14.971429
56
0.30155
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
3efe34a2aa3d3383c8e69af208f200f50567c45adbcf465d9d8d7c4af7b96d8c
40,459
[ -1 ]
40,460
ts-parser-example.lisp
psteeve_tsinco/src/examples/ts-parser-example.lisp
(defvar *type-alias-declaration* '(:pos 14 :end 100 :modifiers (:node-array :pos 129 :end 130 :node-list ((:export-keyword :pos 14 :end 25))) :name (:identifier :pos 30 :end 44 escaped-text "ErrorCallback") :type (:function-type :pos 46 :end 99 :parameters (:node-array :pos 48 :end 90 :node-list ((:parameter :pos 48 :end 74 :name (:identifier :pos 48 :end 55 :escaped-text "message") :type (:type-reference :pos 56 :end 74 :type-name (:identifier :pos 56 :end 74 :escaped-text "DiagnosticMessage"))) (:parameter :pos 75 :end 90 :name (:identifier :pos 75 :end 82 :escaped-text "length") :type (:number-keyword :pos 83 :end 90))))))) (defvar *module-delcaratiion* '(:module-declaration :pos 0 :end 113623 :name (:identifier :pos 9 :end 12 :escaped-text "ts") :body (:module-block :pos 12 :end 113623 :statements (*type-alias-declaration* *function-declaration-1* *function-declaration-2* *interface-declaration*))))
3,678
Common Lisp
.lisp
56
15.375
126
0.17943
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
376dad862880631d126dc687fe0cd9e01ff8409538df019bac197e252ebce4ff
40,460
[ -1 ]
40,461
cons-form.lisp
psteeve_tsinco/src/utils/cons-form.lisp
(defpackage :tsinco.utils (:use :common-lisp) (:export :cons-form-p)) (in-package :tsinco.utils) (defun cons-form-p (form &optional (test #'keywordp)) (and (consp form) (let ((car-of-form (car form))) (or (funcall test car-of-form) (and (cons-form-p car-of-form))))))
308
Common Lisp
.lisp
10
25.8
53
0.611486
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
6bca9ff3422be4b02ec6f2a629518165191fee8c354546cbd63740b80544f622
40,461
[ -1 ]
40,462
parse-simple-sexp.lisp
psteeve_tsinco/src/utils/parse-simple-sexp.lisp
(in-package :tsinco.utils) (defun make-instance-for (object-name value) (apply #'make-instance object-name value)) (defun parse-simple-sexp (sexp) "Parse an expression of the form (:tag :prop 1 :prop2 2 :prop3 3) to produce an object of type tag example: (parse-simple-sexp '(:identifier :pos 20 :end 34 :escaped-text \"log\")) return an object identifier with props (:pos 20 :end 34 :escaped-text \"log\") assume the definition of identifier exists." (destructuring-bind (tag &rest props) sexp (let ((object-name (find-symbol (symbol-name tag)))) (make-instance-for object-name props))))
607
Common Lisp
.lisp
12
48.083333
81
0.728499
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
4c3b518d7b52419c735bffbcc95e85d952457fe77d8c4d891baa1317bcc6c2c5
40,462
[ -1 ]
40,463
text-range.lisp
psteeve_tsinco/src/nodes-elements/text-range.lisp
(in-package :text-range) (defclass text-range () ((pos :initarg :pos :initform 0 :reader pos) (end :initarg :end :initform 0 :reader end)))
162
Common Lisp
.lisp
6
22.333333
46
0.625806
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
63297472319960925826b65d570b4eb97c9ca8dbf2c7805eeb9823c7ea9da427
40,463
[ -1 ]
40,464
variable-declaration.lisp
psteeve_tsinco/src/nodes-elements/variable-declaration.lisp
(defclass variable-declaration (named-declaration) ((kind :initarg :kind :initform :variable-declaration :reader kind) (parent :initarg :parent :initform (error "Must supply value for parent") :reader parent) (name :initarg :name :initform (error "Must supply a value for name") :reader name) (initializer :initarg :initializer :initform (error "Must supply a value form initializer.") :reader initializer) (exclamation-token :initarg :exclamation-token :reader exclamation-token) (v-type :initarg :v-type :reader v-type)))
541
Common Lisp
.lisp
7
73.857143
116
0.754682
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
288041322a48f070abd35ecc326e68d777afa724ad24f1704a20c6ac073f11e7
40,464
[ -1 ]
40,465
export-declaration.lisp
psteeve_tsinco/src/nodes-elements/export-declaration.lisp
(defclass export-declaration (declaration-statement) ((kind :initarg :kind :initform :export-declaration :reader kind) (parent :initarg :parent :initform (error "Must supply a value for \"parent\"") :reader parent) (import-clause :initarg :import-clause :reader import-clause) (module-specifier :initarg :module-specifier :reader module-specifier)))
440
Common Lisp
.lisp
11
30.818182
65
0.631702
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
192444b7830919f03fa0386fbeefb072cc91bca84eb1d19c74f968c01cd9d299
40,465
[ -1 ]
40,466
clauses.lisp
psteeve_tsinco/src/nodes-elements/clauses.lisp
(in-package :tsinco.node-elements) (defclass cach-clause (node) ((kind :initarg :kind :initform :cach-clause :reader kind) (parent :initarg :parent :initform (error "Must supply a value for parent.") :reader parent) (variable-declaration :initarg :variable-declaration :reader variable-declaration) (a-block :initarg :a-block :initform (error "Must supply a value for a-block.") :reader a-block))) (defclass case-block (node) ((kind :initarg :kind :initform :case-block :reader kind) (parent :initarg :parent :initform (error "Must provide a value for \"parent\"") :reader parent) (clauses :initarg :clauses :initform (error "Must provide a value for \"clauses\"") :reader clauses))) (defclass case-clause (node) ((kind :initarg :kind :initform :case-clause :reader kind) (parent :initarg :parent :initform (error "Must provide a value for \"parent\"") :reader parent) (expression :initarg :expression :initform (error "Must provide a value for \"expression\"") :reader expression) (statements :initarg :statements :initform (error "Must provide a value for \"statements\"") :reader statements ))) (defclass default-clause (node) ((kind :initarg :kind :initform :default-clause :reader kind) (parent :initarg :parent :initform (error "Must provide a value for \"parent\"") :reader parent) (statements :initarg :statements :initform (error "Must provide a value for \"statements\"") :reader statements)))
1,696
Common Lisp
.lisp
40
34.1
101
0.630527
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
24a1d2e4b373681cbdac836c9b4de4455b2600bd4c1e80604b16f7c9618aed1d
40,466
[ -1 ]
40,467
named-imports.lisp
psteeve_tsinco/src/nodes-elements/named-imports.lisp
(defclass named-imports (node) ((kind :initarg :kind :initform :named-imports :reader kind) (parent :initarg :parent :reader parent) (elements :initarg :elements :initform (error "Must supply a value for \"elements\""))))
272
Common Lisp
.lisp
8
26.75
72
0.617424
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
d272f853a4db9bae25df611e18d1990182577d1950561a10b92359337b33f243
40,467
[ -1 ]
40,468
void-expression.lisp
psteeve_tsinco/src/nodes-elements/void-expression.lisp
(defclass void-expression (unary-expression) ((kind :initarg :kind :initform :void-expression :reader kind) (expression :initarg :expression :initform (error "Must supply a value for expression.") :reader expression)))
224
Common Lisp
.lisp
3
72
113
0.764706
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
2bc56eb4ea80d0b928e5431b9d9d0c939e881f410698c2087f822f3dc9df4f83
40,468
[ -1 ]
40,469
switch-statement.lisp
psteeve_tsinco/src/nodes-elements/switch-statement.lisp
(in-package :tsinco.node-elements) (defclass switch-statement (statement) ((kind :initarg :kind :initform :switch-statement :reader kind) (expression :initarg :expression :initform (error "Must provide a value for \"expression\"") :reader expression) (case-block :initarg :case-block :initform (error "Must provide a value for \"case-block\"") :reader case-block) (possibly-exhaustive :initarg :possibly-exhaustive :reader possibly-exhaustive)))
458
Common Lisp
.lisp
6
73.333333
115
0.758315
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
4fda6dd8995cff9c9ade41c5f74bfc40f1e535f8eb9a8c9822304cfd20827d43
40,469
[ -1 ]
40,470
class-declaration.lisp
psteeve_tsinco/src/nodes-elements/class-declaration.lisp
(in-package :tsinco.node-elements) (defclass class-declaration (class-like-declaration-base declaration-statement) ((kind :initarg :kind :initform :class-declaration :reader kind) (name :initarg :name :reader name))) (defmethod initialize-instance :after ((object class-declaration) &key) (with-slots (decorators name modifiers) object (setf decorators (mapcar #'parse-simple-sexp (decorators object))) (setf name (parse-simple-sexp (name object))) (setf modifiers (mapcar #'parse-simple-sexp (modifiers object)))))
564
Common Lisp
.lisp
12
42
79
0.721818
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
704c8445176599b169ea5f4f8a7a701aab0093f6a3be4eaa2f6f2ec3a271d7d6
40,470
[ -1 ]
40,471
token.lisp
psteeve_tsinco/src/nodes-elements/token.lisp
(defpackage :tsinco.ast (:use :common-lisp)) (in-package :tsinco.ast) (define-token-class (open-brace-token close-brace-token open-paren-token close-paren-token open-bracket-token close-bracket-token dot-token dot-dot-dot-token semicolon-token comma-token less-than-token less-than-slash-token greater-than-token less-than-equals-token greater-than-equals-token equals-equals-token exclamation-equals-token equals-equals-equals-token exclamation-equals-equals-token equals-greater-than-token plus-token minus-token asterisk-token asterisk-asterisk-token slash-token percent-token plus-plus-token minus-minus-token less-than-less-than-token greater-than-greater-than-token greater-than-greater-than-greater-than-token ampersand-token bar-token caret-token exclamation-token tilde-token ampersand-ampersand-token bar-bar-token question-token colon-token at-token backtick-token equals-token plus-equals-token minus-equals-token asterisk-equals-token asterisk-asterisk-equals-token slash-equals-token percent-equals-token less-than-less-than-equals-token greater-than-greater-than-equals-token greater-than-greater-than-greater-than-equals-token ampersand-equals-token bar-equals-token caret-equals-token dotdot-token question-token exclamation-token colon-token equals-token asterisk-token equals-greater-than-token end-of-file-token readonly-token await-keyword-token)) (define-token-class (abstract-keyword async-keyword const-keyword declare-keyword default-keyword export-keyword public-keyword private-keyword protected-keyword readonly-keyword static-keyword))
2,108
Common Lisp
.lisp
81
18.320988
56
0.647553
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
368e01be5bd37d60b2b06976663449d997ba68fe73139b0ce0fec06dce3f4a7e
40,471
[ -1 ]
40,472
binary-expression.lisp
psteeve_tsinco/src/nodes-elements/binary-expression.lisp
(defclass binary-expression (expression a-declaration) ((kind :initarg :kind :initform :binary-expression :reader kind) (left :initarg :left :initform (error "Must supply a value for left") :reader left) (operator-token :initarg :operator-token :initform (error "Must suppla a value for \"operator-token\"") :reader operator-token) (right :initarg :right :initform (error "Must supply a value for right") :reader right))) (defmethod initialize-instance :after ((object binary-expression) &key) (with-slots (left right operator-token) object (setf left (parse-simple-sexp (left object))) (setf operator-token (parse-simple-sexp (operator-token object))) (setf right (parse-simple-sexp (right object)))))
768
Common Lisp
.lisp
12
57.583333
92
0.704244
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
63e93e0f9c84b40ba1dad68ef3c984d1bd871e510e36afd08825757437a3e3bf
40,472
[ -1 ]
40,473
for-of-statement.lisp
psteeve_tsinco/src/nodes-elements/for-of-statement.lisp
(defclass for-of-statement (iteration-statement) ((kind :initarg :kind :initform :for-of-statement :reader kind) (await-modifier :initarg await-modifier :reader await-modifier) (initializer :initarg :for-initializer :initform (error "Must supply a value for initializer.") :reader initializer) (expression :initarg :expression :initform (error "Must supply a value for expresson.") :reader expression)))
415
Common Lisp
.lisp
5
79.8
119
0.768293
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
a64fd2631f798f8958566e1d62daa5f289c37c604d5cdcd8b9438d0ebd147ac7
40,473
[ -1 ]
40,474
import-clause.lisp
psteeve_tsinco/src/nodes-elements/import-clause.lisp
(defclass import-clause (named-declaration) ((kind :initarg :kind :initform :import-clause :reader kind) (parent :initarg :parent :reader parent) (name :initarg :name :reader name) (is-type-only :initarg :is-type-only :reader is-type-only) (named-bindings :initarg :named-bindings :reader named-bindings))) (defmethod initialize-instance :after ((object import-clause) &key) (with-slots (named-bindings) object (setf named-bindings (parse-simple-sexp (named-bindings object)))))
557
Common Lisp
.lisp
14
33.214286
71
0.671587
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
95b0dc740d2d1efd393a036a8c32249f1d599d4c93a781f6d5d364bc170a07fc
40,474
[ -1 ]
40,475
object-binding-pattern.lisp
psteeve_tsinco/src/nodes-elements/object-binding-pattern.lisp
(defclass object-binding-pattern (node) ((kind :initarg :kind :initform :object-binding-pattern :reader kind) (parent :initarg :parent :initform (error "Must supply a value form parent.") :reader parent) (elements :initarg :elements :initform (error "Must supply a value form elements.") :reader elements)))
316
Common Lisp
.lisp
4
76
106
0.746795
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
812ed87faddb1dd302522fe9b669a64f48b15e33d6d7b89c7406296c01f646dd
40,475
[ -1 ]
40,476
property-assignment.lisp
psteeve_tsinco/src/nodes-elements/property-assignment.lisp
(defclass property-assignment (object-literal-element) ((parent :initarg :parent :reader parent) (kind :initarg :property-assignment :reader kind) (name :initarg :name :reader name) (question-token-? :initarg :question-token-? :reader question-token-?) (initializer :initarg :initializer :reader initializer))) (defmethod initialize-instance :after ((object property-assignment) &key) (with-slots (name initializer) object (setf name (parse-simple-sexp name)) (setf initializer (parse-simple-sexp initializer))))
538
Common Lisp
.lisp
10
50.3
73
0.751423
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
b31c6877f5a38bd534b5bf4ef8dff6bcffdba397c8ecab306e7bd6efd2632c34
40,476
[ -1 ]
40,477
import-declaration.lisp
psteeve_tsinco/src/nodes-elements/import-declaration.lisp
(defclass import-declaration (statement) ((kind :initarg :kind :initform :import-declaration :reader kind) (import-clause :initarg :import-clause :reader import-clause) (module-specifier :initarg :module-specifier :initform (error "Must supply a value for \"module-specifier\"") :reader module-specifier))) (defmethod initialize-instance :after ((object import-declaration) &key) (with-slots (import-clause module-specifier) object (setf import-clause (parse-simple-sexp (import-clause object))) (setf module-specifier (parse-simple-sexp (module-specifier object)))))
665
Common Lisp
.lisp
13
42.692308
85
0.678955
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
f31e5ef6428c1350f65ba029f28d34928b6f949b5a7c00c2afe933270afed4b0
40,477
[ -1 ]
40,478
interface-declaration.lisp
psteeve_tsinco/src/nodes-elements/interface-declaration.lisp
(defclass interface-declaration (declaration-statement) ((kind :initarg :kind :initform :interface-declaration :reader kind) (name :initarg :name :initform (error "Must supply a value for \"name\"") :reader name) (type-parameters :initarg :type-parameters :reader type-parameters) (heritage-clauses :initarg :heritage-clauses :reader heritage-clauses) (members :initarg :members :initform (error "Must supply a value for \"members\"") :reader members)))
569
Common Lisp
.lisp
14
31.428571
67
0.627027
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
a7abbefec63c776c4c9ed4c6cff425b3b626e59bc2dfe4938c1de61727836d7f
40,478
[ -1 ]
40,479
variable-statement.lisp
psteeve_tsinco/src/nodes-elements/variable-statement.lisp
(defclass variable-statement (statement) ((kind :initarg :kind :initform :variable-statement :reader kind) (declaration-list :initarg :declatarion-list :initform (error "Must supply value for declaration-list.") :reader declaration-list)))
287
Common Lisp
.lisp
5
47
80
0.666667
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
ff050c6fa9d0c08046c685b11a1a48fa4c343350f2d550c1ba7f969694f70053
40,479
[ -1 ]
40,480
enum-member.lisp
psteeve_tsinco/src/nodes-elements/enum-member.lisp
(defclass enum-member (named-declaration) ((kind :initarg :kind :initform :enum-member :reader kind) (name :initarg :name :initform (error "Must supply a value for \"name\"") :reader name) (initializer :initarg :initializer :reader initializer)))
255
Common Lisp
.lisp
4
60.75
90
0.733068
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
299f4300967de6f4b5d8b0560edd8857e4bba13c9c1dec0dc1bc5b4e48c41d3e
40,480
[ -1 ]
40,481
object-literal-expression-base.lisp
psteeve_tsinco/src/nodes-elements/object-literal-expression-base.lisp
(defclass object-literal-expression-base (object-literal-element primary-expression named-declaration) ((properties :initarg :properties :initform (error "Must supply a value for \"properties\"") :reader properties))) (defmethod initialize-instance :after ((object object-literal-expression-base) &key) (with-slots (properties) object (setf properties (mapcar #'parse-simple-sexp properties))))
434
Common Lisp
.lisp
7
55.428571
102
0.730047
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
36e0b8cdfff08dc79fbc7ebdcba73c7c01fb95d6d7bbaaa3098063ecfb0e00bb
40,481
[ -1 ]
40,482
binding-element.lisp
psteeve_tsinco/src/nodes-elements/binding-element.lisp
(defclass binding-element (named-declaration) ((kind :initarg :kind :initform :binding-element :reader kind) (parent :initarg :parent :initform (error "Must supply a value for parent.") :reader parent) property-name dotdot-token (name :initarg :name :initform (error "Must supply a value for name") :reader name) initializer))
344
Common Lisp
.lisp
7
45.714286
95
0.738872
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
cefbbca77327cea976472c111b2b73fac5c717563eddf01dcdecfd956817264e
40,482
[ -1 ]
40,483
iteration-statement.lisp
psteeve_tsinco/src/nodes-elements/iteration-statement.lisp
(defclass iteration-statement (statement) ((statement :initarg :statement :initform (error "Must supply a value for statement.") :reader statement)))
153
Common Lisp
.lisp
2
74
109
0.773333
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
c4dc260144e0b595d279dc0395832ddf1ed4923e97b452404c7c3f8349aafb3b
40,483
[ -1 ]
40,484
syntaxkind.lisp
psteeve_tsinco/src/nodes-elements/syntaxkind.lisp
(defpackage :esinco.syntaxkind (:use :common-lisp) (:export :unknown :end-of-file-token :single-line-comment-trivia :multi-line-comment-trivia :new-line-trivia :whitespace-trivia :shebang-trivia :conflict-marker-trivia ;; Literals :numeric-literal :big-int-literal :string-literal :jsx-text :jsx-text-all-white-spaces :regular-expression-literal :no-substitution-template-literal ;; Pseudo-literals :template-head :template-middle :template-tail ;; Punctuation :open-brace-token :close-brace-token :open-paren-token :close-paren-token :open-bracket-token :close-bracket-token :dot-token :dot-dot-dot-token :semicolon-token :comma-token :less-than-token :less-than-slash-token :greater-than-token :less-than-equals-token :greater-than-equals-token :equals-equals-token :exclamation-equals-token :equals-equals-equals-token :exclamation-equals-equals-token :equals-greater-than-token :plus-token :minus-token :asterisk-token :asterisk-asterisk-token :slash-token :percent-token :plus-plus-token :minus-minus-token :less-than-less-than-token :greater-than-greater-than-token :greater-than-greater-than-greater-than-token :ampersand-token :bar-token :caret-token :exclamation-token :tilde-token :ampersand-ampersand-token :bar-bar-token :question-token :colon-token :at-token ;; Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. :backtick-token ;; Assignments :equals-token :plus-equals-token :minus-equals-token :asterisk-equals-token :asterisk-asterisk-equals-token :slash-equals-token :percent-equals-token :less-than-less-than-equals-token :greater-than-greater-than-equals-token :greater-than-greater-than-greater-than-equals-token :ampersand-equals-token :bar-equals-token :caret-equals-token ;; Identifiers :identifier ;; Reserved words :break-keyword :case-keyword :catch-keyword :class-keyword :const-keyword :continue-keyword :debugger-keyword :default-keyword :delete-keyword :do-keyword :else-keyword :enum-keyword :export-keyword :extends-keyword :false-keyword :finally-keyword :for-keyword :function-keyword :if-keyword :import-keyword :in-keyword :instance-of-keyword :new-keyword :null-keyword :return-keyword :super-keyword :switch-keyword :this-keyword :throw-keyword :true-keyword :try-keyword :type-of-keyword :var-keyword :void-keyword :while-keyword :with-keyword ;; Strict mode reserved words :implements-keyword :interface-keyword :let-keyword :package-keyword :private-keyword :protected-keyword :public-keyword :static-keyword :yield-keyword ;; Contextual keywords :abstract-keyword :as-keyword :any-keyword :async-keyword :await-keyword :boolean-keyword :constructor-keyword :declare-keyword :get-keyword :infer-keyword :is-keyword :key-of-keyword :module-keyword :namespace-keyword :never-keyword :readonly-keyword :require-keyword :number-keyword :object-keyword :set-keyword :string-keyword :symbol-keyword :type-keyword :undefined-keyword :unique-keyword :unknown-keyword :from-keyword :global-keyword :big-int-keyword :of-keyword ;; LastKeyword and LastToken and LastContextualKeyword ;; Parse tree nodes ;; Names :qualified-name :computed-property-name ;; Signature elements :type-parameter :parameter :decorator ;; TypeMember :property-signature :property-declaration :method-signature :method-declaration :constructor :get-accessor :set-accessor :call-signature :construct-signature :index-signature ;; Type :type-predicate :type-reference :function-type :constructor-type :type-query :type-literal :array-type :tuple-type :optional-type :rest-type :union-type :intersection-type :conditional-type :infer-type :parenthesized-type :this-type :type-operator :indexed-access-type :mapped-type :literal-type :import-type ;; Binding patterns :object-binding-pattern :array-binding-pattern :binding-element ;; Expression :array-literal-expression :object-literal-expression :property-access-expression :element-access-expression :call-expression :new-expression :tagged-template-expression :type-assertion-expression :parenthesized-expression :function-expression :arrow-function :delete-expression :type-of-expression :void-expression :await-expression :prefix-unary-expression :postfix-unary-expression :binary-expression :conditional-expression :template-expression :yield-expression :spread-element :class-expression :omitted-expression :expression-with-type-arguments :as-expression :non-null-expression :meta-property :synthetic-expression ;; Misc :template-span :semicolon-class-element ;; Element :block :variable-statement :empty-statement :expression-statement :if-statement :do-statement :while-statement :for-statement :for-in-statement :for-of-statement :continue-statement :break-statement :return-statement :with-statement :switch-statement :labeled-statement :throw-statement :try-statement :debugger-statement :variable-declaration :variable-declaration-list :function-declaration :class-declaration :interface-declaration :type-alias-declaration :enum-declaration :module-declaration :module-block :case-block :namespace-export-declaration :import-equals-declaration :import-declaration :import-clause :namespace-import :named-imports :import-specifier :export-assignment :export-declaration :named-exports :export-specifier :missing-declaration ;; Module references :external-module-reference ;; JSX :jsx-element :jsx-self-closing-element :jsx-opening-element :jsx-closing-element :jsx-fragment :jsx-opening-fragment :jsx-closing-fragment :jsx-attribute :jsx-attributes :jsx-spread-attribute :jsx-expression ;; Clauses :case-clause :default-clause :heritage-clause :catch-clause ;; Property assignments :property-assignment :shorthand-property-assignment :spread-assignment ;; Enum :enum-member ;; Unparsed :unparsed-prologue :unparsed-prepend :unparsed-text :unparsed-internal-text :unparsed-synthetic-reference ;; Top-level nodes :source-file :bundle :unparsed-source :input-files ;; JSDoc nodes :js-doc-type-expression ;; The * type :js-doc-all-type ;; The ? type :js-doc-unknown-type :js-doc-nullable-type :js-doc-non-nullable-type :js-doc-optional-type :js-doc-function-type :js-doc-variadic-type :js-doc-comment :js-doc-type-literal :js-doc-signature :js-doc-tag :js-doc-augments-tag :js-doc-class-tag :js-doc-callback-tag :js-doc-enum-tag :js-doc-parameter-tag :js-doc-return-tag :js-doc-this-tag :js-doc-type-tag :js-doc-template-tag :js-doc-typedef-tag :js-doc-property-tag ;; Synthesized list :syntax-list ;; Transformation nodes :not-emitted-statement :partially-emitted-expression :comma-list-expression :merge-declaration-marker :end-of-declaration-marker ;; Enum value count :count)) (in-package :esinco.syntaxkind)
7,718
Common Lisp
.lisp
354
17.782486
129
0.726122
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
1f906883a4993c31f44a69b7e72992f8d40c339779e8820cc3ad99133dc2cd5e
40,484
[ -1 ]
40,485
export-specifier.lisp
psteeve_tsinco/src/nodes-elements/export-specifier.lisp
(defclass export-speficier (named-declaration) ((kind :initarg :kind :initform :export-specifier :reader kind) (parent :initarg :parent :initform (error "Must supply a value for \"parent\"") :reader parent) (property-name :initarg :property-name :reader property-name) (name :initarg :name :initform (error "Must supply a value for \"initform\"") :reader name)))
451
Common Lisp
.lisp
12
29.25
65
0.616438
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
e0c55a4ceb2caedf17fca3318538d41f4c43b810a07437ffce8e562a00efbe02
40,485
[ -1 ]
40,486
type-alias-declaration.lisp
psteeve_tsinco/src/nodes-elements/type-alias-declaration.lisp
(defclass type-alias-declaration (declaration-statement) ((kind :initarg :kind :initform :type-alias-declaration :reader kind) (name :initarg :name :initform (error "Must supply a value for \"name\"") :reader name) type-parameters (alias-type :initarg :type :initform (error "Must supply a value for \"type\"") :reader alias-type)))
410
Common Lisp
.lisp
11
29.272727
67
0.619048
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
d6433333e067c52a7375773b37e503cded8177f72eb268fcaaab4a3ff5ea0679
40,486
[ -1 ]
40,487
if-statement.lisp
psteeve_tsinco/src/nodes-elements/if-statement.lisp
(defclass if-statement (statement) ((kind :initarg :kind :initform :if-statement :reader kind) (expression :initarg :expression :initform (error "Must supply value for expression") :reader expression) (then-statement :initarg :then-statement :initform (error "Must supply value for then-statement") :reader then-statement) (else-statement :initarg :else-statement :reader else-statement)))
401
Common Lisp
.lisp
5
77
124
0.767677
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
eae345757d0dea6ca811754f2e380e19fa18a80358649999702bb8590de85673
40,487
[ -1 ]
40,488
module-declaration.lisp
psteeve_tsinco/src/nodes-elements/module-declaration.lisp
(defclass module-declaration (declaration-statement) ((kind :initarg :kind :initform :module-declaration :reader kind) (name :initarg :name :initform (error "Must supply a value for \"name\"") :reader name) (body :initarg :body :reader body))) (defmethod initialize-instance :after ((object module-declaration) &key) (with-slots (body name) object ;; (setf body (mapcar #'parse-simple-sexp (body object))) (setf name (mapcar #'parse-simple-sexp (name object)))))
530
Common Lisp
.lisp
13
34.846154
72
0.658915
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
65db1aa69f30913b44c5a2e06c35ad278fd77a36163c78b0afc7ec86f6da4a08
40,488
[ -1 ]
40,489
class-like-declaration-base.lisp
psteeve_tsinco/src/nodes-elements/class-like-declaration-base.lisp
(defclass class-like-declaration-base (named-declaration) ((kind :initarg :kind :initform :class-like-declaration-base :reader kind) (name :initarg :name :reader name) (type-parameters :initarg :type-parameters :reader type-parameters) (heritage-clauses :initarg :heritage-clauses :reader heritage-clauses) (members :initarg :members :initform (error "Must supply a value for \"members\"") :reader members)))
515
Common Lisp
.lisp
13
30.461538
67
0.629482
psteeve/tsinco
0
0
0
GPL-3.0
9/19/2024, 11:48:31 AM (Europe/Amsterdam)
b72c6b4cd83001dcc599d5b85cb4d1d7bfc4f6d5ac480f86e616f74404da30ce
40,489
[ -1 ]