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
18,137
roswell.map
jstoddard_roswell/roswell.map
;;; This is a -*- Lisp -*- file... (in-package #:roswell) ;;; Level 1: A 52x42 Map (defun level1-start () (setf (x-position *player*) 80) (setf (y-position *player*) 176)) (let ((level1 (make-instance 'level-map :map-width 52 :map-height 42 :bg-map (make-array '(52 42) :initial-element 1) :obstacle-map (make-array '(52 42) :initial-element -1) :object-map (make-array '(52 42) :initial-element -1) :load-function 'level1-start))) ;; put walls around the map (dotimes (i 52) (setf (aref (obstacle-map level1) i 0) 20) (setf (aref (obstacle-map level1) i 41) 20) (when (< i 42) (setf (aref (obstacle-map level1) 0 i) 20) (setf (aref (obstacle-map level1) 51 i) 20))) ;; stick in some random radiation warnings (dotimes (i 25) (setf (aref (bg-map level1) (random 52) (random 42)) 22)) ;; Some platforms toward the top (dotimes (i 5) (setf (aref (obstacle-map level1) (1+ i) 6) 20) (setf (aref (obstacle-map level1) (+ i 46) 6) 20)) ;; Big long platform (dotimes (i 40) (setf (aref (obstacle-map level1) (+ i 6) 10) 20)) ;; Full length of the map, with gap in the middle (dotimes (i 24) (setf (aref (obstacle-map level1) (+ i 1) 15) 20) (setf (aref (obstacle-map level1) (+ i 27) 15) 20)) ;; Three long platforms forming a zig-zag (dotimes (i 45) (setf (aref (obstacle-map level1) (+ i 6) 20) 20) (setf (aref (obstacle-map level1) (1+ i) 25) 20) (setf (aref (obstacle-map level1) (+ i 6) 30) 20)) ;; Another gap in the middle, this time a bit bigger (dotimes (i 20) (setf (aref (obstacle-map level1) (1+ i) 35) 20) (setf (aref (obstacle-map level1) (+ i 31) 35) 20)) ;; Add newly created level to the game. (add-level level1))
1,806
Common Lisp
.l
47
33.595745
61
0.611048
jstoddard/roswell
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7683ee814879294ad160ae78b1850c065b9c61d013d4a083ba8fcfdc5f7bfd96
18,137
[ -1 ]
18,139
projectiles.xcf
jstoddard_roswell/media/projectiles.xcf
gimp xcf file` BљBљ G gimp-commentCreated with GIMPgimp-image-grid(style solid) (fgcolor (color-rgba 0.000000 0.000000 0.000000 1.000000)) (bgcolor (color-rgba 1.000000 1.000000 1.000000 1.000000)) (xspacing 10.000000) (yspacing 10.000000) (spacing-unit inches) (xoffset 0.000000) (yoffset 0.000000) (offset-unit inches) ▓ `  New Layer      `` x§` ї1?;?;?;?;?;?;?;?8А? ?А? ?А? ?■ЄАА? ?чnЄАА???чKnЄА??8ЧKnЄ??;?;?;?;?;?;?;?І1┐;┐;┐;┐;┐;┐;┐;┐8А┐ ┐А┐ ┐А┐ ┐■ЄАА┐ ┐чnЄАА┐┐┐чKnЄА┐┐8ЧKnЄ┐┐;┐;┐;┐;┐;┐;┐;┐І1;;;;;;;8А А А ■ЄАА чnЄААчKnЄА8ЧKnЄ;;;;;;;І1ч `` :чѕээѕ:ч├  ├:ч└  └:чи  и:чи  и:чи  и:чи  и:чи  и:чи  ич ѕ├└ии§Ъ@чи  и§`э  ■┐чи  и§`э  ■┐чи  ич ѕ├└ии§Ъ@чи  и:чи  и:чи  и:чи  и:чи  и:чи  и:чи  и:чЪ  Ъ:ч@┐┐@іЇААС■АА§СА■ЄАА§nЄААЧKnЄААЩKnЄААГЇААС■АА§СА■ЄАА§nЄААЧKnЄААЩKnЄААГЇААС■АА§СА■ЄАА§nЄААЧKnЄААЩKnЄААГЇ ■  ■     ■  «0` Background      ░` ╚З` ▄У      0
1,792
Common Lisp
.l
13
136.923077
1,103
0.281461
jstoddard/roswell
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c9e049bf5ad83a766aee53b715baaab42bfe75783761c991bc6e9f9f58581a94
18,139
[ -1 ]
18,154
operators.lisp
marcoheisig_Leibniz/code/internals/operators.lisp
(in-package #:leibniz) ;;; Constants (define-operator +e+) (define-operator +i+) (define-operator +gamma+) (define-operator +phi+) (define-operator +pi+) ;;; Common Lisp Operators (define-operator = (number &rest more-numbers)) (define-operator /= (number &rest more-numbers)) (define-operator < (number &rest more-numbers)) (define-operator > (number &rest more-numbers)) (define-operator <= (number &rest more-numbers)) (define-operator >= (number &rest more-numbers)) (define-operator max (number &rest more-numbers)) (define-operator min (number &rest more-numbers)) (define-operator floor (number &optional divisor)) (define-operator ceiling (number &optional divisor)) (define-operator truncate (number &optional divisor)) (define-operator round (number &optional divisor)) (define-operator sin (number)) (define-operator cos (number)) (define-operator tan (number)) (define-operator asin (number)) (define-operator acos (number)) (define-operator atan (number1 &optional number2)) (define-operator sinh (number)) (define-operator cosh (number)) (define-operator tanh (number)) (define-operator asinh (number)) (define-operator acosh (number)) (define-operator atanh (number)) (define-operator * (&rest numbers)) (define-operator + (&rest numbers)) (define-operator - (number &rest more-numbers)) (define-operator / (number &rest more-numbers)) (define-operator 1+ (number)) (define-operator 1- (number)) (define-operator abs (number)) (define-operator evenp (number)) (define-operator oddp (number)) (define-operator exp (number)) (define-operator expt (base power)) (define-operator gcd (&rest integers)) (define-operator lcm (&rest integers)) (define-operator log (number &optional base)) (define-operator mod (number divisor)) (define-operator rem (number divisor)) (define-operator signum (number)) (define-operator sqrt (number)) (define-operator isqrt (natural-number)) (define-operator cis (radians)) (define-operator conjugate (number)) (define-operator phase (number)) (define-operator realpart (number)) (define-operator imagpart (number)) (define-operator ash (integer count)) (define-operator integer-length (integer)) ;;; Other Operators (define-operator free-variables (expression)) (define-operator integrate (expression variable &optional a b)) (define-operator diff (expression &optional variable)) (define-operator solve (expression variable)) (define-operator factor (expression)) (define-operator expand (expression)) ;;; Metadata (defparameter *cl-operators* (loop for operator being the hash-keys of leibniz-internals:*operators* when (find-symbol (symbol-name operator) "CL") collect operator) "A list with the names of all Leibniz operators that have the same name as a standard Common Lisp symbol. Useful for shadowing those symbols within package definitions.")
2,888
Common Lisp
.lisp
73
37.30137
78
0.769734
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b9455f923a7cdfdbd204e49ff93d168b435c6176969edf0fe5d7e8d6055c6979
18,154
[ -1 ]
18,155
operator.lisp
marcoheisig_Leibniz/code/internals/operator.lisp
(in-package #:leibniz-internals) (defclass operator () ((%name :initform (alexandria:required-argument :name) :initarg :name :reader operator-name :type (and symbol (not null))) (%min-arguments :initform (alexandria:required-argument :min-arguments) :initarg :min-arguments :reader operator-min-arguments :type (integer 0 (#.call-arguments-limit))) (%max-arguments :initform (alexandria:required-argument :max-arguments) :initarg :max-arguments :reader operator-max-arguments :type (integer 0 (#.call-arguments-limit))))) (defmethod print-object ((operator operator) stream) (format stream "~@<#<~;~S ~_~@{~S ~:_~S~^ ~_~}~;>~:>" (class-name (class-of operator)) :name (operator-name operator) :min-arguments (operator-min-arguments operator) :max-arguments (operator-max-arguments operator))) (defmethod operatorp ((object t)) nil) (defmethod operatorp ((operator operator)) t) (defparameter *operators* (make-hash-table :test #'eq)) (defmethod reinitialize-instance :before ((operator operator) &key &allow-other-keys) (remhash (operator-name operator) *operators*)) (defmethod initialize-instance :after ((operator operator) &key &allow-other-keys) (setf (gethash (operator-name operator) *operators*) operator)) (defun ensure-operator (&rest arguments &key name &allow-other-keys) (let ((operator (gethash name *operators*))) (if (not operator) (apply #'make-instance 'operator arguments) (apply #'reinitialize-instance operator arguments)))) (defun find-operator (name &optional (errorp t)) (or (gethash name *operators*) (and errorp (error "~@<There is no operator named ~S.~:@>" name)))) (defun argcheck (operator n-arguments) "Check whether it is permissible to call the operator with the supplied number of arguments." (with-accessors ((name operator-name) (min-arguments operator-min-arguments) (max-arguments operator-max-arguments)) operator (unless (<= min-arguments n-arguments) (error "~@<Only ~R arguments supplied to the operator ~S~ that expects ~:[at least ~]~R arguments.~:@>" n-arguments name (= min-arguments max-arguments) min-arguments)) (unless (<= n-arguments max-arguments) (error "~@<~:(~R~) arguments supplied to the operator ~S~ that expects ~:[at most ~]~R arguments.~:@>" n-arguments name (= min-arguments max-arguments) max-arguments)))) (defmacro define-operator (name &optional (lambda-list '() lambda-list-supplied-p)) (multiple-value-bind (required optional rest keyword aak aux keyp) (alexandria:parse-ordinary-lambda-list lambda-list) (declare (ignore keyword)) (unless (typep name '(and symbol (not null))) (error "~@<Not a valid operator name: ~A.~:@>" name)) (unless (not aux) (error "~@<Operator lambda lists mustn't have &aux parameters.~:@>")) (unless (not keyp) (error "~@<Operator lambda lists mustn't have &key parameters.~:@>")) (let* ((n-required (length required)) (n-optional (length optional)) (min-arguments n-required) (max-arguments (if (or rest aak) (1- call-arguments-limit) (+ n-required n-optional))) (optional (loop for (name init suppliedp) in optional collect (list name init (or suppliedp (gensym (concatenate 'string (symbol-name name) "-SUPPLIED-P")))))) (lambda-list `(,@required ,@`(&optional ,@optional) ,@(when rest `(&rest ,rest)))) (arguments (alexandria:with-gensyms (head tail collect x) `(let* ((,head (cons nil nil)) (,tail ,head)) (flet ((,collect (,x) (setf (cdr ,tail) (cons ,x nil)) (setf ,tail (cdr ,tail)))) ,@(loop for var in required collect `(,collect ,var)) ,@(loop for (var nil suppliedp) in optional collect `(when ,suppliedp (,collect ,var))) ,@(when rest `((mapcar #',collect ,rest))) (cdr ,head)))))) (alexandria:once-only ((operator `(ensure-operator :name ',name :min-arguments ,min-arguments :max-arguments ,max-arguments))) (if (not lambda-list-supplied-p) (alexandria:with-gensyms (fn-name) `(progn (defun ,fn-name () (apply-noun ,operator '())) (define-symbol-macro ,name (,fn-name)))) `(progn (defun ,name ,lambda-list (apply-verb ,operator ,arguments)) (defvar ,name (lambda ,lambda-list (apply-noun ,operator ,arguments))))))))) (defmacro define-noun (client-spec operator-spec &body clauses) (multiple-value-bind (client client-specializer) (canonicalize-client-spec client-spec) (multiple-value-bind (operator operator-specializer) (canonicalize-operator-spec operator-spec) (alexandria:with-gensyms (arguments) `(defmethod client-apply-noun-internal ((,client ,client-specializer) (,operator ,operator-specializer) (,arguments list)) (declare (ignorable ,client ,operator)) (trivia:match ,arguments ,@clauses (_ (call-next-method)))))))) (defmacro define-verb (client-spec operator-spec &body clauses) (multiple-value-bind (client client-specializer) (canonicalize-client-spec client-spec) (multiple-value-bind (operator operator-specializer) (canonicalize-operator-spec operator-spec) (alexandria:with-gensyms (arguments) `(defmethod client-apply-verb-internal ((,client ,client-specializer) (,operator ,operator-specializer) (,arguments list)) (declare (ignorable ,client ,operator)) (trivia:match ,arguments ,@clauses (_ (call-next-method)))))))) (defun canonicalize-client-spec (client-spec) (trivia:match client-spec ((type symbol) (values (gensym "CLIENT") client-spec)) ((list (and variable (type symbol)) specializer) (values variable specializer)) (_ (error "~@<Invalid client spec: ~S~:@>" client-spec)))) (defun canonicalize-operator-spec (operator-spec) (trivia:match operator-spec ((type symbol) (values (gensym "OPERATOR") `(eql (find-operator ',operator-spec)))) ((list (and variable (type symbol)) specializer) (values variable specializer)) (_ (error "~@<Invalid operator spec: ~S~:@>" operator-spec))))
7,130
Common Lisp
.lisp
163
33.496933
91
0.589209
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
aa0eb160af8122d3de3b78214fa054c6cad09191ccf88ac02c91593e90fefddf
18,155
[ -1 ]
18,156
expression.lisp
marcoheisig_Leibniz/code/internals/expression.lisp
(in-package #:leibniz-internals) ;;; Common Lisp symbols and numbers are always a valid external representation ;;; of an expression, so that the results of many verbs can be passed directly ;;; to Common Lisp functions. (defmethod expressionp ((number number)) t) (defmethod atomic-expression-p ((number number)) t) (defmethod compound-expression-p ((number number)) nil) (defmethod expressionp ((symbol symbol)) t) (defmethod atomic-expression-p ((symbol symbol)) t) (defmethod compound-expression-p ((symbol symbol)) nil) ;;; The list of arguments of a compound expression can be derived from other, ;;; more specific methods. (defmethod compound-expression-arguments ((object t)) (loop for position below (compound-expression-number-of-arguments object) collect (compound-expression-argument object position))) ;;; Argument checking. (defmethod client-apply-noun :before ((client t) (operator operator) (arguments list)) (argcheck operator (length arguments))) (defmethod client-apply-verb :before ((client t) (operator operator) (arguments list)) (argcheck operator (length arguments))) ;;; Switch from external to internal representation. (defmethod client-apply-noun ((client t) (operator operator) (arguments list)) (client-external-representation client (client-apply-noun-internal client operator (mapcar (lambda (argument) (client-internal-representation client argument)) arguments)))) (defmethod client-apply-verb ((client t) (operator operator) (arguments list)) (client-external-representation client (client-apply-verb-internal client operator (mapcar (lambda (argument) (client-internal-representation client argument)) arguments)))) ;;; Verbs have the fallback solution of simply applying the noun. (defmethod client-apply-verb-internal ((client t) (operator operator) (arguments list)) (client-apply-noun-internal client operator arguments)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Functions (defvar *client*) (defun internal-representation (object) (client-internal-representation *client* object)) (defun external-representation (object) (client-external-representation *client* object)) (defun apply-noun (operator arguments) (client-apply-noun *client* operator arguments)) (defun apply-verb (operator arguments) (client-apply-verb *client* operator arguments))
2,563
Common Lisp
.lisp
84
26.77381
79
0.714693
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
eaaa4c29999a45b23d6c5fc2c6b884a0a576ad8958a1f0cb260690a74c9d805d
18,156
[ -1 ]
18,157
generic-functions.lisp
marcoheisig_Leibniz/code/internals/generic-functions.lisp
(in-package #:leibniz-internals) ;;; Operators (defgeneric operatorp (object)) (defgeneric operator-min-arguments (object)) (defgeneric operator-max-arguments (object)) ;;; Expressions (defgeneric expressionp (object)) (defgeneric atomic-expression-p (object)) (defgeneric compound-expression-p (object)) (defgeneric compound-expression-operator (expression)) (defgeneric compound-expression-argument (expression position)) (defgeneric compound-expression-number-of-arguments (expression)) (defgeneric compound-expression-arguments (expression)) ;;; Client Functions (defgeneric client-internal-representation (client object) (:documentation "Returns an object that is the internal representation of CLIENT for the supplied external representation, which can be one of the following: - A Common Lisp number, which denotes itself. - A Common Lisp symbol, which denotes a variable of the same name. - The external representation of any possible client.")) (defgeneric client-external-representation (client object) (:documentation "Returns an object that is the external representation of CLIENT for the supplied internal representation.")) (defgeneric client-apply-noun (client operator arguments) (:documentation "Returns the external representation of CLIENT for a noun clause with the supplied OPERATOR and the supplied list of external representations of any client in ARGUMENTS.")) (defgeneric client-apply-verb (client operator arguments) (:documentation "Returns the external representation of CLIENT for a verb clause with the supplied OPERATOR and the supplied list of external representations of any client in ARGUMENTS.")) (defgeneric client-apply-noun-internal (client operator arguments) (:documentation "Returns the internal representation of CLIENT for a noun clause with the supplied OPERATOR and the supplied list of internal representations of that client in ARGUMENTS.")) (defgeneric client-apply-verb-internal (client operator arguments) (:documentation "Returns the internal representation of CLIENT for a verb clause with the supplied OPERATOR and the supplied list of internal representations of that client in ARGUMENTS."))
2,199
Common Lisp
.lisp
45
46.711111
76
0.819418
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b7151c2c7eafdf75d59bcfa152b7defceaeb6344fc87145a2a4a141488d22995
18,157
[ -1 ]
18,158
packages.lisp
marcoheisig_Leibniz/code/internals/packages.lisp
(in-package #:common-lisp-user) (progn (defpackage #:leibniz-internals (:use #:common-lisp) (:export #:operator #:operatorp #:operator-min-arguments #:operator-max-arguments #:expressionp #:atomic-expression-p #:compound-expression-p #:compound-expression-operator #:compound-expression-argument #:compound-expression-number-of-arguments #:compound-expression-arguments #:internal-representation #:external-representation #:apply-noun #:apply-verb #:client-internal-representation #:client-external-representation #:client-apply-noun #:client-apply-verb #:client-apply-noun-internal #:client-apply-verb-internal #:*client* #:*operators* #:ensure-operator #:find-operator #:define-operator #:define-noun #:define-verb)) (defpackage #:leibniz ;; Operators that shadow symbols in the CL package. (:export . #1= (#:= #:/= #:< #:> #:<= #:>= #:max #:min #:floor #:ceiling #:truncate #:round #:sin #:cos #:tan #:asin #:acos #:atan #:sinh #:cosh #:tanh #:asinh #:acosh #:atanh #:* #:+ #:- #:/ #:1+ #:1- #:abs #:evenp #:oddp #:exp #:expt #:gcd #:lcm #:log #:mod #:rem #:signum #:sqrt #:isqrt #:cis #:conjugate #:phase #:realpart #:imagpart #:ash #:integer-length)) ;; Other Operators (:export #:+e+ #:+i+ #:+gamma+ #:+phi+ #:+pi+ #:free-variables #:integrate #:diff #:solve #:factor #:expand) (:export ;; Metadata #:*cl-operators*) (:import-from #:common-lisp . #.(loop for sym being the external-symbols of "CL" unless (member sym '#1# :test #'string=) collect sym)) (:import-from #:leibniz-internals #:define-operator)) (defpackage #:leibniz-user (:use #:leibniz #:leibniz-internals) (:import-from #:common-lisp . #.(loop for sym being the external-symbols of "CL" unless (member sym '#1# :test #'string=) collect sym))))
2,363
Common Lisp
.lisp
118
13.533898
57
0.524532
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7301e0e792c264986f3c24530bb6fb4f90fdc935d0eaba739e50675871a1a081
18,158
[ -1 ]
18,159
operators.lisp
marcoheisig_Leibniz/code/maxima/operators.lisp
(in-package #:leibniz-maxima) ;;; Constants (define-noun maxima leibniz:+e+ ((list) 'maxima::$%e)) (define-noun maxima leibniz:+i+ ((list) 'maxima::$%i)) (define-noun maxima leibniz:+gamma+ ((list) 'maxima::$%gamma)) (define-noun maxima leibniz:+phi+ ((list) 'maxima::$%phi)) (define-noun maxima leibniz:+pi+ ((list) 'maxima::$%pi)) ;;; Common Lisp Operators (macrolet ((def (leibniz-operator maxima-operator) `(define-noun maxima ,leibniz-operator ((list _) t) ((list number1 number2) `((,',maxima-operator) ,number1 ,number2)) ((list* number more-numbers) `((maxima::$mand) ,@(loop for a = number then b for b in more-numbers collect `((,',maxima-operator) ,a ,b))))))) (def leibniz:= maxima::mequal) (def leibniz:< maxima::mlessp) (def leibniz:> maxima::mgreaterp) (def leibniz:<= maxima::mleqp) (def leibniz:>= maxima::mgeqp)) (defun map-pairs (fn list) (loop for sublist on list for a = (first sublist) do (loop for b in (rest sublist) do (funcall fn a b)))) (define-noun maxima leibniz:/= ((list _) t) ((list number1 number2) `((maxima::mnotequal) ,number1 ,number2)) ((list* numbers) (let ((booleans '())) (map-pairs (lambda (a b) (push `((maxima::mnotequal) ,a ,b) booleans)) numbers) `((maxima::mand) ,@booleans)))) ;; TODO min, max ;; TODO floor, ceiling, truncate, round (macrolet ((def (leibniz-operator maxima-operator) `(progn (define-noun maxima ,leibniz-operator ((list number) `((,',maxima-operator) ,number))) (define-verb maxima ,leibniz-operator ((list number) (,maxima-operator number)))))) (def leibniz:sin maxima::$sin) (def leibniz:cos maxima::$cos) (def leibniz:tan maxima::$tan) (def leibniz:asin maxima::$asin) (def leibniz:acos maxima::$acos) (def leibniz:sinh maxima::$sinh) (def leibniz:cosh maxima::$cosh) (def leibniz:tanh maxima::$tanh) (def leibniz:asinh maxima::$asinh) (def leibniz:acosh maxima::$acosh) (def leibniz:atanh maxima::$atanh)) (define-noun maxima leibniz:atan ((list number) `((maxima::$atan) ,number)) ((list number1 number2) `((maxima::$atan2) ,number1 ,number2))) (define-verb maxima leibniz:atan ((list number) (maxima::$atan number))) (define-noun maxima leibniz:* ((list) 1) ((list number) number) ((list* numbers) `((maxima::mtimes) ,@numbers))) (define-noun maxima leibniz:+ ((list) 0) ((list number) number) ((list* numbers) `((maxima::mplus) ,@numbers))) (define-noun maxima leibniz:- ((list number) `((maxima::mminus) ,number)) ((list* number more-numbers) `((maxima::mplus) ,number ,@(mapcar (lambda (x) `((maxima::mminus) ,x)) more-numbers)))) (define-noun maxima leibniz:/ ((list number) `((maxima::mquotient) 1 ,number)) ((list* numbers) (reduce (lambda (a b) `((maxima::mquotient) ,a ,b)) numbers))) (define-noun maxima leibniz:1+ ((list number) `((maxima::mplus) ,number 1))) (define-noun maxima leibniz:1- ((list number) `((maxima::mplus) ,number -1))) (define-noun maxima leibniz:abs ((list number) `((maxima::$abs) ,number))) (define-verb maxima leibniz:abs ((list number) (maxima::$abs number))) ;; TODO evenp, oddp (define-noun maxima leibniz:exp ((list number) `((maxima::$exp) ,number))) (define-verb maxima leibniz:exp ((list number) (maxima::$exp number))) (define-noun maxima leibniz:expt ((list base power) `((maxima::mexpt) ,base ,power))) ;;; Other Operators (define-noun maxima leibniz:free-variables ((list expression) `((maxima::$listofvars) ,expression))) (define-verb maxima leibniz:free-variables ((list expression) (maxima::$listofvars expression))) (define-noun maxima leibniz:integrate ((list* arguments) `((maxima::$integrate) ,@arguments))) (define-verb maxima leibniz:integrate ((list* arguments) (apply #'maxima::$integrate arguments))) (define-noun maxima leibniz:diff ((list* arguments) `((maxima::$diff) ,@arguments))) (define-verb maxima leibniz:diff ((list* arguments) (apply #'maxima::$diff arguments))) (define-noun maxima leibniz:solve ((list* arguments) `((maxima::$solve) ,@arguments))) (define-verb maxima leibniz:solve ((list* arguments) (apply #'maxima::$solve arguments))) (define-noun maxima leibniz:factor ((list expression) `((maxima::$factor) ,expression))) (define-verb maxima leibniz:factor ((list expression) (maxima::$factor expression))) (define-noun maxima leibniz:expand ((list expression) `((maxima::$expand) ,expression))) (define-verb maxima leibniz:expand ((list expression) (maxima::$expand expression)))
4,953
Common Lisp
.lisp
158
26.386076
66
0.63428
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d0f125061dd0d85e12ea9401f3055b6c485c616a42a1906d13208da45387a45b
18,159
[ -1 ]
18,160
classes.lisp
marcoheisig_Leibniz/code/maxima/classes.lisp
(in-package #:leibniz-maxima) (defclass maxima () ()) (defclass expression () ((%form :initform (alexandria:required-argument :form) :initarg :form :reader expression-form))) (defun make-expression (form) (make-instance 'expression :form form))
270
Common Lisp
.lisp
11
21.272727
50
0.703125
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
5f784b0a1c8f1964d3845e94c9556a741b3b7155760d902a37788ccfbb18dd56
18,160
[ -1 ]
18,161
methods.lisp
marcoheisig_Leibniz/code/maxima/methods.lisp
(in-package #:leibniz-maxima) (defmethod print-object ((expression expression) stream) (print-unreadable-object (expression stream :type t) (maxima::mgrind (expression-form expression) stream))) (defmethod expressionp ((expression expression)) t) (defmethod atomic-expression-p ((expression expression)) nil) (defmethod compound-expression-p ((expression expression)) t) (defmethod compound-expression-operator ((expression expression)) (maxima::$part (expression-form expression) 0)) (defmethod compound-expression-argument ((expression expression) (position integer)) (make-expression (maxima::$part (expression-form expression) (1+ position)))) (defmethod compound-expression-number-of-arguments ((expression expression)) (maxima::$length (expression-form expression))) ;;; Internal Representation (defmethod client-internal-representation ((maxima maxima) (expression expression)) (expression-form expression)) (defmethod client-internal-representation ((maxima maxima) (integer integer)) integer) (defmethod client-internal-representation ((maxima maxima) (rational rational)) `((maxima::mquotient) ,(client-internal-representation maxima (numerator rational)) ,(client-internal-representation maxima (denominator rational)))) (defmethod client-internal-representation ((maxima maxima) (complex complex)) `((maxima::mplus) ,(client-internal-representation maxima (realpart complex)) ((maxima::mtimes) maxima::$%i ,(client-internal-representation maxima (imagpart complex))))) (defmethod client-internal-representation ((maxima maxima) (symbol symbol)) (let ((name (concatenate 'string "$" (symbol-name symbol))) (package (symbol-package symbol))) (assert package) (intern name package))) ;;; External Representation (defmethod client-external-representation ((maxima maxima) (form t)) (maxima-external-representation form)) (defun maxima-external-representation (form) (trivia:match form ((list* (list 'maxima::mlist) subforms) (mapcar #'maxima-external-representation subforms)) ;; TODO complex numbers ((list (list 'maxima::mquotient) (and a (type integer)) (and b (type integer))) (/ a b)) ((type symbol) (intern (subseq (symbol-name form) 1) (symbol-package form))) ((type number) form) (_ (make-expression form)))) ;;; Verbs and Nouns. ;;; Maxima verbs are obtained by evaluating the corresponding nouns. (defmethod client-apply-verb-internal ((maxima maxima) (operator operator) (arguments list)) (maxima::meval (client-apply-noun-internal maxima operator arguments)))
2,761
Common Lisp
.lisp
83
28.879518
69
0.718421
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6a24b415c13962e1c0158452cabcc384f4b48d2eae49fe7058bd7c3f1d519222
18,161
[ -1 ]
18,162
packages.lisp
marcoheisig_Leibniz/code/maxima/packages.lisp
(cl:in-package #:common-lisp-user) (defpackage #:leibniz-maxima (:use #:closer-common-lisp #:leibniz-internals) (:export #:maxima #:expression)) ;; I have no idea why the variable %e-val isn't bound right away, but only ;; during Maxima's (initialize-runtime-globals). Many Maxima functions crash ;; without this definition. We don't want to call that initialization function ;; ourselves, because it also clobbers many standard CL variables like ;; *print-length*, so the somewhat awkward solution is to simply define this ;; one variable ourselves. (defvar maxima::%e-val (maxima::mget 'maxima::$%e 'maxima::$numer))
633
Common Lisp
.lisp
13
46.769231
79
0.749191
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
11fa079fafbf790ab7f3498df1aee37683a9973e805cc40442fa50e3ce0a4385
18,162
[ -1 ]
18,163
leibniz-common-lisp.asd
marcoheisig_Leibniz/code/common-lisp/leibniz-common-lisp.asd
(defsystem "leibniz-common-lisp" :author "Marco Heisig <[email protected]>" :license "AGPLv3" :depends-on ("alexandria" "closer-mop") :serial t :components ((:file "packages")))
199
Common Lisp
.lisp
9
19
46
0.68617
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2637eb9653efebb586fa8be11762775a236307b9d892de4e4f7c0885349db52d
18,163
[ -1 ]
18,164
leibniz.asd
marcoheisig_Leibniz/code/leibniz.asd
(defsystem "leibniz" :author "Marco Heisig <[email protected]>" :license "AGPLv3" :depends-on ("leibniz-internals" "leibniz-common-lisp" "leibniz-maxima") :components ((:file "leibniz")))
210
Common Lisp
.asd
9
20.111111
46
0.693467
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ec291b030beb9750cd93c26ac1508478cfe6c9e563996d7e2e919139083937eb
18,164
[ -1 ]
18,165
leibniz-internals.asd
marcoheisig_Leibniz/code/internals/leibniz-internals.asd
(defsystem "leibniz-internals" :author "Marco Heisig <[email protected]>" :license "AGPLv3" :depends-on ("alexandria" "trivia") :serial t :components ((:file "packages") (:file "generic-functions") (:file "operator") (:file "expression") (:file "operators")))
293
Common Lisp
.asd
13
19.153846
46
0.661871
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
1b81ecc73956b862f92cfb1e9e6a19e06daddbfd98da1190fc8021f554644560
18,165
[ -1 ]
18,166
leibniz-maxima.asd
marcoheisig_Leibniz/code/maxima/leibniz-maxima.asd
(defsystem "leibniz-maxima" :author "Marco Heisig <[email protected]>" :license "AGPLv3" :depends-on ("alexandria" "closer-mop" "maxima" "trivia") :serial t :components ((:file "packages") (:file "classes") (:file "methods") (:file "operators")))
283
Common Lisp
.asd
14
16.785714
46
0.644195
marcoheisig/Leibniz
3
0
0
AGPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
86eff8e27c05ebd24548de48f8838914ff68558622ec8c40579068e960fb4747
18,166
[ -1 ]
18,194
assert-p-test.lisp
noloop_assert-p/test/assert-p-test.lisp
(defpackage #:noloop.assert-p-test (:use #:common-lisp #:simplet #:assert-p) (:nicknames #:assert-p-test) (:import-from #:assert-p #:assertion-error-check)) (in-package #:noloop.assert-p-test) (defun test-t-p () (let ((actual t)) (assertion-error-check (eq (t-p actual) nil)))) (defun test-not-t-p () (let ((actual nil)) (assertion-error-check (eq (not-t-p actual) nil)))) (defun test-zero-p () (let ((actual 0)) (assertion-error-check (eq (zero-p actual) nil)))) (defun test-not-zero-p () (let ((actual nil)) (assertion-error-check (eq (not-zero-p actual) nil)))) (defun test-nil-p () (let ((actual nil)) (assertion-error-check (eq (nil-p actual) nil)))) (defun test-not-nil-p () (let ((actual t)) (assertion-error-check (eq (not-nil-p actual) nil)))) (defun test-null-p () (let ((actual nil)) (assertion-error-check (eq (null-p actual) nil)))) (defun test-not-null-p () (let ((actual t)) (assertion-error-check (eq (not-null-p actual) nil)))) (defun test-eq-p () (let ((actual t) (expected t)) (assertion-error-check (eq (eq-p actual expected) nil)))) (defun test-not-eq-p () (let ((actual 3) (expected t)) (assertion-error-check (eq (not-eq-p actual expected) nil)))) (defun test-eql-p () (let ((actual t) (expected t)) (assertion-error-check (eq (eql-p actual expected) nil)))) (defun test-not-eql-p () (let ((actual 3) (expected t)) (assertion-error-check (eq (not-eql-p actual expected) nil)))) (defun test-equal-p () (let ((actual t) (expected t)) (assertion-error-check (eq (equal-p actual expected) nil)))) (defun test-not-equal-p () (let ((actual 3) (expected t)) (assertion-error-check (eq (not-equal-p actual expected) nil)))) (defun test-equalp-p () (let ((actual t) (expected t)) (assertion-error-check (eq (equalp-p actual expected) nil)))) (defun test-not-equalp-p () (let ((actual 3) (expected t)) (assertion-error-check (eq (not-equalp-p actual expected) nil)))) (defun test-typep-p () (let ((actual 1) (expected 'integer)) (assertion-error-check (eq (typep-p actual expected) nil)))) (defun test-not-typep-p () (let ((actual "stg") (expected 'integer)) (assertion-error-check (eq (not-typep-p actual expected) nil)))) (defun test-values-p () (let ((actual '("i" "i" "i")) (expected "i")) (assertion-error-check (eq (values-p 'string= actual expected) nil)))) (defun test-not-values-p () (let ((actual '(1 1 1)) (expected 2)) (assertion-error-check (eq (not-values-p '= actual expected) nil)))) (defun test-error-p () (assertion-error-check (eq (error-p #'(lambda () (error "Something"))) nil))) (defun test-not-error-p () (assertion-error-check (eq (not-error-p #'(lambda () ())) nil))) (defun test-condition-error-p () (assertion-error-check (eq nil (condition-error-p #'(lambda () (error 'division-by-zero)) division-by-zero)))) (defun test-not-condition-error-p () (assertion-error-check (eq nil (not-condition-error-p #'(lambda () (error "Something")) division-by-zero)))) (defun test-custom-p () (let ((actual '(1 2 3)) (expected '(1 2))) (assertion-error-check (eq nil (custom-p (every #'= actual expected) actual expected "every ="))))) (suite "Suite assert-p" (test "Test t-p" #'test-t-p) (test "Test not-t-p" #'test-not-t-p) (test "Test zero-p" #'test-zero-p) (test "Test not-zero-p" #'test-not-zero-p) (test "Test nil-p" #'test-nil-p) (test "Test not-nil-p" #'test-not-nil-p) (test "Test null-p" #'test-null-p) (test "Test not-null-p" #'test-not-null-p) (test "Test eq-p" #'test-eq-p) (test "Test not-eq-p" #'test-not-eq-p) (test "Test eql-p" #'test-eql-p) (test "Test not-eql-p" #'test-not-eql-p) (test "Test equal-p" #'test-equal-p) (test "Test not-equal-p" #'test-not-equal-p) (test "Test equalp-p" #'test-equalp-p) (test "Test not-equalp-p" #'test-not-equalp-p) (test "Test typep-p" #'test-typep-p) (test "Test not-typep-p" #'test-not-typep-p) (test "Test values-p" #'test-values-p) (test "Test not-values-p" #'test-not-values-p) (test "Test error-p" #'test-error-p) (test "Test not-error-p" #'test-not-error-p) (test "Test error-p" #'test-error-p) (test "Test condition-error-p" #'test-condition-error-p) (test "Test not-condition-error-p" #'test-not-condition-error-p) (test "Test custom-p" #'test-custom-p))
4,864
Common Lisp
.lisp
151
26.443709
71
0.586641
noloop/assert-p
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
38c2a8571185df8a16b83584077058fe1bb52afd66c2f22d593347baf9a8e475
18,194
[ -1 ]
18,195
package.lisp
noloop_assert-p/src/package.lisp
(defpackage #:noloop.assert-p (:use #:common-lisp) (:nicknames #:assert-p) (:import-from #:assertion-error #:assertion-error #:get-stack-trace #:assertion-error-actual #:assertion-error-expected #:assertion-error-message #:assertion-error-result #:assertion-error-stack) (:export #:t-p #:not-t-p #:zero-p #:not-zero-p #:nil-p #:not-nil-p #:null-p #:not-null-p #:eq-p #:not-eq-p #:eql-p #:not-eql-p #:equal-p #:not-equal-p #:equalp-p #:not-equalp-p #:typep-p #:not-typep-p #:values-p #:not-values-p #:error-p #:not-error-p #:condition-error-p #:not-condition-error-p #:custom-p))
956
Common Lisp
.lisp
36
15.083333
42
0.428261
noloop/assert-p
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9568f28e884386fbd8721921be4a457ce742dbe606a87d258f777c0509895076
18,195
[ -1 ]
18,196
assert-p.lisp
noloop_assert-p/src/assert-p.lisp
(in-package #:noloop.assert-p) (defun t-p (actual) "Check actual eq t" (assertion (eq t actual) actual t 'eq)) (defun not-t-p (actual) "Check actual not eq t" (assertion (not (eq t actual)) actual t 'not-eq)) (defun zero-p (actual) "Check actual eq 0" (assertion (eq 0 actual) actual 0 'eq)) (defun not-zero-p (actual) "Check actual not eq 0" (assertion (not (eq 0 actual)) actual 0 'not-eq)) (defun nil-p (actual) "Check actual eq nil" (assertion (eq nil actual) actual nil 'eq)) (defun not-nil-p (actual) "Check actual not eq nil" (assertion (not (eq nil actual)) actual nil 'not-eq)) (defun null-p (actual) "Check null actual. Equivalent to (null actual)" (assertion (null actual) actual nil 'null)) (defun not-null-p (actual) "Check not null actual. Equivalent to (not (null actual))" (assertion (not (null actual)) actual nil 'not-null)) (defun eq-p (actual expected) "Check actual eq expected" (assertion (eq actual expected) actual expected 'eq)) (defun not-eq-p (actual expected) "Check actual not eq expected" (assertion (not (eq actual expected)) actual expected 'not-eq)) (defun eql-p (actual expected) "Check actual eql expected" (assertion (eql actual expected) actual expected 'eql)) (defun not-eql-p (actual expected) "Check actual not eql expected" (assertion (not (eql actual expected)) actual expected 'not-eql)) (defun equal-p (actual expected) "Check actual equal expected" (assertion (equal actual expected) actual expected 'equal)) (defun not-equal-p (actual expected) "Check actual not equal expected" (assertion (not (equal actual expected)) actual expected 'not-equal)) (defun equalp-p (actual expected) "Check actual equalp expected" (assertion (equalp actual expected) actual expected 'equalp)) (defun not-equalp-p (actual expected) "Check actual not equalp expected" (assertion (not (equalp actual expected)) actual expected 'not-equalp)) (defun typep-p (actual expected) "Check actual typep expected" (assertion (typep actual expected) actual expected 'typep)) (defun not-typep-p (actual expected) "Check actual not typep expected" (assertion (not (typep actual expected)) actual expected 'not-typep)) (defun values-p (predicate actual expected) "Check actual every predicate expected. Predicate is a symbol of function, actual is a list, and expected an atom. Example: (values-p '= '(t t t) t) It's similar to (every #'(lambda (i) (= t i)) '(t t t))" (assertion-values 'every #'(lambda (i) (funcall (symbol-function predicate) expected i)) actual expected (concatenate 'string "every" (write-to-string predicate)))) (defun not-values-p (predicate actual expected) "Check actual every not predicate expected. Predicate is a symbol of function, actual is a list, and expected an atom. Example: (values-p '= '(t t t) t) It's similar to (every #'(lambda (i) (not (= t i))) '(t t t))" (assertion-values 'every #'(lambda (i) (not (funcall (symbol-function predicate) expected i))) actual expected (concatenate 'string "every" (write-to-string predicate)))) (defun error-p (fn) "Check if fn throw an error." (assertion (error-check fn) fn 'error 'catch)) (defun not-error-p (fn) "Check if fn not throw an error." (assertion (not (error-check fn)) fn 'error 'catch)) (defmacro condition-error-p (fn condition) "Check if fn throw an specified condition error." `(assertion (condition-error-check ,fn ,condition) 'fn 'error 'catch)) (defmacro not-condition-error-p (fn condition) "Check if fn not throw an specified condition error." `(assertion (not (condition-error-check ,fn ,condition)) 'fn 'error 'catch)) (defun custom-p (test-result actual expected operator) "Custom check for special cases. Where test-result is a form that returns t or nil, actual is value actual used in test-result, expected is value expected used in test-result, operator is operator used in test-result. Return t when test-result is t, and throw assertion-error when test-result is nil." (assertion test-result actual expected operator)) (defun assertion (result actual expected operator) "When result is t return t. When result is nil throw assertion-error. One assertion need result (t or nil), one object actual, one object expected, and one operator (string or symbol). Assertion-error also loading one message of error (built with actual, expected and operator) and the stack trace of error throw moment." (if result t (error 'assertion-error :assertion-error-message (error-message actual expected operator) :assertion-error-result result :assertion-error-actual actual :assertion-error-expected expected :assertion-error-stack (get-stack-trace)))) (defun error-message (actual expected operator) (format nil "~a ~a ~a~%~%~a" (type-of actual) (write-to-string operator) (type-of expected) (format nil "Actual:~%~%~a~%~%Expected:~%~%~a" (write-to-string actual) (write-to-string expected))))
5,118
Common Lisp
.lisp
117
40
323
0.716067
noloop/assert-p
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d7a29fd525a2ebfdda576b7b27d471cc78a667f5cf949636227844024bcb2725
18,196
[ -1 ]
18,197
macros.lisp
noloop_assert-p/src/macros.lisp
(in-package #:noloop.assert-p) (defmacro with-gensyms (vars &body body) `(let ,(loop for v in vars collect `(,v (gensym))) ,@body)) (defmacro once-only ((&rest names) &body body) (let ((gensyms (loop for n in names collect (gensym)))) `(with-gensyms (,@gensyms) `(let (,,@(loop for g in gensyms for n in names collect ``(,,g ,,n))) ,(let (,@(loop for n in names for g in gensyms collect `(,n ,g))) ,@body))))) (defmacro assertion-error-check (test-form) (with-gensyms (result) `(let ((,result t)) (handler-case ,test-form (assertion-error (c) (declare (ignore c)) (setf ,result nil))) ,result))) (defmacro assertion-values (test-fn predicate actual expected operator) (once-only (test-fn predicate actual expected) `(assertion (funcall (symbol-function ,test-fn) ,predicate ,actual) ,actual ,expected ,operator))) (defmacro error-check (test-fn) (with-gensyms (result) `(let ((,result nil)) (handler-case (funcall ,test-fn) (error (c) (declare (ignore c)) (setf ,result t))) ,result))) (defmacro condition-error-check (test-fn condition) (with-gensyms (result) `(let ((,result nil)) (handler-case (funcall ,test-fn) (,condition (c) (declare (ignore c)) (setf ,result t)) (error (c) (declare (ignore c)) (setf ,result nil))) ,result)))
1,669
Common Lisp
.lisp
49
24.204082
71
0.522629
noloop/assert-p
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ff08bfa1018103b9923a0a7577de44632bcd167763123298e419cf2a389cfbf5
18,197
[ -1 ]
18,198
assert-p.asd
noloop_assert-p/assert-p.asd
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; Base: 10 -*- (defsystem :assert-p :author "noloop <[email protected]>" :maintainer "noloop <[email protected]>" :license "GPLv3" :version "1.0.0" :homepage "https://github.com/noloop/assert-p" :bug-tracker "https://github.com/noloop/assert-p/issues" :source-control (:git "[email protected]:noloop/assert-p.git") :description "A library of assertions written in Common Lisp." :depends-on (:assertion-error) :components ((:module "src" :components ((:file "package") (:file "macros" :depends-on ("package")) (:file "assert-p" :depends-on ("macros"))))) :in-order-to ((test-op (test-op "assert-p/test")))) (defsystem :assert-p/test :author "noloop <[email protected]>" :maintainer "noloop <[email protected]>" :license "GPLv3" :description "assert-p Test." :depends-on (:assert-p :simplet) :defsystem-depends-on (:simplet-asdf) :components ((:module "test" :components ((:test-file "assert-p-test")))) :perform (test-op (op c) (symbol-call :simplet '#:run)))
1,131
Common Lisp
.asd
28
34.464286
64
0.626703
noloop/assert-p
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cb14de4fbc8566b7522dc4b5c83807607d0857c299436fe9efedac350eed0f50
18,198
[ -1 ]
18,218
package.lisp
karlosz_elf-parser/package.lisp
;;;; package.lisp (defpackage #:elf-parser (:use #:cl) (:export :elf-p :elf-header :read-elf-header :display-elf-header))
140
Common Lisp
.lisp
7
16.428571
25
0.633588
karlosz/elf-parser
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e59c568ebb4fb227716fa3349dc7af9af6987a63be0377a34e83cadf3f5487f3
18,218
[ -1 ]
18,219
elf-parser.lisp
karlosz_elf-parser/elf-parser.lisp
;;;; elf-parser.lisp (in-package #:elf-parser) (defun elf-p (filespec) "Determines if file has an ELF header." (with-open-file (input filespec :element-type '(unsigned-byte 8)) (= (read-ubytes 4 input) #x7f454c46))) (defclass elf-header () ((EI_MAG0 :initarg :EI_MAG0 :accessor magic-number :documentation "Magic number") (EI_CLASS :initarg :EI_CLASS :accessor elf-class :documentation "1/2 signals 32/64 bit format.") (EI_DATA :initarg :EI_DATA :accessor endian :documentation "1/2 signals little/big endianness,") (EI_VERSION :initarg :EI_VERSION :accessor elf-version :documentation "Version of ELF.") (EI_OSABI :initarg :EI_OSABI :accessor os-abi :documentation "Operating System ABI 0x00 System V 0x01 HP-UX 0x02 NetBSD 0x03 Linux 0x06 Solaris 0x07 AIX 0x08 IRIX 0x09 FreeBSD 0x0c OpenBSD") (EI_ABIVERSION :initarg :EI_ABIVERSION :accessor abi-version :documentation "ABI Version") (EI_PAD :initarg :EI_PAD :accessor padding :documentation "Unused") (e_type :initarg :e_type :accessor exec-type :documentation "1 - relocatable 2 - executable 3 - shared 4 - core") (e_machine :initarg :e_machine :accessor machine :documentation "Machine architecture 0x02 SPARC 0x03 x86 0x08 MIPS 0x14 PowerPC 0x28 ARM 0x32 IA-64 0x3E x86-64 0xB7 AArch64") (e_version :initarg :e_version :accessor another-elf-version :documentation "Version of ELF; again") (e_entry :initarg :e_entry :accessor entry :documentation "Entry point address of process.") (e_phoff :initarg :e_phoff :accessor header-table :documentation "Header table location of file.") (e_shoff :initarg :e_shoff :accessor section-table :documentation "Section table location of file.") (e_flags :initarg :e_flags :accessor flags :documentation "Depends on target architecture.") (e_ehsize :initarg :e_ehsize :accessor elf-header-size :documentation "Size of elf header 52 32 bits 64 64 bits") (e_phentsize :initarg :e_phentsize :accessor program-header-size :documentation "Size of program header.") (e_phnum :initarg :e_phnum :accessor program-header-count :documentation "Number of entries in program header table") (e_shentsize :initarg :e_shentsize :accessor section-header-size :documentation "Size of section header.") (e_shnum :initarg :e_shnum :accessor section-header-count :documentation "Number of entries in section header table.") (e_shstrndx :initarg :e_shstrndx :accessor section_name_index :documentation "Contains index of section names in section header tables."))) (defun read-elf-header (in) (let ((header (make-instance 'elf-header)) endianness bits) (with-slots (EI_MAG0 EI_CLASS EI_DATA EI_VERSION EI_OSABI EI_ABIVERSION EI_PAD e_type e_machine e_version e_entry e_phoff e_shoff e_flags e_ehsize e_phentsize e_phnum e_shentsize e_shnum e_shstrndx) header (setf EI_MAG0 (read-ubytes 4 in)) (setf EI_CLASS (read-ubytes 1 in)) (setf bits (= EI_CLASS 1)) (setf EI_DATA (read-ubytes 1 in)) (setf endianness (= EI_DATA 1)) (setf EI_VERSION (read-ubytes 1 in)) (setf EI_OSABI (read-ubytes 1 in)) (setf EI_ABIVERSION (read-ubytes 1 in)) (setf EI_PAD (read-ubytes 7 in)) (setf e_type (read-ubytes 2 in endianness)) (setf e_machine (read-ubytes 2 in endianness)) (setf e_version (read-ubytes 4 in endianness)) (setf e_entry (if bits (read-ubytes 4 in endianness) (read-ubytes 8 in endianness))) (setf e_phoff (if bits (read-ubytes 4 in endianness) (read-ubytes 8 in endianness))) (setf e_shoff (if bits (read-ubytes 4 in endianness) (read-ubytes 8 in endianness))) (setf e_flags (read-ubytes 4 in endianness)) (setf e_ehsize (read-ubytes 2 in endianness)) (setf e_phentsize (read-ubytes 2 in endianness)) (setf e_phnum (read-ubytes 2 in endianness)) (setf e_shentsize (read-ubytes 2 in endianness)) (setf e_shnum (read-ubytes 2 in endianness)) (setf e_shstrndx (read-ubytes 2 in endianness))) header)) (defun read-ubytes (bytes in &optional little-endian) (if little-endian (loop with value = 0 for low-bit from 0 to (* 8 (1- bytes)) by 8 do (setf (ldb (byte 8 low-bit) value) (read-byte in)) finally (return value)) (loop with value = 0 for low-bit downfrom (* 8 (1- bytes)) to 0 by 8 do (setf (ldb (byte 8 low-bit) value) (read-byte in)) finally (return value)))) (defun display-elf-header (filespec) (with-open-file (in filespec :element-type '(unsigned-byte 8)) (let ((header (read-elf-header in))) (format t "Magic: 0x~X~%" (magic-number header)) (format t "Class: 0x~X~%" (elf-class header)) (format t "Endianness: ~A~%" (endian header)) (format t "Version: ~A~%" (elf-version header)) (format t "OS ABI: ~A~%" (os-abi header)) (format t "ABI Version: 0x~X~%" (abi-version header)) (format t "Padding: 0x~X~%" (padding header)) (format t "Type: 0x~X~%" (exec-type header)) (format t "Machine: 0x~X~%" (machine header)) (format t "Version: 0x~X~%" (another-elf-version header)) (format t "Entry Point Address: 0x~X~%" (entry header)) (format t "Start of Program Headers: ~A (bytes into file)~%" (header-table header)) (format t "Start of Section Headers: ~A (bytes into file)~%" (section-table header)) (format t "Flags: 0x~X~%" (flags header)) (format t "Size of ELF Header: ~A (bytes)~%" (elf-header-size header)) (format t "Size of Program Headers: ~A (bytes)~%" (program-header-size header)) (format t "Number of Program Headers: ~A~%" (program-header-count header)) (format t "Size of section headers: ~A (bytes)~%" (section-header-size header)) (format t "Number of section headers: ~A~%" (section-header-count header)) (format t "Section header string table index: ~A~%" (section_name_index header)))))
6,723
Common Lisp
.lisp
148
36.033784
67
0.608616
karlosz/elf-parser
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8294431029f1aa5143fd1bf65a851d5131b31065de02d7bea94efa2936ea22e5
18,219
[ -1 ]
18,220
elf-parser.asd
karlosz_elf-parser/elf-parser.asd
;;;; elf-parser.asd (asdf:defsystem #:elf-parser :serial t :description "Parses ELF files" :license "GPL v3" :components ((:file "package") (:file "elf-parser")))
188
Common Lisp
.asd
7
22.285714
37
0.625698
karlosz/elf-parser
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
131a18ec6767d90924af5156d2e99aab53333a98be51d00756248a146abd7352
18,220
[ -1 ]
18,239
day3.lisp
blake-watkins_advent-of-code-2022/day3.lisp
(in-package :aoc-2022) (defun parse-rucksack () (parse-line (one-or-more (parse-alphanumeric)))) (defun parse-rucksacks () (one-or-more (parse-rucksack))) (defun parse-groups () (one-or-more (n-of 3 (parse-rucksack)))) (defun split-rucksack (rucksack) (let* ((half (floor (length rucksack) 2)) (front (subseq rucksack 0 half)) (back (subseq rucksack half (length rucksack)))) (list front back))) (defun common (rucksacks) (iter (for c in (first rucksacks)) (finding c such-that (every (lambda (rucksack) (member c rucksack)) rucksacks)))) (defun priority (c) (if (lower-case-p c) (+ (- (char-code c) (char-code #\a)) 1) (+ (- (char-code c) (char-code #\A)) 27))) (defun day3 (input &key (part 1)) (reduce #'+ (if (= part 1) (mapcar (lambda (rucksack) (priority (common (split-rucksack rucksack)))) (run-parser (parse-rucksacks) input)) (mapcar (lambda (rucksacks) (priority (common rucksacks))) (run-parser (parse-groups) input)))))
1,117
Common Lisp
.lisp
29
31.172414
73
0.587581
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0aea9954b6bca2ccf72d0de7dd1cb0a9077a029bc144888a0a347de314f985ce
18,239
[ -1 ]
18,240
day12.lisp
blake-watkins_advent-of-code-2022/day12.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (parse-list (parse-alphanumeric) ""))) (defun neighbours (square squares) (remove-if-not (lambda (s) (gethash s squares)) (mapcar (lambda (dir) (map 'list #'+ square dir)) '((0 1) (0 -1) (1 0) (-1 0))))) (defun get-map (parsed) (let ((map (hash-table-from-list-list parsed)) (start nil) (end nil)) (iter (for (vertex val) in-hashtable map) (when (char= val #\S) (setf start vertex)) (when (char= val #\E) (setf end vertex))) (setf (gethash start map) #\a) (setf (gethash end map) #\z) (list start end map))) (defun start-squares (map) (iter (for (vertex val) in-hashtable map) (when (char= val #\a) (collect vertex)))) (defun day12 (input &key (part 1)) (destructuring-bind (start end squares) (get-map (run-parser (parse-file) input)) (labels ((neighbour-fn (cur) (let ((cur-elevation (char-code (gethash cur squares)))) (remove-if-not (lambda (n) (let ((n-elevation (char-code (gethash n squares)))) (<= n-elevation (1+ cur-elevation)))) (neighbours cur squares))))) (iter (for (vertex parent distance) in-bfs-from (if (= part 1) start (start-squares squares)) neighbours #'neighbour-fn test 'equal) (until (equal vertex end)) (finally (return distance))))))
1,553
Common Lisp
.lisp
40
29.45
72
0.54244
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0c3f6f00e71c5da7813707cb35faa330144c77108583d8a4e485bed91be5df18
18,240
[ -1 ]
18,241
day16.lisp
blake-watkins_advent-of-code-2022/day16.lisp
(in-package :aoc-2022) (defstruct valve name flow next-valves neighbours position) (defun parse-plural (item) (with-monad (parse-string item) (zero-or-more (parse-character #\s)))) (defun parse-valve () (with-monad (parse-string "Valve ") (assign name (parse-keyword)) (assign flow-rate (parse-until (parse-number))) (parse-plural "; tunnel") (parse-plural " lead") (parse-plural " to valve") (parse-character #\Space) (assign tunnels (parse-list (parse-keyword #'alphanumericp) ", ")) (unit (make-valve :name name :flow flow-rate :next-valves tunnels :neighbours nil)))) (defun parse-file () (with-monad (assign valves (parse-lines (parse-valve))) (unit (iter (with ret = (make-hash-table)) (with valve-names = '()) (for valve in valves) (setf (gethash (valve-name valve) ret) valve) (when (> (valve-flow valve) 0) (push (valve-name valve) valve-names)) (finally (set-neighbours ret valve-names) (return (list ret (list-to-opened '() valve-names) valve-names))))))) ;; Build list of all reachable open valves & their distance ;; Store position of valve in to-open list (defun set-neighbours (valves to-open) (iter (for (name valve) in-hashtable valves) (setf (valve-neighbours valve) '()) (iter (for (neighbour parent distance) in-bfs-from name neighbours (lambda (v) (valve-next-valves (gethash v valves))) test 'eq single t) (when (and (not (eq name neighbour)) (member neighbour to-open)) (push (list neighbour distance) (valve-neighbours valve)))) (setf (valve-position valve) (position name to-open)))) (defparameter *best-path-for-set* (make-hash-table :test 'equal)) (defun open-valve (valve opened) (let ((ret (copy-seq opened))) (setf (bit ret (valve-position valve)) 1) ret)) (defun valve-closed (valve opened) (= 0 (bit opened (valve-position valve)))) (defun valve-open (valve opened) (= 1 (bit opened (valve-position valve)))) (defun list-to-opened (valves valve-names) (let ((ret (make-array (length valve-names) :element-type 'bit :initial-element 0))) (iter (for valve in valves) (setf (bit ret (position valve valve-names)) 1) (finally (return ret))))) (defun opened-to-list (opened valve-names) (iter (for open in-sequence opened) (for name in valve-names) (when (= 1 open) (collect name)))) ;; given the time remaining, current valve, current released pressure, which ;; valves are open (and valve information) ;; return the most pressure that can be added from this point (defun pressure-for-set (time-remaining valve pressure opened valves) (setf (gethash opened *best-path-for-set*) (max (gethash opened *best-path-for-set* 0) pressure)) (if (= time-remaining 0) 0 (or (iter (for (neighbour distance) in (valve-neighbours (gethash valve valves))) (for neighbour-open-time = (- time-remaining (+ distance 1))) (for neighbour-valve = (gethash neighbour valves)) (when (and (valve-closed neighbour-valve opened) (>= neighbour-open-time 0)) (maximizing (+ (* neighbour-open-time (valve-flow neighbour-valve)) (pressure-for-set neighbour-open-time neighbour (+ pressure (* neighbour-open-time (valve-flow neighbour-valve))) (open-valve neighbour-valve opened) valves))))) 0))) (defun day16 (input &key (part 1)) (setf *best-path-for-set* (make-hash-table :test 'equal)) (destructuring-bind (valves opened valve-names) (run-parser (parse-file) input) (if (= part 1) (pressure-for-set 30 :aa 0 opened valves) (progn (pressure-for-set 26 :aa 0 opened valves) (iter outer (for (my-valves my-score) in-hashtable *best-path-for-set*) (for unopened-valves = (bit-not my-valves)) (for unopened-list = (opened-to-list unopened-valves valve-names)) (iter (for elephant-list in (combinations unopened-list)) (for elephant-valves = (list-to-opened elephant-list valve-names)) (for elephant-score = (gethash elephant-valves *best-path-for-set*)) (when (and (not (null my-score)) (not (null elephant-score))) (in outer (maximizing (+ my-score elephant-score))))))))))
4,908
Common Lisp
.lisp
113
33.265487
83
0.583229
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
82e7b43175bcab00b25618c5a27789e2863287afd170f0a9795a0cf50a256877
18,241
[ -1 ]
18,242
package.lisp
blake-watkins_advent-of-code-2022/package.lisp
(defpackage :advent-of-code-2022 (:nicknames :aoc-2022) (:use :cl :aoc :iterate) (:shadowing-import-from :fset :reverse :size :convert :set :set-difference :seq :subseq) (:import-from :fset :concat :empty-set :empty-map :domain-contains? :lookup :contains? :includef :arb))
283
Common Lisp
.lisp
5
53.8
105
0.714801
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0b30510cc253cf176c4b3967a6d8522edbb6359ea47f945b664801052dd6489b
18,242
[ -1 ]
18,243
day21.lisp
blake-watkins_advent-of-code-2022/day21.lisp
(in-package :aoc-2022) (defun parse-monkey () (parse-keyword #'alphanumericp)) (defun parse-expr () (either (parse-number) (with-monad (assign op1 (parse-monkey)) (parse-space) (assign op (parse-keyword)) (parse-space) (assign op2 (parse-monkey)) (unit (list op op1 op2))))) (defun parse-file () (with-monad (assign parsed (parse-lines (with-monad (assign name (parse-monkey)) (parse-string ": ") (assign expr (parse-expr)) (unit (list name expr))))) (unit (iter (with ret = (make-hash-table :test 'eq)) (for (name expr) in parsed) (setf (gethash name ret) expr) (finally (return ret)))))) (defstruct expr (x1 0) (x0 0)) (defun expr+ (e1 e2) (make-expr :x1 (+ (expr-x1 e1) (expr-x1 e2)) :x0 (+ (expr-x0 e1) (expr-x0 e2)))) (defun expr- (e1 e2) (make-expr :x1 (- (expr-x1 e1) (expr-x1 e2)) :x0 (- (expr-x0 e1) (expr-x0 e2)))) (defun expr* (e1 e2) (when (and (/= 0 (expr-x1 e1)) (/= 0 (expr-x1 e2))) (error 'cant-multiply)) (make-expr :x1 (+ (* (expr-x1 e1) (expr-x0 e2)) (* (expr-x0 e1) (expr-x1 e2))) :x0 (* (expr-x0 e1) (expr-x0 e2)))) (defun expr/ (e1 e2) (when (or (/= 0 (expr-x1 e2)) (= 0 (expr-x0 e2))) (error 'cant-divide)) (make-expr :x1 (/ (expr-x1 e1) (expr-x0 e2)) :x0 (/ (expr-x0 e1) (expr-x0 e2)))) (defun expr= (e1 e2) (make-expr :x0 (/ (- (expr-x0 e2) (expr-x0 e1)) (- (expr-x1 e1) (expr-x1 e2))))) (defun eval-monkey (monkey monkeys part) (if (and (= part 2) (eq monkey :humn)) (make-expr :x1 1 :x0 0) (let ((expr (gethash monkey monkeys))) (if (numberp expr) (make-expr :x0 expr) (apply (if (and (eq part 2) (eq monkey :root)) #'expr= (ecase (car expr) (:+ #'expr+) (:* #'expr*) (:/ #'expr/) (:- #'expr-))) (mapcar (lambda (m) (eval-monkey m monkeys part)) (cdr expr))))))) (defun day21 (input &key (part 1)) (let ((monkeys (run-parser (parse-file) input))) (expr-x0 (eval-monkey :root monkeys part))))
2,430
Common Lisp
.lisp
62
28.33871
82
0.473483
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
525a2de5207aa1cc0ebadbf0ab9072a66d1f2e584c3ba6ce09d08727a02291b4
18,243
[ -1 ]
18,244
day22.lisp
blake-watkins_advent-of-code-2022/day22.lisp
(in-package :aoc-2022) (defun parse-square () (with-monad (assign char (parse-character " .#")) (unit (case char (#\Space :blank) (#\. :open) (#\# :wall))))) (defun parse-direction () (with-monad (assign dir (parse-keyword #'upper-case-p)) (unit (ecase dir (:l :left) (:r :right))))) (defun parse-path () (one-or-more (either (parse-number) (parse-direction)))) (defun parse-file () (with-monad (assign net (parse-lines (one-or-more (parse-square)))) (assign path (parse-until (parse-path))) (unit (list (hash-table-from-list-list net) path)))) (defun valid-face-corners (pos size net) "Are the corners of a square, sized SIZE starting at POS, in NET and non-blank?" (and (> size 0) (every (lambda (offset) (let* ((coord (point+ pos (point* (1- size) offset))) (square (gethash coord net))) (and square (not (eq :blank square))))) '((0 0) (1 0) (0 1) (1 1))))) (defun get-first-face (net) "Get a list containing the face size, and the rc index of the first face in NET." (let ((col (iter (for c from 0) (while (eq (gethash (list 0 c) net) :blank)) (finally (return c))))) (iter (for face-size from 1) (finding (list face-size (list 0 (floor col face-size))) such-that (not (valid-face-corners (list 0 col) (1+ face-size) net)))))) ;; +x is to the right, +y is into the screen, +z is up. The reference frame is ;; looking down onto the xy plane, with +y in the up direction and +x in the right. ;; Forward in this frame is toward -z. (defparameter *reference-frame* '(1 0 0 0)) (defparameter *reference-frame-forward* '(0 0 -1)) ;; Each direction stores: ;; * the rc offset required to move in that direction on the net ;; * the score for the password at the end ;; * the axis to rotate around in the reference frame to move in that direction ;; on the cube. Direction given by right hand rule, so for :right (0 -1 0) the ;; right thumb pointing to -y means the fingers curl anticlockwise, so will turn ;; the reference orientation from looking down to looking right. (defparameter *direction-info* '((:right (0 1) 0 (0 -1 0)) (:down ( 1 0) 1 (-1 0 0)) (:left (0 -1) 2 (0 1 0)) (:up (-1 0) 3 ( 1 0 0)) (:cw nil nil (0 0 -1)) (:ccw nil nil (0 0 1)))) (defun direction-offset (dir) (cadr (assoc dir *direction-info*))) (defun direction-score (dir) (caddr (assoc dir *direction-info*))) (defun direction-axis (dir) (cadddr (assoc dir *direction-info*))) (defun offset-direction (offset) (car (rassoc offset *direction-info* :test 'equal :key #'first))) (defun frame-forward (frame) "Return the forward vector in FRAME." (q-round (q-rotate-vector *reference-frame-forward* frame))) (defun turn (frame direction) "Return a frame turned 90 degrees in DIRECTION from FRAME." (q-compose frame (q-rotor (/ pi 2) (direction-axis direction)))) (defun net-direction (frame face-frame) "Return the direction of the forward vector in FRAME from the perspective of the face in the original net." (destructuring-bind (x y z) (q-round (q-rotate-vector (frame-forward frame) (q-reciprocal face-frame))) (declare (ignore z)) (offset-direction (list (- y) x)))) ;; In the reference frame, the RC coordinates of the net map to a square in the ;; xy plane. For a face size of 4, the (0,0) rc point maps to (0,3,0) xyz and the ;; (3,3) rc point maps to (3,0,0). The face is surrounded by 1 coordinate in each ;; direction so that points on different faces will not map to the same 3d ;; position. (defun rc-to-cube (rc frame face-size) "Return the 3D cube position corresponding to the RC position on the base of a cube with faces of size FACE-SIZE in frame FRAME." (destructuring-bind (r c) rc (let* ((half-length (/ (1- face-size) 2)) (center (list half-length half-length (1+ half-length))) (xyz (list c (- face-size r 1) 0))) (q-round (point+ (q-rotate-vector (point- xyz center) frame) center))))) ;; Recursively search from the first face returning a hash table of all faces ;; and the frame that points to them. As we move from face to face on the net, ;; change the frame to simulate the cube rolling in the appropriate direction. (defun get-face-frames (face-size current net &key (face-frames (make-hash-table :test 'equal)) (prev nil) (current-frame *reference-frame*)) (setf (gethash current face-frames) current-frame) (iter (for direction in '(:up :down :left :right)) (for neighbour = (point+ current (direction-offset direction))) (when (and (valid-face-corners (point* face-size neighbour) face-size net) (or (null prev) (not (equal prev neighbour)))) (for neighbour-frame = (turn current-frame direction)) (get-face-frames face-size neighbour net :face-frames face-frames :prev current :current-frame neighbour-frame)) (finally (return face-frames)))) ;; Return a hash table mapping each occupied 3d position to its rc coordinate in ;; the net. (defun get-cube (face-size face-frames net) (iter (with cube = (make-hash-table :test 'equal)) (for (pos square) in-hashtable net) (when (or (eq square :open) (eq square :wall)) (for tile = (mapcar (lambda (x) (floor x face-size)) pos)) (for rc = (mapcar (lambda (x) (mod x face-size)) pos)) (for frame = (gethash tile face-frames)) (for cube-pos = (rc-to-cube rc frame face-size)) (setf (gethash cube-pos cube) pos)) (finally (return cube)))) ;; Takes a 3d POSITION, FRAME, and CUBE. Tries to move forward but if we ;; get to the edge of the cube, turns up then tries to move forward onto the next ;; side. If there isn't one, keep turning down and attempting again. ;; Handles moving around both closed and open lidded boxes. (defun next-position (position frame cube) (let ((test-position (point+ position (frame-forward frame)))) (if (gethash test-position cube) (list test-position frame) (iter (for next-frame first (turn frame :up) then (turn next-frame :down)) (for next-position = (point+ test-position (frame-forward next-frame))) (finding (list next-position next-frame) such-that (gethash next-position cube)))))) ;; Return the position and direction from the perspective of the original net (defun net-coordinates (position frame cube face-size face-frames) (let* ((net-position (gethash position cube)) (face-tile (mapcar (lambda (x) (floor x face-size)) net-position)) (face-frame (gethash face-tile face-frames))) (list net-position (net-direction frame face-frame)))) (defun start-position-and-frame (face-size) (list (rc-to-cube '(0 0) *reference-frame* face-size) *reference-frame*)) ;; Find the top-right face, which will be the lid. Find the direction it joins in. ;; Move all the points on the lid to their proper places. Change the frame of the ;; lid in the face-frames hash table. If we would have originally started on the ;; lid, return the new start position, otherwise return the original start pos. (defun open-lid (face-frames cube face-size) (labels ((topmost-rightmost (a b) (if (or (null a) (< (first b) (first a)) (and (= (first b) (first a)) (> (second b) (second a)))) b a))) (iter (with lid = (iter (for (face nil) in-hashtable face-frames) (reducing face by #'topmost-rightmost))) (with lid-frame = (gethash lid face-frames)) (with (join-direction join-frame) = (iter (for dir in '(:left :down)) (for neighbour = (point+ lid (direction-offset dir))) (for frame = (gethash neighbour face-frames)) (finding (list dir frame) such-that frame))) (with join-offset = (point* (- (1+ face-size)) (direction-offset join-direction))) (for r below face-size) (iter (for c below face-size) (for closed-pos = (rc-to-cube (list r c) lid-frame face-size)) (for opened-pos = (rc-to-cube (point+ (list r c) join-offset) join-frame face-size)) (setf (gethash opened-pos cube) (gethash closed-pos cube)) (remhash closed-pos cube)) (finally (setf (gethash lid face-frames) join-frame) (return (if (equal lid-frame *reference-frame*) (list (rc-to-cube join-offset join-frame face-size) join-frame) (start-position-and-frame face-size))))))) (defun traverse (net path &key open-lid) (iter (with (face-size first-face) = (get-first-face net)) (with face-frames = (get-face-frames face-size first-face net)) (with cube = (get-cube face-size face-frames net)) (with (position frame) = (if open-lid (open-lid face-frames cube face-size) (start-position-and-frame face-size))) (initially (setf frame (turn (turn frame :right) :cw))) (for steps-or-direction in path) (if (numberp steps-or-direction) (iter (repeat steps-or-direction) (for (next-position next-frame) = (next-position position frame cube)) (for next-square = (gethash (gethash next-position cube) net)) (until (eq next-square :wall)) (setf position next-position) (setf frame next-frame)) (setf frame (turn frame steps-or-direction))) (finally (return (net-coordinates position frame cube face-size face-frames))))) (defun password (pos dir) (+ (* 1000 (1+ (first pos))) (* 4 (1+ (second pos))) (direction-score dir))) (defun day22 (input &key (open-lid nil)) (let ((parsed (run-parser (one-or-more (parse-until (parse-file))) input))) (iter (for (net path) in parsed) (sum (apply #'password (traverse net path :open-lid open-lid))))))
9,875
Common Lisp
.lisp
197
44.497462
150
0.654304
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
fd950dafc1722412b9344b849e6bfb72b5806f64db0b6d4569ccb5964707706b
18,244
[ -1 ]
18,245
day13.lisp
blake-watkins_advent-of-code-2022/day13.lisp
(in-package :aoc-2022) (defun parse-packet () (parse-bracketed (either (parse-list (either (parse-number) (parse-packet)) ",") (unit '())) "[]")) (defun parse-file () (parse-lines (n-of 2 (parse-line (parse-packet))))) (defun compare (a b) (cond ((and (numberp a) (numberp b)) (cond ((< a b) :less) ((= a b) :equal) (t :more))) ((and (listp a) (listp b)) (cond ((and (null a) (null b)) :equal) ((null a) :less) ((null b) :more) (t (let ((cmp (compare (car a) (car b)))) (if (eq cmp :equal) (compare (cdr a) (cdr b)) cmp))))) ((numberp a) (compare (list a) b)) ((numberp b) (compare a (list b))))) (defparameter *divider-packets* '(((2)) ((6)))) (defun packet< (a b) (eq :less (compare a b))) (defun index-of (packet packets) (1+ (position packet packets :test 'equal))) (defun all-packets (parsed) (append *divider-packets* (iter (for (a b) in parsed) (collect a) (collect b)))) (defun day13 (input &key (part 1)) (let ((parsed (run-parser (parse-file) input))) (if (= part 1) (iter (for index from 1) (for (a b) in parsed) (when (packet< a b) (sum index))) (let ((sorted (sort (all-packets parsed) #'packet<))) (reduce #'* (mapcar (lambda (packet) (index-of packet sorted)) *divider-packets*))))))
1,319
Common Lisp
.lisp
39
29.74359
82
0.580975
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
9d9ce89dbb9c62d54362cae0a31320fbc8cafacfcaf24cadb024bff8b11609fa
18,245
[ -1 ]
18,246
day5.lisp
blake-watkins_advent-of-code-2022/day5.lisp
(in-package :aoc-2022) (defun parse-crate () (parse-bracketed (parse-alphanumeric) "[]")) (defun parse-blank () (with-monad (n-of 3 (parse-space)) (unit :blank))) (defun parse-crates () (parse-lines (parse-list (either (parse-blank) (parse-crate)) " "))) (defun parse-move () (with-monad (parse-string "move ") (assign amount (parse-number)) (parse-string " from ") (assign from (parse-number)) (parse-string " to ") (assign to (parse-number)) (unit (list amount from to)))) (defun parse-file () (with-monad (assign crates (parse-crates)) (n-of 3 (parse-until (parse-newline))) (assign moves (parse-lines (parse-move))) (unit (list crates moves)))) (defun get-stacks (crates) (iter (with ret = (iter (repeat (length (first crates))) (collect '()))) (for level in (reverse crates)) (iter (for crate in level) (for i from 0) (unless (eq :blank crate) (push crate (elt ret i)))) (finally (return ret)))) (defun move (amount from to stacks &key (reverse nil)) (let ((crates (subseq (elt stacks from) 0 amount))) (setf (elt stacks from) (subseq (elt stacks from) amount)) (setf (elt stacks to) (concatenate 'list (if reverse (reverse crates) crates) (elt stacks to)))) stacks) (defun day5 (input &key (part 1)) (destructuring-bind (crates moves) (run-parser (parse-file) input) (let ((stacks (get-stacks crates))) (iter (for (amount from to) in moves) (setf stacks (move amount (1- from) (1- to) stacks :reverse (= part 1)))) stacks)))
1,647
Common Lisp
.lisp
49
28.204082
81
0.61195
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
11269c5345ee2ed628305ae2fcb470b70e15b4b4baa899b63ba0db628e5cd676
18,246
[ -1 ]
18,247
day6.lisp
blake-watkins_advent-of-code-2022/day6.lisp
(in-package :aoc-2022) (defun parse-file () (one-or-more (parse-alphanumeric))) (defun day6 (input &key (part 1)) (let ((search-length (if (= part 1) 4 14)) (parsed (run-parser (parse-file) input))) (iter (for i from 0) (until (= search-length (length (remove-duplicates (subseq parsed i (+ i search-length)))))) (finally (return (+ i search-length))))))
433
Common Lisp
.lisp
12
28.666667
66
0.563246
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
39432d1c920ca19bd49778682e058665d033168fbcc1ac886768cf29bed9dc03
18,247
[ -1 ]
18,248
day19.lisp
blake-watkins_advent-of-code-2022/day19.lisp
(in-package :aoc-2022) (defun parse-cost () (with-monad (assign costs (parse-list (with-monad (assign num (parse-number)) (parse-space) (assign type (parse-keyword #'alphanumericp)) (unit (make-mineral type num))) " and ")) (unit (reduce #'mineral+ costs)))) (defun parse-robot () (with-monad (parse-string "Each ") (assign type (parse-word #'alphanumericp)) (parse-string " robot costs ") (assign cost (parse-cost)) (parse-string ".") (unit (list (intern (string-upcase type)) cost)))) (defun parse-blueprint () (with-monad (parse-string "Blueprint ") (assign id (parse-number)) (parse-string ": ") (assign robots (parse-list (parse-robot) " ")) (unit (list id robots)))) (defun parse-file () (parse-lines (parse-blueprint))) (defparameter *mineral-types* '(ore clay obsidian geode)) (defstruct mineral (ore 0) (clay 0) (obsidian 0) (geode 0)) (defparameter *robots* (iter (with ret = (make-hash-table)) (for type in *mineral-types*) (setf (gethash type ret) (make-mineral (intern (symbol-name type) :keyword) 1)) (finally (return ret)))) (defun map-mineral (fn) (lambda (a b) (iter (with ret = (make-mineral)) (for slot in '(ore clay obsidian geode)) (setf (slot-value ret slot) (funcall fn (slot-value a slot) (slot-value b slot))) (finally (return ret))))) (setf (symbol-function 'mineral+) (map-mineral #'+)) (setf (symbol-function 'mineral-) (map-mineral #'-)) (setf (symbol-function 'mineral-max) (map-mineral #'max)) (defun mineral* (m k) (let ((ret (make-mineral))) (mapcar (lambda (slot) (setf (slot-value ret slot) (* k (slot-value m slot)))) *mineral-types*) ret)) (defun required-resources (robot-type blueprint) (iter (for (type resources) in blueprint) (finding resources such-that (eq robot-type type)))) ;; Return the number of minutes until required resources can be collected ;; NIL if we can't. (defun time-to-collect (required resources robots) (labels ((have-production (required robots) (every (lambda (slot) (or (<= (slot-value required slot) 0) (> (slot-value robots slot) 0))) *mineral-types*))) (let ((required (mineral- required resources))) (when (have-production required robots) (iter (for type in *mineral-types*) (maximizing (if (<= (slot-value required type) 0) 0 (ceiling (slot-value required type) (slot-value robots type))))))))) ;; Return list of robots to build. Each item is a list of robot type, when it'll ;; be ready, and the required resources. ;; Don't return robots if we're already at max production (apart from geode) ;; Don't return robots if they won't produce anything (too little time) (defun choose-robot-to-build (time-remaining resources robots blueprint max-production) (iter (for type in *mineral-types*) (for required-resource = (required-resources type blueprint)) (for time-to-collect = (time-to-collect required-resource resources robots)) (when (and (or (eq type 'geode) (< (slot-value robots type) (slot-value max-production type))) (and time-to-collect (<= time-to-collect (- time-remaining 2)))) (collect (list type (1+ time-to-collect) required-resource))))) ;; How many resources we need to be able to build any robot we like (defun max-required-production (blueprint) (reduce (lambda (ret type) (mineral-max ret (required-resources type blueprint))) *mineral-types* :initial-value (make-mineral))) ;; Upper bound on the number of geodes we can make (disregarding resources) ;; How many we have + (Geode robots * time) + (Make a Geode robot every min) (defun upper-bound (time-remaining resources robots) (+ (mineral-geode resources) (* time-remaining (mineral-geode robots)) (/ (* time-remaining (1- time-remaining)) 2))) (defun max-geodes (time-remaining resources robots blueprint max-resources best-so-far) (cond ((< (upper-bound time-remaining resources robots) best-so-far) 0) ((= 0 time-remaining) (mineral-geode resources)) (t (let ((options (choose-robot-to-build time-remaining resources robots blueprint max-resources))) (if (null options) (+ (mineral-geode resources) (* (mineral-geode robots) time-remaining)) (iter (for (type build-time required-resource) in options) (for new-resources = (mineral- (mineral+ resources (mineral* robots build-time)) required-resource)) (for new-robots = (mineral+ robots (gethash type *robots*))) (maximizing (max-geodes (- time-remaining build-time) new-resources new-robots blueprint max-resources best-so-far) into best-child) (setf best-so-far (max best-so-far (or best-child 0))) (finally (return best-child)))))))) (defun day19 (input &key (part 1)) (let ((parsed (run-parser (parse-file) input))) (if (= part 1) (iter (for (id blueprint) in parsed) (for max-production = (max-required-production blueprint)) (for geodes = (max-geodes 24 (make-mineral) (make-mineral :ore 1) blueprint max-production 0)) (format t "~a ~a ~a~%" id geodes (* id geodes)) (summing (* id geodes))) (iter (repeat 3) (for (id blueprint) in parsed) (for max-production = (max-required-production blueprint)) (for geodes = (max-geodes 32 (make-mineral) (make-mineral :ore 1) blueprint max-production 0)) (format t "~a ~a ~a~%" id geodes (* id geodes)) (multiply geodes)))))
5,924
Common Lisp
.lisp
155
31.722581
87
0.628149
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
118df150a308f62f27915c4a01b5e848ea1b3efd95430d51e5086b27dceed677
18,248
[ -1 ]
18,249
day17.lisp
blake-watkins_advent-of-code-2022/day17.lisp
(in-package :aoc-2022) (defun parse-file () (with-monad (assign chars (zero-or-more (parse-character "<>"))) (unit (mapcar (lambda (c) (case c (#\< :left) (#\> :right))) chars)))) (defparameter *shapes* '(((0 0) (0 1) (0 2) (0 3)) ((0 1) (1 0) (1 1) (1 2) (2 1)) ((0 0) (0 1) (0 2) (1 2) (2 2)) ((0 0) (1 0) (2 0) (3 0)) ((0 0) (1 0) (0 1) (1 1)))) ;; Given the position of the rock shape's (0 0) coordinate, a rock shape, and ;; the map, return either ;; :intersect-wall if it's horizontally out of bounds ;; :intersect-floor if it's below the floor or touching a rock on the map ;; :falling otherwise (defun check-rock (pos rock map) (let ((abs-rock (mapcar (lambda (p) (point+ p pos)) rock))) (cond ((some (lambda (p) (not (<= 0 (second p) 6))) abs-rock) :intersect-wall) ((or (some (lambda (p) (< (first p) 0)) abs-rock) (some (lambda (p) (gethash p map)) abs-rock)) :intersect-floor) (t :falling)))) ;; Shift the rock left or right depending on JET if possible. Move the rock down ;; if possible. Return (:falling pos) if the rock is still falling, ;; (:intersect-floor pos) if the rock landed at pos. (defun move-rock (jet rock pos map) (let ((shifted-pos (point+ pos (if (eq jet :left) '(0 -1) '(0 1))))) (when (eq :falling (check-rock shifted-pos rock map)) (setf pos shifted-pos)) (let ((fallen-pos (point+ pos '(-1 0)))) (if (eq :falling (check-rock fallen-pos rock map)) (list :falling fallen-pos) (list :intersect-floor pos))))) ;; Transfer all parts of the rock shape at position pos to the map. (defun update-map (rock pos map) (iter (for stone in rock) (for abs-stone = (point+ stone pos)) (setf (gethash abs-stone map) t) (maximizing (first abs-stone) into floor) (finally (return floor)))) ;; Create a function that can be called with values. The function will return NIL ;; until it detects a repeat of length N in the stream of values. Once it does ;; it will return a two element list with the indices of the repeats. (defun make-sliding-window (n) (let ((history (fset:empty-map)) (window (fset:empty-seq)) (idx 0)) (lambda (val) (let* ((added-window (fset:with-last window val)) (new-window (if (<= (fset:size added-window) n) added-window (fset:less-first added-window))) (ret (when (fset:domain-contains? history new-window) (list (1+ (- (fset:lookup history new-window) n)) (1+ (- idx n)))))) (setf window new-window) (setf history (fset:with history new-window idx)) (incf idx) ret)))) ;; Return either the height of the tower after N rocks have fallen if given N, ;; otherwise return a list of two indices where the pattern of height differences ;; repeats. (defun get-height-or-repeat (parsed &key n window) (iter outer (with map = (make-hash-table :test 'equal)) (with highest = 0) (generate jet-idx from 0) (generate jet next (elt parsed (mod (next jet-idx) (length parsed)))) (for rock-idx from 0) (for rock = (elt *shapes* (mod rock-idx (length *shapes*)))) (for rock-pos = (list (+ 3 highest) 2)) (when (and n (= rock-idx n)) (terminate)) ;; break after n rocks, if given n. (iter (for (state pos) = (move-rock (in outer (next jet)) rock rock-pos map)) (setf rock-pos pos) (until (eq :intersect-floor state))) (for rock-height = (1+ (update-map rock rock-pos map))) (for height-diff = (- rock-height highest)) (setf highest (max highest rock-height)) (when window (for repeat? = (funcall window height-diff)) (until repeat?)) ;; break when there's a repeat, if given a sliding window (finally (return-from outer (if n highest repeat?))))) (defun calc-height-from-repeat (idx1 idx2 input) (let* ((n 1000000000000) (modulus (- idx2 idx1)) (height1 (get-height-or-repeat input :n idx1)) (height2 (get-height-or-repeat input :n idx2)) (height-diff (- height2 height1))) (multiple-value-bind (num-repeats offset) (floor (- n idx1) modulus) (+ (get-height-or-repeat input :n (+ idx1 offset)) (* num-repeats height-diff))))) (defun day17 (input &key (part 1)) (let ((parsed (run-parser (parse-file) input))) (if (= part 1) (get-height-or-repeat parsed :n 2022) (destructuring-bind (idx1 idx2) (get-height-or-repeat parsed :window (make-sliding-window 30)) (calc-height-from-repeat idx1 idx2 parsed)))))
4,688
Common Lisp
.lisp
102
39.578431
81
0.614016
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0940c260235a181802a7265931c6c19766fc402a9181e7d3cc58d93eac334db3
18,249
[ -1 ]
18,250
day4.lisp
blake-watkins_advent-of-code-2022/day4.lisp
(in-package :aoc-2022) (defun parse-assignment () (parse-list (parse-number) (parse-character #\-))) (defun parse-file () (parse-lines (parse-list (parse-assignment)))) (defun day4 (input &key (part 1)) (let ((parsed (run-parser (parse-file) input))) (iter (for ((s1 e1) (s2 e2)) in parsed) (counting (if (= part 1) (or (and (>= s1 s2) (<= e1 e2)) (and (>= s2 s1) (<= e2 e1))) (or (<= s2 s1 e2) (<= s2 e1 e2) (<= s1 s2 e1) (<= s1 e2 e1)))))))
557
Common Lisp
.lisp
17
25.058824
52
0.484171
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ad2cd34f45374855773a0f9853a8d3069d75ca4d500a28639a8b3152b1aca8ad
18,250
[ -1 ]
18,251
day15.lisp
blake-watkins_advent-of-code-2022/day15.lisp
(in-package :aoc-2022) (defun parse-coordinate () (with-monad (parse-string "x=") (assign x (parse-number)) (parse-string ", y=") (assign y (parse-number)) (unit (list x y)))) (defun parse-file () (zero-or-more (n-of 2 (parse-until (parse-coordinate))))) (defun covered-interval (sensor beacon row) "Given SENSOR, BEACON as positions, and a ROW number, return interval where there cannot be another beacon, or NIL." (destructuring-bind (x y) sensor (let* ((covered-range (manhattan sensor beacon)) (row-range (- covered-range (abs (- y row))))) (when (>= row-range 0) (list (- x row-range) (+ x row-range)))))) (defun covered-intervals (parsed row) "Return list of all intervals covered by the sensors and beacons in PARSED in the given ROW." (intervals-normalize (iter (for (sensor beacon) in parsed) (for interval = (covered-interval sensor beacon row)) (when interval (collect interval))))) (defun find-uncovered (x intervals) "Find the first position at or above X that is not covered by INTERVALS." (let ((containing (intervals-contain intervals x))) (if (null containing) x (find-uncovered (1+ (interval-end containing)) intervals)))) (defun num-covered-beacons (parsed intervals row) "Find the number of beacons in parsed that are covered by INTERVALS in ROW. " (length (remove-duplicates (iter (for (nil (x y)) in parsed) (when (and (= y row) (intervals-contain intervals x)) (collect x)))))) (defun day15 (input &key (part 1)) (let* ((parsed (run-parser (parse-file) input)) (row 2000000) (search-size 4000000)) (if (= part 1) (let* ((intervals (covered-intervals parsed row)) (num-covered-beacons (num-covered-beacons parsed intervals row))) (- (intervals-size intervals) num-covered-beacons)) (destructuring-bind (x y) (iter (for row below search-size) (for uncovered-pos = (find-uncovered 0 (covered-intervals parsed row))) (finding (list uncovered-pos row) such-that (<= uncovered-pos search-size))) (+ (* search-size x) y)))))
2,152
Common Lisp
.lisp
53
35.622642
118
0.663958
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
4d8d02e37458d084c46dd865a804f35e1180879ef2668c28c725c3f8764d269d
18,251
[ -1 ]
18,252
day14.lisp
blake-watkins_advent-of-code-2022/day14.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (parse-list (parse-number-list) " -> "))) (defun build-path (start end map) (iter (with dir = (point-signum (point- end start))) (for cur initially start then (point+ cur dir)) (setf (gethash cur map) t) (until (equal cur end)) (finally (return map)))) (defun build-map (paths) (iter (with map = (make-hash-table :test 'equal)) (for path in paths) (reduce (lambda (s e) (build-path s e map) e) path) (finally (return map)))) (defun move-sand (sand occupied-fn) (let ((falling (iter (for dir in '((0 1) (-1 1) (1 1))) (for next = (point+ sand dir)) (finding next such-that (not (funcall occupied-fn next)))))) (if falling (list :falling falling) (list :landed sand)))) (defun day14 (input &key (part 1)) (let* ((parsed (run-parser (parse-file) input)) (map (build-map parsed)) (floor (+ 2 (iter (for (pos nil) in-hashtable map) (maximizing (second pos))))) (occupied (lambda (sand) (or (gethash sand map) (when (= part 2) (= (second sand) floor)))))) (iter (with start = '(500 0)) (for num-units from 0) (until (funcall occupied start)) ; break for part 2 (for status = (iter (initially (setf pos start)) (for (status pos) next (move-sand pos occupied)) (when (eq status :landed) (setf (gethash pos map) t)) (until (or (eq status :landed) (> (second pos) floor))) ; break for part 1 (finally (return status)))) (until (eq :falling status)) (finally (return num-units))))) ;; This version is approx 20x faster for part 2 - just recursively see where the ;; sand goes. (defun day14-2 (input) (let* ((parsed (run-parser (parse-file) input)) (map (build-map parsed)) (floor (+ 2 (iter (for (pos nil) in-hashtable map) (maximizing (second pos)))))) (labels ((occupied (sand) (or (gethash sand map) (= (second sand) floor))) (count-sand (from) (cond ((occupied from) 0) (t (setf (gethash from map) t) (1+ (iter (for dir in '((0 1) (-1 1) (1 1))) (for next-square = (point+ from dir)) (sum (count-sand next-square)))))))) (count-sand '(500 0)))))
2,676
Common Lisp
.lisp
70
27.514286
80
0.50481
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c832553c5eec7180b4a0237b9e461a952edc4a4f2ec164e19d29fcac8a5e14fc
18,252
[ -1 ]
18,253
day9.lisp
blake-watkins_advent-of-code-2022/day9.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (parse-list (either (parse-number) (parse-keyword)) " "))) (defun move (pos dir) (destructuring-bind (r c) pos (ecase dir (:U (list (1- r) c)) (:D (list (1+ r) c)) (:L (list r (1- c))) (:R (list r (1+ c)))))) (defun update-tail (head tail) (let ((diff (map 'list #'- head tail))) (cond ((every (lambda (d) (<= (abs d) 1)) diff) tail) (t (map 'list #'+ tail (mapcar #'signum diff)))))) (defun day9 (input &key (part 1)) (let ((num-knots (if (= part 1) 2 10)) (moves (run-parser (parse-file) input))) (iter (with knots = (iter (repeat num-knots) (collect '(0 0)))) (with tail-positions = (make-hash-table :test 'equal)) (for (direction amount) in moves) (iter (repeat amount) (setf (elt knots 0) (move (elt knots 0) direction)) (iter (for i from 1 below num-knots) (setf (elt knots i) (update-tail (elt knots (1- i)) (elt knots i)))) (setf (gethash (elt knots (1- num-knots)) tail-positions) t)) (finally (return (hash-table-count tail-positions))))))
1,157
Common Lisp
.lisp
30
32.566667
78
0.563669
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
fc50f6a6fee27550cddc9beec726762c292e26f964f47095c185c3de440d882e
18,253
[ -1 ]
18,254
day24.lisp
blake-watkins_advent-of-code-2022/day24.lisp
(in-package :aoc-2022) (defun parse-map () (parse-lines (one-or-more (parse-character "#.><^v")))) ;; Return the start and end squares rc, the dimensions of the blizzard area, and a ;; hash keyed by position of each blizzard (defun get-map (input) (let* ((parsed (run-parser (parse-map) input)) (start (list -1 (1- (position #\. (first parsed))))) (end (list (- (length parsed) 2) (1- (position #\. (first (last parsed))))))) (iter (with blizzards = (make-hash-table :test 'equal)) (for r from 1 below (1- (length parsed))) (for row = (elt parsed r)) (iter (for c from 1 below (1- (length row))) (for square = (elt row c)) (when (char/= square #\.) (setf (gethash (list (1- r) (1- c)) blizzards) square))) (finally (return (list start end (list (- (length parsed) 2) (- (length (first parsed)) 2)) blizzards)))))) ;; For the given square RC, return a list of the pairs of time index and modulus ;; for when it will be occupied. (defun get-occupied-horizontal (rc dimensions blizzards) (iter (with (cur-row cur-col) = rc) (with width = (second dimensions)) (for c below width) (for blizzard = (gethash (list cur-row c) blizzards)) (when (and blizzard (or (char= blizzard #\>) (char= blizzard #\<))) (collect (list (mod (if (char= blizzard #\>) (- cur-col c) (- c cur-col)) width) width))))) (defun get-occupied-vertical (rc dimensions blizzards) (iter (with (cur-row cur-col) = rc) (with height = (first dimensions)) (for r below height) (for blizzard = (gethash (list r cur-col) blizzards)) (when (and blizzard (or (char= blizzard #\v) (char= blizzard #\^))) (collect (list (mod (if (char= blizzard #\v) (- cur-row r) (- r cur-row)) height) height))))) (defun get-occupied (dimensions blizzards) (iter (with ret = (make-hash-table :test 'equal)) (with (rows cols) = dimensions) (for r below rows) (iter (for c below cols) (for occupied = (remove-duplicates (concatenate 'list (get-occupied-horizontal (list r c) dimensions blizzards) (get-occupied-vertical (list r c) dimensions blizzards)) :test 'equal)) (setf (gethash (list r c) ret) occupied)) (finally (return ret)))) ;; Is SQUARE occupied at TIME (defun is-occupied-at (square time occupied) (some (lambda (occupied-at) (destructuring-bind (offset modulus) occupied-at (= (mod time modulus) offset))) (gethash square occupied))) (define-condition found-end (condition) ((distance :initarg :distance))) ;; Finds path using A*. Each node (vertex) is made up of a pair of (position time) ;; Heuristic is manhattan distance to the end. Neighbours of a node are at ;; 1 minute away and are either the start or end square, or they are any ;; neighbour (or the current position) that is on the board and unoccupied. (defun find-path (start start-time end occupied) (labels ((vertex-fn (cur parent distance) (declare (ignore parent)) (when (equal (first cur) end) (signal 'found-end :distance distance))) (neighbour-fn (vertex) (destructuring-bind (pos time) vertex (mapcar (lambda (next-square) (list (list next-square (1+ time)) 1)) (remove-if-not (lambda (next-square) (or (equal next-square end) (equal next-square start) (and (nth-value 1 (gethash next-square occupied)) (not (is-occupied-at next-square (1+ time) occupied))))) (mapcar (lambda (offset) (point+ offset pos)) '((-1 0) (1 0) (0 -1) (0 1) (0 0))))))) (heuristic-fn (vertex) (manhattan (first vertex) end))) (handler-case (a-star (list start start-time) #'vertex-fn #'neighbour-fn #'heuristic-fn) (found-end (fe) (slot-value fe 'distance))))) (defun day24 (input &key (part 1)) (destructuring-bind (start end dimensions blizzards) (get-map input) (let* ((occupied (get-occupied dimensions blizzards)) (t1 (find-path start 0 end occupied))) (if (= part 1) t1 (let* ((t2 (find-path end t1 start occupied)) (t3 (find-path start (+ t1 t2) end occupied))) (+ t1 t2 t3))))))
4,609
Common Lisp
.lisp
107
34.364486
82
0.579568
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
544026021ca78de4dde6c1939e6c82e8a06f3a0f6fdf55c39b1c7d2a49dc5ec2
18,254
[ -1 ]
18,255
day18.lisp
blake-watkins_advent-of-code-2022/day18.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (parse-number-list))) (defun neighbours (point) (mapcar (lambda (d) (point+ point d)) '((1 0 0) (-1 0 0) (0 1 0) (0 -1 0) (0 0 1) (0 0 -1)))) (defun map-dimensions (map) (iter (with max = nil) (with min = nil) (for (point nil) in-hashtable map) (setf max (point-max max point)) (setf min (point-min min point)) (finally (return (list min max))))) (defun get-exterior (map) (destructuring-bind (min max) (map-dimensions map) (setf min (point- min '(1 1 1))) (setf max (point+ max '(1 1 1))) (labels ((valid-exterior-point (point) (and (every (lambda (min val max) (<= min val max)) min point max) (not (gethash point map))))) (iter (with exterior = (make-hash-table :test 'equal)) (for (point) in-bfs-from min neighbours (lambda (point) (remove-if-not #'valid-exterior-point (neighbours point))) test 'equal single t) (setf (gethash point exterior) t) (finally (return exterior)))))) (defun day18 (input &key (part 1)) (let* ((parsed (run-parser (parse-file) input)) (map (iter (with map = (make-hash-table :test 'equal)) (for point in parsed) (setf (gethash point map) t) (finally (return map)))) (exterior (get-exterior map))) (iter (for point in parsed) (for neighbours = (neighbours point)) (summing (iter (for n in neighbours) (counting (and (not (gethash n map)) (or (= part 1) (gethash n exterior)))))))))
1,878
Common Lisp
.lisp
49
26.938776
67
0.501098
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
90dc22a5b82cd4a6f17ced0600ed4b43ccacb7e7f8e2b72910c640621cdc47ca
18,255
[ -1 ]
18,256
day11.lisp
blake-watkins_advent-of-code-2022/day11.lisp
(in-package :aoc-2022) (defstruct monkey id items operation test-num throw-to inspections) (defun parse-monkey () (with-monad (parse-string "Monkey ") (assign id (parse-number)) (parse-until (parse-string "Starting items: ")) (assign items (parse-list (parse-number) ", ")) (parse-until (parse-string "Operation: new = ")) (assign operation (parse-list (either (parse-number) (parse-keyword)) " ")) (parse-until (parse-string "Test: divisible by ")) (assign test-num (parse-number)) (assign throw-to (n-of 2 (with-monad (parse-until (parse-string "throw to monkey ")) (parse-number)))) (n-of 2 (parse-newline)) (unit (make-monkey :id id :items items :operation operation :test-num test-num :throw-to throw-to :inspections 0)))) (defun parse-file () (one-or-more (parse-monkey))) (defun apply-operation (old-val operation) (let ((substituted (substitute old-val :old operation))) (funcall (ecase (second substituted) (:+ #'+) (:* #'*)) (first substituted) (third substituted)))) (defun monkey-turn (monkey monkeys modulus part) (with-slots (items operation test-num throw-to inspections) monkey (iter (for item in items) (incf inspections) (for worry-level = (mod (floor (apply-operation item operation) (if (= part 1) 3 1)) modulus)) (for target-id = (if (zerop (mod worry-level test-num)) (first throw-to) (second throw-to))) (with-slots ((target-items items)) (elt monkeys target-id) (setf target-items (append target-items (list worry-level))))) (setf items '()))) (defun monkey-business (monkeys) (reduce #'* (subseq (sort (mapcar #'monkey-inspections monkeys) #'>) 0 2))) (defun day11 (input &key (part 1)) (let* ((monkeys (run-parser (parse-file) input)) (modulus (reduce #'* (mapcar #'monkey-test-num monkeys)))) (iter (repeat (if (= part 1) 20 10000)) (iter (for monkey in monkeys) (monkey-turn monkey monkeys modulus part)) (finally (return (monkey-business monkeys))))))
2,376
Common Lisp
.lisp
55
33.2
79
0.571305
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ab45ea0b7eca0919626ac598ff31fa56800dfb2cb0795dac53f7e8596e02485a
18,256
[ -1 ]
18,257
day23.lisp
blake-watkins_advent-of-code-2022/day23.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (one-or-more (either (then (parse-character "#") (unit :elf)) (then (parse-character ".") (unit :blank)) (then (parse-character " ") (unit :blank)))))) (defparameter *propose-order* '(:n :s :w :e)) (setf *print-circle* t) (setf (cddddr *propose-order*) *propose-order*) (defparameter *directions* '((:n (-1 0)) (:ne (-1 1)) (:e (0 1)) (:se (1 1)) (:s (1 0)) (:sw (1 -1)) (:w (0 -1)) (:nw (-1 -1)))) (defun is-accompanied (elf elves) (some (lambda (direction) (gethash (point+ elf (second direction)) elves)) *directions*)) (defun valid-direction (elf dir elves) (iter (with idx = (position dir *directions* :key #'first)) (for offset from -1 to 1) (for direction = (elt *directions* (mod (+ idx offset) (length *directions*)))) (for check-square = (point+ elf (second direction))) (never (gethash check-square elves)) (finally (return (point+ elf (second (elt *directions* idx))))))) (defun propose (elf order elves) (when (is-accompanied elf elves) (iter (repeat 4) (for direction in order) (thereis (valid-direction elf direction elves))))) (defun get-proposals (order elves) (iter (with ret = (make-hash-table :test 'equal)) (for (elf nil) in-hashtable elves) (for proposal = (propose elf order elves)) (if proposal (push elf (gethash proposal ret)) (push elf (gethash :unmoved ret))) (finally (return ret)))) (defun move-elves (proposals) (iter (with ret = (make-hash-table :test 'equal)) (for (target elves) in-hashtable proposals) (if (and (not (eq :unmoved target)) (= 1 (length elves))) (setf (gethash target ret) t) (iter (for elf in elves) (setf (gethash elf ret) t))) (finally (return ret)))) (defun do-round (elves) (let* ((proposals (get-proposals *propose-order* elves)) (moved (move-elves proposals))) (pop *propose-order*) (values moved (= (length (gethash :unmoved proposals)) (hash-table-count elves))))) (defun bounds (elves) (iter (for ((r c) nil) in-hashtable elves) (minimizing r into min-r) (minimizing c into min-c) (maximizing r into max-r) (maximizing c into max-c) (finally (return (list min-r min-c max-r max-c))))) (defun calc-empty (elves bounds) (destructuring-bind (min-r min-c max-r max-c) bounds (- (* (1+ (- max-r min-r)) (1+ (- max-c min-c))) (hash-table-count elves)))) (defun day23 (input) (let* ((parsed (run-parser (parse-file) input)) (elves (iter (with ret = (make-hash-table :test 'equal)) (for r from 0) (for row in parsed) (iter (for c from 0) (for square in row) (when (eq :elf square) (setf (gethash (list r c) ret) t))) (finally (return ret))))) (setf *propose-order* '(:n :s :w :e)) (setf (cddddr *propose-order*) *propose-order*) (iter (for round from 1) (multiple-value-bind (new-elves done) (do-round elves) (until done) (setf elves new-elves)) (finally (return round)))))
3,383
Common Lisp
.lisp
89
30.258427
83
0.567155
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b6b3a4411495d4cb0656e1e86d7c86ccc03ddcd9368bd1605abee831729041c9
18,257
[ -1 ]
18,258
day7.lisp
blake-watkins_advent-of-code-2022/day7.lisp
(in-package :aoc-2022) (defun parse-directory-name () (parse-characters #'alphanumericp)) (defun parse-cd () (with-monad (parse-string "cd ") (either (then (parse-string "..") (unit (list :cd-up))) (then (parse-string "/") (unit (list :cd-root))) (with-monad (assign directory (parse-directory-name)) (unit (list :cd directory)))))) (defun parse-ls () (then (parse-string "ls") (unit (list :ls)))) (defun parse-command () (with-monad (parse-string "$ ") (either (parse-cd) (parse-ls)))) (defun parse-directory-entry () (with-monad (parse-string "dir ") (assign name (parse-directory-name)) (unit (list :dir name)))) (defun parse-file-name () (parse-characters (lambda (c) (or (alphanumericp c) (char= c #\.))))) (defun parse-file-entry () (with-monad (assign size (parse-number)) (parse-space) (assign name (parse-file-name)) (unit (list :file name size)))) (defun parse-interaction () (with-monad (assign command (parse-line (parse-command))) (assign output (zero-or-more (parse-line (either (parse-directory-entry) (parse-file-entry))))) (unit (list command output)))) (defun parse-file () (one-or-more (parse-interaction))) (defun get-filesystem (parsed) (iter (with file-system = (make-hash-table :test 'equal)) (with current-directory = nil) (for (command output) in parsed) (for command-name = (first command)) (case command-name (:cd-root (setf current-directory nil)) (:cd-up (pop current-directory)) (:cd (push (second command) current-directory)) (:ls (setf (gethash current-directory file-system) output))) (finally (return file-system)))) (defun get-size (directory file-system) (let ((contents (gethash directory file-system))) (iter (for entry in contents) (summing (if (eq :file (first entry)) (third entry) (get-size (cons (second entry) directory) file-system)))))) (defun day7 (input) (let* ((parsed (run-parser (parse-file) input)) (file-system (get-filesystem parsed))) (iter (with needed-space = (- 30000000 (- 70000000 (get-size nil file-system)))) (for (dir entry) in-hashtable file-system) (for size = (get-size dir file-system)) (when (<= size 100000) (summing size into part-1)) (when (> size needed-space) (minimizing size into part-2)) (finally (return (list part-1 part-2))))))
2,572
Common Lisp
.lisp
69
30.985507
80
0.615261
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
0575dce8394d47a53af32ec4c36f61fec521905ca92e4de52ace708da309281d
18,258
[ -1 ]
18,259
day1.lisp
blake-watkins_advent-of-code-2022/day1.lisp
(in-package :aoc-2022) (defun parse-elf () (parse-list (parse-number) (parse-newline))) (defun parse-elves () (parse-list (parse-elf) (n-of 2 (parse-newline)))) (defun day1 (input &key (part 1)) (let* ((parsed (run-parser (parse-elves) input)) (calories (mapcar (lambda (foods) (reduce #'+ foods)) parsed)) (sorted (sort calories #'>))) (if (= part 1) (first sorted) (reduce #'+ (subseq sorted 0 3)))))
422
Common Lisp
.lisp
12
32.583333
64
0.643735
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2774c6bf2bbbcda1c5c399fc0992389ac011fece3b9355b9303c067e515cea96
18,259
[ -1 ]
18,260
day20.lisp
blake-watkins_advent-of-code-2022/day20.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (parse-number))) (defun mix-num (nums num orig-idx) (let* ((idx (fset:position-if (lambda (pair) (= orig-idx (second pair))) nums)) (new-idx (mod (+ num idx) (1- (fset:size nums)))) (without (fset:less nums idx))) (fset:insert without new-idx (list num orig-idx)))) (defun mix (nums) (iter (with ret = nums) (format t "~a~%" (fset:image #'first ret)) (for (num idx) in-fset (fset:sort nums #'< :key #'second)) (setf ret (mix-num ret num idx)) (finally (return ret)))) (defun grove (nums) (iter (with zero-pos = (fset:position-if (lambda (pair) (= 0 (first pair))) nums)) (for idx in '(1000 2000 3000)) (sum (first (fset:lookup nums (mod (+ zero-pos idx) (fset:size nums))))))) (defun day20 (input &key (part 1)) (let* ((nums (mapcar (lambda (num) (* num (if (= part 1) 1 811589153))) (run-parser (parse-file) input))) (pairs (fset:convert 'fset:seq (iter (for idx from 0) (for num in nums) (collect (list num idx)))))) (iter (repeat (if (= part 1) 1 10)) (setf pairs (mix pairs))) (grove pairs)))
1,343
Common Lisp
.lisp
33
30.939394
80
0.522008
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
444caef4dc66f6dcc5205538dba45ed2dd6eff38285bc24d996ba805ef7e8b2a
18,260
[ -1 ]
18,261
day2.lisp
blake-watkins_advent-of-code-2022/day2.lisp
(in-package :aoc-2022) (defun parse-game () (parse-list (parse-keyword) (parse-space))) (defun parse-file () (parse-lines (parse-game))) ;; convert the parsed list into appropriate symbols (defun convert-rps (parsed &key (part 1)) (mapcar (lambda (c) (if (eq part 1) (ecase c ((:A :X) :rock) ((:B :Y) :paper) ((:C :Z) :sizzors)) (ecase c (:A :rock) (:B :paper) (:C :sizzors) (:X :lose) (:Y :draw) (:Z :win)))) parsed)) (defparameter *beats* '((:rock . :sizzors) (:sizzors . :paper) (:paper . :rock))) (defun winning-move-against (move) (car (rassoc move *beats*))) (defun losing-move-against (move) (cdr (assoc move *beats*))) ;; Given opponent and my move as a list, return whether I win, lose, draw. (defun outcome (moves) (destructuring-bind (opponent-move my-move) moves (cond ((eq opponent-move my-move) :draw) ((eq my-move (winning-move-against opponent-move)) :win) (t :lose)))) ;; Return game score based on my move and the outcome (defun score (my-move outcome) (+ (ecase my-move (:rock 1) (:paper 2) (:sizzors 3)) (* 3 (ecase outcome (:lose 0) (:draw 1) (:win 2))))) ;; Given opponent's move and desired outcome, return my move. (defun move-for-outcome (move-outcome) (destructuring-bind (opponent-move outcome) move-outcome (ecase outcome (:draw opponent-move) (:win (winning-move-against opponent-move)) (:lose (losing-move-against opponent-move))))) (defun day2 (input &key (part 1)) (labels ((score-1 (moves) (score (second moves) (outcome moves))) (score-2 (move-outcome) (score (move-for-outcome move-outcome) (second move-outcome)))) (let* ((parsed (run-parser (parse-file) input)) (converted (mapcar (lambda (p) (convert-rps p :part part)) parsed)) (scores (mapcar (if (eq part 1) #'score-1 #'score-2) converted))) (reduce #'+ scores))))
2,054
Common Lisp
.lisp
49
34.836735
74
0.593985
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c2b0ac031ba6ee119605ce84877628e5a1975629b20e8c846aed0c05d8a70b3a
18,261
[ -1 ]
18,262
day8.lisp
blake-watkins_advent-of-code-2022/day8.lisp
(in-package :aoc-2022) (defun parse-file () (parse-lines (one-or-more (parse-digit)))) (defparameter *directions* '((1 0) (-1 0) (0 1) (0 -1))) (defun get-tree (pos trees) (destructuring-bind (r c) pos (if (<= 0 r (1- (length trees))) (let ((row (elt trees r))) (if (<= 0 c (1- (length row))) (elt row c) nil)) nil))) (defun visible-trees-in-direction (pos dir trees &key (prev-height -1)) (let* ((next-pos (map 'list #'+ pos dir)) (next (get-tree next-pos trees))) (if next (if (>= next prev-height) (1+ (visible-trees-in-direction next-pos dir trees :prev-height next)) (visible-trees-in-direction next-pos dir trees :prev-height prev-height)) 0))) (defun visible? (pos trees) (some (lambda (dir) (= 0 (visible-trees-in-direction pos dir trees :prev-height (get-tree pos trees)))) *directions*)) (defun view-distance-in-direction (height pos dir trees) (let* ((next-pos (map 'list #'+ pos dir)) (next (get-tree next-pos trees))) (if next (if (>= next height) 1 (1+ (view-distance-in-direction height next-pos dir trees))) 0))) (defun scenic-score (pos trees) (apply #'* (mapcar (lambda (dir) (view-distance-in-direction (get-tree pos trees) pos dir trees)) *directions*))) (defun day8 (input) (let* ((parsed (run-parser (parse-file) input)) (max-r (length parsed)) (max-c (length (first parsed)))) (iter outer (for r below max-r) (iter (for c below max-c) (when (visible? (list r c) parsed) (in outer (summing 1))))))) (defun day8-2 (input) (let* ((parsed (run-parser (parse-file) input)) (max-r (length parsed)) (max-c (length (first parsed)))) (iter outer (for r below max-r) (iter (for c below max-c) (in outer (maximizing (scenic-score (list r c) parsed)))))))
1,939
Common Lisp
.lisp
70
22.814286
71
0.595481
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c1da5d33fb36b47923fa2ae24cb50250c37b5c58f68e8721876354757eee3864
18,262
[ -1 ]
18,263
advent-of-code-2022.asd
blake-watkins_advent-of-code-2022/advent-of-code-2022.asd
(asdf:defsystem "advent-of-code-2022" :description "Advent of Code 2022" :version "0.0.1" :author "Blake Watkins <[email protected]>" :licence "GNU General Public License (GPL) version 3" :depends-on ("advent-of-code" "iterate" "fset") :components ((:file "package") (:file "day1" :depends-on ("package")) (:file "day2" :depends-on ("package")) (:file "day3" :depends-on ("package")) (:file "day4" :depends-on ("package")) (:file "day5" :depends-on ("package")) (:file "day6" :depends-on ("package")) (:file "day7" :depends-on ("package")) (:file "day8" :depends-on ("package")) (:file "day9" :depends-on ("package")) (:file "day10" :depends-on ("package")) (:file "day11" :depends-on ("package")) (:file "day12" :depends-on ("package")) (:file "day13" :depends-on ("package")) (:file "day14" :depends-on ("package")) (:file "day15" :depends-on ("package")) (:file "day16" :depends-on ("package"))))
1,157
Common Lisp
.asd
23
38.347826
56
0.5194
blake-watkins/advent-of-code-2022
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
8e7a20b3851ce0088135449e138f22b7669993ffae36f83b74f0ffb33227dba6
18,263
[ -1 ]
18,303
day3.lisp
blake-watkins_advent-of-code-2021/day3.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-digit) ""))) (defun most-common (numbers) (let* ((half-length (/ (length numbers) 2)) (one-counts (reduce (lambda (a b) (map 'list #'+ a b)) numbers))) (mapcar (lambda (c) (cond ((> c half-length) 1) ((= c half-length) :eq) (t 0))) one-counts))) (defun keep-if (position value numbers) (remove-if-not (lambda (word) (= (elt word position) value)) numbers)) (defun get-rating (position numbers &key (oxygen-p t)) (if (= 1 (length numbers)) (car numbers) (let* ((most-common (elt (most-common numbers) position)) (keep-if (case most-common (:eq (if oxygen-p 1 0)) (t (if oxygen-p most-common (- 1 most-common)))))) (get-rating (1+ position) (keep-if position keep-if numbers) :oxygen-p oxygen-p)))) (defun day3 (input) (let* ((parsed (run-parser (parse-file) input)) (most-common (most-common parsed)) (gamma (digits-to-int most-common)) (epsilon (digits-to-int (mapcar (lambda (x) (- 1 x)) most-common)))) (* gamma epsilon))) (defun day3-2 (input) (let ((parsed (run-parser (parse-file) input))) (* (digits-to-int (get-rating 0 parsed)) (digits-to-int (get-rating 0 parsed :oxygen-p nil)))))
1,451
Common Lisp
.lisp
33
34.363636
77
0.54745
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
77beaade6d3593395cafa22166f6af43c65131b74bbbb31f55210d00d01d9c82
18,303
[ -1 ]
18,304
day12.lisp
blake-watkins_advent-of-code-2021/day12.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-characters #'alpha-char-p) "-"))) (defun big-cave-p (cave) (upper-case-p (elt cave 0))) (defun num-paths-from (cave path allow-repeat caves) (if (equal cave "end") 1 (iter (for neighbour in-fset (fset:lookup caves cave)) (for visited-p = (fset:find neighbour path)) (when (or (big-cave-p neighbour) (not visited-p) (and allow-repeat (not (equal neighbour "start")))) (sum (num-paths-from neighbour (fset:with-last path cave) (and allow-repeat (or (big-cave-p neighbour) (not visited-p))) caves)))))) (defun get-caves (parsed) (iter (with ret = (fset:empty-map (fset:empty-set))) (for (from to) in parsed) (fset:adjoinf (fset:lookup ret from) to) (fset:adjoinf (fset:lookup ret to) from) (finally (return ret)))) (defun day12 (input &key (part 2)) (let* ((parsed (run-parser (parse-file) input)) (caves (get-caves parsed))) (num-paths-from "start" (fset:empty-seq) (= part 2) caves)))
1,260
Common Lisp
.lisp
31
29.967742
69
0.540474
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
afec4e3116efbe7f1d897ca5a0c4ad5ada82ecb3bb18b578bb3b25575ef4d4d2
18,304
[ -1 ]
18,305
package.lisp
blake-watkins_advent-of-code-2021/package.lisp
(defpackage :advent-of-code-2021 (:nicknames :aoc-2021) (:use :cl :aoc :iterate) (:shadowing-import-from :fset :reverse :size :convert :set :set-difference :seq :subseq) (:import-from :fset :concat :empty-set :empty-map :domain-contains? :lookup :contains? :includef :arb))
283
Common Lisp
.lisp
5
53.8
105
0.714801
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
96c0476fc4e90b82afb59dbf3a8eb2350df72a8a0dc1bbe12f6e5b9fac665de5
18,305
[ -1 ]
18,306
day25.lisp
blake-watkins_advent-of-code-2021/day25.lisp
(in-package :aoc-2021) (defun parse-map () (parse-lines (one-or-more (with-monad (assign char (parse-character ">v.")) (unit (ecase char (#\> :east) (#\v :south) (#\. :empty))))))) (defun get-map (input) (let ((parsed (run-parser (parse-map) input))) (iter (with ret = (fset:empty-map :empty)) (for r below (length parsed)) (for row in parsed) (iter (for c below (length row)) (for square in row) (unless (eq square :empty) (fset:includef ret (list r c) square))) (finally (return (list ret (list (length parsed) (length (first parsed))))))))) (defun adjacent (square type dimensions) (mapcar #'mod (point+ square (if (eq type :east) '(0 1) '(1 0))) dimensions)) (defun step-type (type map dimensions) (iter (with ret = (fset:empty-map :empty)) (with changed = nil) (for square in-fset map) (for square-type = (fset:lookup map square)) (cond ((eq type square-type) (let ((adjacent (adjacent square type dimensions))) (if (eq (fset:lookup map adjacent) :empty) (progn (fset:includef ret adjacent type) (setf changed t)) (fset:includef ret square type)))) (t (fset:includef ret square square-type))) (finally (return (list ret changed))))) (defun step-map (map dimensions) (destructuring-bind (map-2 east-changedp) (step-type :east map dimensions) (destructuring-bind (map-3 south-changedp) (step-type :south map-2 dimensions) (list map-3 (or east-changedp south-changedp))))) (defun day25 (input) (destructuring-bind (map dimensions) (get-map input) (iter (for steps from 1) (for (new-map changedp) = (step-map map dimensions)) (while changedp) (setf map new-map) (finally (return steps)))))
2,087
Common Lisp
.lisp
54
28.462963
82
0.545634
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
61004076d8e1f14338bbf7db303a6a97941b0625612d0155de1f9c0614c46720
18,306
[ -1 ]
18,307
day21.lisp
blake-watkins_advent-of-code-2021/day21.lisp
(in-package :aoc-2021) ;; Return the place in the circle you'd be if you started at N and moved X ;; places forward. (defun place (n x) (1+ (mod (+ (1- n) x) 10))) ;; Returns the score of rolling a deterministic dice three times if it has ;; already been rolled ROLLS times. (defun roll-three (rolls) (iter (repeat 3) (summing (1+ (mod rolls 100))) (incf rolls))) (defun day21 (pos other-pos &optional (score 0) (other-score 0) (rolls 0)) (cond ((>= other-score 1000) (* score rolls)) (t (let ((new-pos (place pos (roll-three rolls)))) (day21 other-pos new-pos other-score (+ score new-pos) (+ rolls 3)))))) ;; wins returns a two element list with the number of wins for both players. ;; Base cases: If the player's score is >= 21, the player has a win. If the ;; other player's score is >= 21, the other player has a win. ;; Recursive case: The three rolls of the die can move the player any number ;; from 3 - 9 squares forward. There is one universe where it moves forward ;; 3 ((1 1 1)), three where it moves forward 4 ((1 1 2) (1 2 1) (2 1 1)) etc. ;; Find the number of wins from the other player's perspective from each of ;; those positions and multiply by the number of universes it happened in. ;; Add up all those results then reverse the answer since wins for the other ;; player are losses for the player. (defun wins (pos other-pos &optional (score 0) (other-score 0)) (cond ((>= score 21) (list 1 0)) ((>= other-score 21) (list 0 1)) (t (reverse (apply #'map 'list #'+ (iter (for (next-inc universes) in '((3 1) (4 3) (5 6) (6 7) (7 6) (8 3) (9 1))) (for next-square = (place pos next-inc)) (for other-wins = (wins other-pos next-square other-score (+ score next-square))) (collect (mapcar (lambda (x) (* x universes)) other-wins)))))))) (defun day21-2 (pos-1 pos-2) (reduce #'max (wins pos-1 pos-2))) ;; Memoize arguments, decreases part 2 runtime ~100x. (defun memo (f) (let ((cache (fset:empty-map))) (lambda (&rest args) (let ((cached (fset:lookup cache args))) (if cached cached (let ((ret (apply f args))) (fset:includef cache args ret) ret)))))) (setf (symbol-function 'wins) (memo #'wins))
2,446
Common Lisp
.lisp
54
38.37037
80
0.597653
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2333b7a4c0f5a1413f43707dacfada9bacadc3e977e234094c5d183504a750a3
18,307
[ -1 ]
18,308
day5.lisp
blake-watkins_advent-of-code-2021/day5.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-number-list) (parse-string " -> ")))) (defun day5 (input &optional (part2 nil)) (let ((parsed (run-parser (parse-file) input)) (counts (make-hash-table :test 'equal))) (iter (for (a b) in parsed) (for diff = (point- b a)) (for dir = (point-signum diff)) (for steps = (1+ (reduce #'max (point-abs diff)))) (when (or part2 (find 0 diff)) (iter (repeat steps) (for pos first a then (point+ pos dir)) (incf (gethash pos counts 0))))) (iter (for (nil v) in-hashtable counts) (counting (>= v 2)))))
636
Common Lisp
.lisp
19
28.947368
71
0.598374
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a543f38167e6f2e0204e8a9314f2b6842d02dd4db7c0a0cc7304e0d07ebb5c2b
18,308
[ -1 ]
18,309
day6.lisp
blake-watkins_advent-of-code-2021/day6.lisp
(in-package :aoc-2021) (defun parse-file () (parse-number-list)) (defun age-fish (fish) (let ((new-fish (make-hash-table))) (iter (for (timer num-fish) in-hashtable fish) (if (= 0 timer) (progn (incf (gethash 6 new-fish 0) num-fish) (incf (gethash 8 new-fish 0) num-fish)) (incf (gethash (1- timer) new-fish 0) num-fish)) (finally (return new-fish))))) (defun day6 (days input) (let* ((parsed (run-parser (parse-file) input)) (fish (make-hash-table))) (iter (for timer in parsed) (incf (gethash timer fish 0))) (iter (repeat days) (setf fish (age-fish fish))) (iter (for (nil num) in-hashtable fish) (summing num))))
759
Common Lisp
.lisp
25
23.68
58
0.576976
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
23ff5bd73b25b4f6bcad299b37447078a8b11dd6f5b778e10e076b6a8327dbd4
18,309
[ -1 ]
18,310
day19.lisp
blake-watkins_advent-of-code-2021/day19.lisp
(in-package :aoc-2021) (defun parse-beacon () (with-monad (assign coords (parse-number-list)) (unit coords))) (defun parse-scanner () (with-monad (parse-string "--- scanner ") (assign id (parse-number)) (parse-string " ---") (parse-newline) (assign beacons (parse-lines (parse-beacon))) (unit (list id (fset:convert 'fset:set beacons))))) (defun parse-file () (parse-list (parse-scanner) (n-of 2 (parse-newline)))) (defun matrix* (a b) (when (= (length (first a)) (length b)) (iter (for r below (length a)) (collect (iter (for c below (length (first b))) (collect (iter (for i below (length (first a))) (summing (* (elt (elt a r) i) (elt (elt b i) c)))))))))) (defun matrix-apply (matrix) (lambda (point) (iter (for c in (matrix* matrix (iter (for c in point) (collect (list c))))) (collect (first c))))) (defun transpose-matrix (matrix) (iter (for r below (length matrix)) (collect (iter (for c below (length (first matrix))) (collect (elt (elt matrix c) r)))))) (defparameter *id* '((1 0 0) (0 1 0) (0 0 1))) (defparameter *r-x* '((1 0 0) (0 0 -1) (0 1 0))) (defparameter *r-y* '(( 0 0 1) ( 0 1 0) (-1 0 0))) (defparameter *all-rotations* (iter outer (with orientation = (list *id* *r-y* (matrix* *r-y* *r-y*) (matrix* *r-y* (matrix* *r-y* *r-y*)) (matrix* *r-x* *r-y* ) (matrix* *r-x* (matrix* *r-y* (matrix* *r-y* *r-y*))))) (for r1 in orientation) (iter (repeat 4) (for r2 first *id* then (matrix* *r-x* r2)) (in outer (collect (matrix* r1 r2)))))) ;; Try to find a rotation and translation that will match MATCHES-REQUIRED ;; beacons in the two point clouds. ;; ;; Given the reference points ref-points and another set of points ;; - for every possible rotation (24) ;; - for every pair of possible points in the reference and other set ;; - find the translation that would match those two points ;; - keep track of all the translations, if there's a translation that ;; happens as many times as matches-required, then thats it. (defun match-points (ref-points points matches-required) (iter outer (for rotation-matrix in *all-rotations*) (for rotator = (matrix-apply rotation-matrix)) (for rotated-points = (fset:image rotator points)) (iter (with translations = (fset:empty-map 0)) (for ref-point in-fset ref-points) (iter (for point in-fset rotated-points) (for translation = (point- ref-point point)) (for count = (incf (fset:lookup translations translation))) (in outer (finding (list rotation-matrix translation) such-that (>= count matches-required))))))) ;; Given a list of (id beacon-list) lists representing scanners and their ;; beacons, return a map of pairwise transformations to transform between ;; scanner frames. The keys of the returned map are (id1 id2) where the ;; transformation value will map points in scanner id2's frame into scanner ;; id1's frame. (defun get-pairwise-transforms (scanners matches-required) (let ((uf (make-uf)) (ret (fset:empty-map)) (beacons-map (fset:empty-map))) (iter (for (id beacons) in scanners) (fset:includef beacons-map id beacons) (uf-make-set id uf)) (iter (for (id-1 . matches) in-fset (prematch-pairs scanners matches-required)) (for beacons-1 = (fset:lookup beacons-map id-1)) (iter (for id-2 in-fset matches) (for beacons-2 = (fset:lookup beacons-map id-2)) (unless (= (uf-find id-1 uf) (uf-find id-2 uf)) (for match = (match-points beacons-1 beacons-2 matches-required)) (when match (format t "Linked ~a ~a~%" id-1 id-2) (uf-union id-1 id-2 uf) (fset:includef ret (list id-1 id-2) (cons :normal match)) (fset:includef ret (list id-2 id-1) (cons :inverted match)))))) ret)) ;; Return a map keyed by scanner id of the transform needed to get closer to ;; the reference frame. The map keys are scanner ids, the values are a list ;; of the new scanner frame and a transform to take points there. (defun get-reference-transform-map (pairwise-transforms) (let ((parents (make-hash-table :test 'equal))) (labels ((vertex-fn (vertex parent distance) (declare (ignore distance)) (setf (gethash vertex parents) (cons parent (fset:lookup pairwise-transforms (list parent vertex))))) (neighbour-fn (vertex) (iter (for pair in-fset pairwise-transforms) (when (find vertex pair) (collect (list (if (= vertex (first pair)) (second pair) (first pair)) 1)))))) (dijkstra 0 #'vertex-fn #'neighbour-fn) parents))) ;; Transform a set of points. A normal transformation applies rotation then ;; adds the translation. An inverted transformation subtracts the translation ;; then applies the inverted (transpose since these are orthonormal matrices) ;; rotation matrix. (defun transform-points (points rotation translation &optional (inverted :normal)) (if (eq inverted :normal) (fset:image (lambda (point) (point+ (funcall (matrix-apply rotation) point) translation)) points) (let ((matrix (transpose-matrix rotation))) (fset:image (lambda (point) (funcall (matrix-apply matrix) (point- point translation))) points)))) ;; Transform set of points to the reference frame from the given frame through ;; the set of transforms in transform-map (defun transform-to-reference (points frame transform-map) (if (= frame 0) points (destructuring-bind (next-frame inverted rotation translation) (gethash frame transform-map) (transform-to-reference (transform-points points rotation translation inverted) next-frame transform-map)))) (defun get-coordinate-difference-bags (beacons) (iter (with ret = (iter (repeat (length (fset:arb beacons))) (collect (fset:empty-bag)))) (for (a . rest) on (fset:convert 'list beacons)) (iter (for b in rest) (iter (with diff = (point-abs (point- b a))) (for i from 0) (for d in diff) (fset:includef (elt ret i) d))) (finally (return ret)))) (defun prematch-pairs (scanners matches-required) (let ((diffs-required (floor (* matches-required (1- matches-required)) 2)) (coord-bags (iter (with ret = (fset:empty-map)) (for (id scanner) in scanners) (fset:includef ret id (get-coordinate-difference-bags scanner)) (finally (return ret)))) (ret (fset:empty-map))) (iter (with initial-set = (fset:convert 'fset:set (iter (for (id nil) in scanners) (collect id)))) (for (id nil) in scanners) (fset:includef ret id initial-set) (fset:excludef (fset:lookup ret id) id)) (iter (for id in-fset coord-bags) (iter (for coords in (fset:lookup coord-bags id)) (iter (for other-id in-fset coord-bags) (when (/= id other-id) (unless (fset:find-if (lambda (bag) (>= (fset:size (fset:intersection bag coords)) diffs-required)) (fset:lookup coord-bags other-id)) (fset:excludef (fset:lookup ret id) other-id))))) (finally (return (fset:sort (fset:convert 'fset:seq ret) #'< :key (lambda (x) (fset:size (cdr x))))))))) (defun day19 (input &optional (matches-required 12)) (let* ((parsed (run-parser (parse-file) input)) (pairwise-transforms (get-pairwise-transforms parsed matches-required)) (transform-map (get-reference-transform-map pairwise-transforms)) (all-beacons (fset:empty-set)) (all-scanners (fset:empty-set))) (iter (for (id beacons) in parsed) (fset:unionf all-beacons (transform-to-reference beacons id transform-map)) (fset:unionf all-scanners (transform-to-reference (fset:set '(0 0 0)) id transform-map))) (list (fset:size all-beacons) (iter (for (a b) in (pairs (fset:convert 'list all-scanners))) (maximizing (manhattan a b))))))
9,424
Common Lisp
.lisp
231
30.225108
82
0.557071
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
24cedaaf470f71b8ba91d40225255d00be41f2691dd2d5811aa8bc5d8859ebfa
18,310
[ -1 ]
18,311
day17.lisp
blake-watkins_advent-of-code-2021/day17.lisp
(in-package :aoc-2021) (defun parse-range () (with-monad (parse-lower-case) (parse-character #\=) (parse-list (parse-number) (parse-string "..")))) (defun parse-file () (with-monad (parse-string "target area: ") (parse-list (parse-range) ", "))) (defun within (point target) (every (lambda (coord range) (<= (first range) coord (second range))) point target)) (defun fire (velocity target) (iter (with pos = '(0 0)) (maximizing (second pos) into max-height) (until (or (within pos target) (< (second pos) (y-min target)) (> (first pos) (x-max target)))) (setf pos (point+ pos velocity)) (setf velocity (point+ velocity (list (- (signum (first velocity))) -1))) (finally (return (if (within pos target) max-height nil))))) (defun x-max (target) (cadar target)) (defun y-min (target) (caadr target)) (defun day17 (input) (let ((target (run-parser (parse-file) input))) (iter outer (for x-vel from 1 to (x-max target)) (iter (for y-vel from (y-min target) to (- (y-min target))) (for result = (fire (list x-vel y-vel) target)) (when result (in outer (maximizing result into part1)) (in outer (counting result into part2)))) (finally (return-from outer (list part1 part2))))))
1,366
Common Lisp
.lisp
38
29.868421
81
0.598336
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f889ea7963e28bd9ced4eceb539e66b21fe8d15a33cbe2e82d261851a7dbc901
18,311
[ -1 ]
18,312
day4.lisp
blake-watkins_advent-of-code-2021/day4.lisp
(in-package :aoc-2021) (defun parse-board () (n-of 5 (n-of 5 (parse-until (parse-number))))) (defun parse-file () (with-monad (assign numbers (parse-number-list)) (assign board (parse-list (parse-board) "")) (unit (list numbers board)))) (defun winning-p (board) (or (some (lambda (row) (every (lambda (n) (eq n :marked)) row)) board) (iter (for i below (length board)) (thereis (every (lambda (row) (eq (elt row i) :marked)) board))))) (defun play (num-called numbers board) (when numbers (let* ((called (car numbers)) (new-board (subst :marked called board))) (if (winning-p new-board) (list (1+ num-called) called new-board) (play (1+ num-called) (cdr numbers) new-board))))) (defun score (called-number board) (let ((sum (reduce (lambda (acc row) (+ acc (reduce #'+ row))) (subst 0 :marked board) :initial-value 0))) (* called-number sum))) (defun day4 (input) (destructuring-bind (numbers boards) (run-parser (parse-file) input) (iter (for board in boards) (for result = (play 0 numbers board)) (when result (destructuring-bind (num-called last-number board) result (finding (score last-number board) minimizing num-called into part1) (finding (score last-number board) maximizing num-called into part2))) (finally (return (list part1 part2))))))
1,476
Common Lisp
.lisp
37
32.837838
80
0.607816
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
a2ba73bd30d3008690a60383c52d193f58651094a3c7cf372496ee42385b72c3
18,312
[ -1 ]
18,313
day15.lisp
blake-watkins_advent-of-code-2021/day15.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-digit) ""))) (defun neighbours (p max) (remove-if-not (lambda (neighbour) (every (lambda (c m) (<= 0 c (1- m))) neighbour max)) (mapcar (lambda (d) (map 'list #'+ d p)) '((1 0) (0 1) (-1 0) (0 -1))))) (defun risk (cur map) (multiple-value-bind (rq rr) (floor (first cur) (length map)) (multiple-value-bind (cq cr) (floor (second cur) (length (first map))) (let ((base-risk (elt (elt map rr) cr))) (1+ (mod (+ (1- base-risk) rq cq) 9)))))) (defun day15 (input &key (part 2)) (let* ((map (run-parser (parse-file) input)) (ret (fset:empty-map)) (dim (list (length map) (length (first map))))) (when (= part 2) (setf dim (mapcar (lambda (x) (* 5 x)) dim))) (dijkstra '(0 0) (lambda (vertex parent distance) (declare (ignore parent)) (fset:includef ret vertex distance)) (lambda (v) (mapcar (lambda (n) (list n (risk n map))) (neighbours v dim)))) (fset:lookup ret (mapcar #'1- dim))))
1,110
Common Lisp
.lisp
28
33.178571
74
0.553803
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
456bc19c00d7873d177e7decb8036d8ce35e9e4a7c02f6bd39817d3f4ef65870
18,313
[ -1 ]
18,314
day14.lisp
blake-watkins_advent-of-code-2021/day14.lisp
(in-package :aoc-2021) (defun parse-file () (with-monad (assign polymer (parse-list (parse-upper-case) "")) (n-of 2 (parse-newline)) (assign templates (parse-lines (with-monad (assign pattern (parse-list (parse-upper-case) "")) (parse-string " -> ") (assign replacement (parse-upper-case)) (unit (cons pattern replacement))))) (unit (list polymer templates)))) ;; Use cached internal recursive function. Base case is zero steps, in which case ;; return a bag with just the start and end characters. Otherwise, find the character ;; that goes between start and end (from the template) and add the bag of characters ;; from the start to the middle character and the bag from the middle to the end. The ;; middle character was counted twice, so remove a copy. (defun expand (steps start end templates) "Expand the polymer between the characters START and END for STEPS steps. Return a bag of the number of each element." (let ((cache (fset:empty-map))) (labels ((expand-rec (steps start end) (let ((cached (fset:lookup cache (list steps start end)))) (cond (cached cached) ((= 0 steps) (fset:bag start end)) (t (let* ((mid (cdr (assoc (list start end) templates :test 'equal))) (bag (fset:less (fset:bag-sum (expand-rec (1- steps) start mid) (expand-rec (1- steps) mid end)) mid))) (fset:includef cache (list steps start end) bag) bag)))))) (expand-rec steps start end)))) ;; For each pair in the polymer, expand it to get the bag of characters between the ;; start and end. Add the bags together. All of the elements in the middle of the ;; polymer have been added twice, so remove one of each from the bag. (defun count-elements (steps polymer templates) (iter (with ret = (fset:empty-bag)) (for (start end) on polymer) (when end (setf ret (fset:bag-sum ret (expand steps start end templates)))) (finally (let ((repeated (subseq polymer 1 (1- (length polymer))))) (return (fset:bag-difference ret (fset:convert 'fset:bag repeated))))))) (defun score (bag) (iter (for (nil m) in-fset-bag bag) (maximizing m into max) (minimizing m into min) (finally (return (- max min))))) (defun day14 (input &key (part 2)) (let* ((parsed (run-parser (parse-file) input))) (destructuring-bind (polymer templates) parsed (score (count-elements (if (= part 1) 10 40) polymer templates)))))
2,823
Common Lisp
.lisp
57
38.842105
120
0.589279
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cb7bbaf2c37ebd4b483d9d1562398535a971110741d732f5913ad0b4a0e5b6c2
18,314
[ -1 ]
18,315
day9.lisp
blake-watkins_advent-of-code-2021/day9.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-digit) ""))) (defun neighbours (p map) (remove-if-not (lambda (p) (destructuring-bind (a b) p (and (<= 0 a (1- (length map))) (<= 0 b (1- (length (first map))))))) (mapcar (lambda (d) (map 'list #'+ p d)) '((1 0) (-1 0) (0 1) (0 -1))))) (defun height (p map) (elt (elt map (first p)) (second p))) (defun fill-map (from map) (let ((seen (fset:empty-set)) (queue (fset:seq from))) (iter (while (> (fset:size queue) 0)) (for cur = (fset:first queue)) (for height = (height cur map)) (setf queue (fset:less-first queue)) (when (not (fset:contains? seen cur)) (fset:includef seen cur) (iter (for n in (neighbours cur map)) (for height-n = (height n map)) (when (and (/= height-n 9) (> height-n height)) (setf queue (fset:with-last queue n)))))) (fset:size seen))) (defun get-sinks (map) (iter (with sinks = '()) (for r below (length map)) (iter (for c below (length (first map))) (for height = (height (list r c) map)) (for neighbours = (neighbours (list r c) map)) (when (every (lambda (n) (< height (height n map))) (neighbours (list r c) map)) (setf sinks (cons (list r c) sinks)))) (finally (return sinks)))) (defun day9 (input) (let* ((parsed (run-parser (parse-file) input)) (sinks (get-sinks parsed)) (part1 (iter (for sink in sinks) (summing (1+ (height sink parsed)))))) (let ((sizes (iter (for sink in sinks) (collect (fill-map sink parsed))))) (setf sizes (sort sizes #'>)) (list part1 (reduce #'* (subseq sizes 0 3))))))
1,880
Common Lisp
.lisp
52
27.942308
59
0.521142
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
fa2a8fa57b1d3d4de743d5266c4833e7df2ab1c436e5773272461c847351d070
18,315
[ -1 ]
18,316
day24.lisp
blake-watkins_advent-of-code-2021/day24.lisp
(in-package :aoc-2021) (defun parse-instruction () (with-monad (assign opcode (parse-keyword)) (parse-space) (assign operands (parse-list (either (parse-number) (parse-keyword)) #\Space)) (unit (list opcode operands)))) (defun program (instructions) (if (null instructions) (with-monad (assign state (get-state)) (guard (= 0 (fset:lookup state :z))) (unit (reverse (fset:lookup state :inputs)))) (destructuring-bind (opcode operands) (car instructions) (with-monad (op opcode operands) (program (cdr instructions)))))) (defun analyse (parsed) (let ((parts (iter (for i from 0 below (length parsed) by 18) (collect (subseq parsed i (+ i 18)))))) (mapcar (lambda (part) (list (cadadr (elt part 5)) (cadadr (elt part 15)))) parts))) (defun day24 (input) (let* ((parsed (run-parser (parse-lines (parse-instruction)) input)) (analysis (analyse parsed))) (run-game (program parsed) (fset:with (fset:with (fset:with (fset:empty-map 0) :inputs '()) :analysis analysis) :stack '())))) (defun get-operand (operand) (if (numberp operand) (unit operand) (with-monad (assign state (get-state)) (unit (fset:lookup state operand))))) (defun set-choice (reg choice) (with-monad (assign state (get-state)) (progn (fset:includef state reg choice) (fset:includef state :inputs (cons choice (fset:lookup state :inputs))) (set-state state)) (unit choice))) (defun push-stack (choice) (with-monad (assign state (get-state)) (let ((analysis (fset:lookup state :analysis))) (fset:includef state :analysis (cdr analysis)) (fset:includef state :stack (cons (+ choice (cadar analysis)) (fset:lookup state :stack))) (set-state state)))) (defun pop-stack () (with-monad (assign state (get-state)) (let ((stack (fset:lookup state :stack)) (analysis (fset:lookup state :analysis))) (fset:includef state :analysis (cdr analysis)) (fset:includef state :stack (cdr stack)) (with-monad (set-state state) (unit (list (car stack) (caar analysis))))))) (defun op-input (reg) (with-monad (assign state (get-state)) (assign choice (amb '(1 2 3 4 5 6 7 8 9))) (set-choice reg choice) (if (plusp (caar (fset:lookup state :analysis))) (push-stack choice) (with-monad (assign target (pop-stack)) (guard (= choice (apply #'+ target))))))) (defun op (opcode operands) (let ((reg (first operands)) (operand (second operands))) (with-monad (assign state (get-state)) (assign reg-value (get-operand reg)) (assign operand-value (get-operand operand)) (ecase opcode (:inp (op-input reg)) (:mul (set-state (fset:with state reg (* reg-value operand-value)))) (:add (set-state (fset:with state reg (+ reg-value operand-value)))) (:div (with-monad (guard (/= operand-value 0)) (set-state (fset:with state reg (truncate reg-value operand-value))))) (:mod (with-monad (guard (>= reg-value 0)) (guard (> operand-value 0)) (set-state (fset:with state reg (mod reg-value operand-value))))) (:eql (set-state (fset:with state reg (if (= reg-value operand-value) 1 0))))))))
3,784
Common Lisp
.lisp
102
27.54902
77
0.554072
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
12f7b2aba8fd8ad6ac2c0858bada9ffcc96d79cc34629733a7d20e0d56bc552d
18,316
[ -1 ]
18,317
day18.lisp
blake-watkins_advent-of-code-2021/day18.lisp
(in-package :aoc-2021) (defun parse-pair () (either (with-monad (parse-character #\[) (assign x (parse-pair)) (parse-character #\,) (assign y (parse-pair)) (parse-character #\]) (unit (list x y))) (parse-number))) ;; Zippers ;; http://learnyouahaskell.com/zippers ;; ;; Maybe monad ;; Given a function f :: Zipper -> Maybe Zipper, this will return a function ;; (dont-fail f) :: Zipper -> Maybe Zipper that will not be :nothing. If f ;; would have failed, then (dont-fail f) will return the zipper originally ;; passed to it, otherwise it will return f's result. (defun dont-fail (f) (lambda (zipper) (maybe-mplus (funcall f zipper) (unit zipper)))) ;; add-to-previous :: Int -> Zipper a -> Maybe Zipper a ;; Takes an Int and returns a function taking a Zipper -> Maybe Zipper. When ;; the function is given a zipper it attempts to go to the previous, add the ;; int, then come back. If anything fails this function will return the ;; unaltered zipper, otherwise it will return the altered one. (defun add-to-previous (n) (dont-fail (lambda (explosion-site) (with-zipper explosion-site (go-prev) (modify (lambda (x) (+ x n))) (go-next))))) (defun add-to-next (n) (dont-fail (lambda (explosion-site) (with-zipper explosion-site (go-next) (modify (lambda (x) (+ x n))) (go-prev))))) ;; find-explosion-site :: Tree a -> Maybe Zipper a ;; Uses utility fun FIND-IN-TREE that returns a zipper to the first (in-order) ;; node that satisfies the predicate. Returns :nothing if there aren't any ;; explosion sites. ;; The explosion site must be a pair (list) at depth 4. (defun find-explosion-site (tree) (find-in-tree tree (lambda (tree-node depth) (and (listp tree-node) (= 4 depth))))) ;; Takes a tree, returns a Maybe Tree. A tree is returned if there was an ;; explosion, otherwise :nothing is returned. (defun explode (tree) (with-monad (assign explosion-site (find-explosion-site tree)) (assign ret (let ((pair (zipper-tree explosion-site))) (with-zipper explosion-site (attach 0) (add-to-previous (first pair)) (add-to-next (second pair))))) (unit (zipper-to-tree ret)))) ;; A split site is a single number that is >= 10. (defun find-split-site (tree) (find-in-tree tree (lambda (tree-node depth) (declare (ignore depth)) (and (numberp tree-node) (>= tree-node 10))))) ;; Split takes a tree and returns a Maybe Tree. If there was a split the new ;; tree is returned, otherwise :nothing is returned. (defun split (tree) (with-monad (assign split-site (find-split-site tree)) (assign ret (let* ((number (zipper-tree split-site)) (new-pair (list (floor number 2) (ceiling number 2)))) (funcall (attach new-pair) split-site))) (unit (zipper-to-tree ret)))) ;; Fully reduces snailnum by exploding and splitting. (defun snailnum-reduce (snailnum) (iter (for exploded = (from-maybe (explode snailnum))) (when exploded (setf snailnum exploded) (next-iteration)) (for split = (from-maybe (split snailnum))) (when split (setf snailnum split) (next-iteration)) (while (or exploded split)) (finally (return snailnum)))) ;; Add two snailnums. Make a list and then reduce it. (defun snailnum+ (a b) (snailnum-reduce (list a b))) (defun snailnum-magnitude (snailnum) (cond ((numberp snailnum) snailnum) (t (+ (* 3 (snailnum-magnitude (first snailnum))) (* 2 (snailnum-magnitude (second snailnum))))))) (defun day18 (input) (let ((parsed (run-parser (parse-lines (parse-pair)) input))) (snailnum-magnitude (reduce #'snailnum+ parsed)))) (defun day18-2 (input) (let ((parsed (run-parser (parse-lines (parse-pair)) input))) (iter outer (for a in parsed) (iter (for b in parsed) (unless (equal a b)) (in outer (maximizing (max (snailnum-magnitude (snailnum+ a b)) (snailnum-magnitude (snailnum+ b a)))))))))
4,038
Common Lisp
.lisp
110
32.527273
78
0.664452
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
368898e41b40a3dc17143902a381168fc970f8746f02fbef3109c81df44e1305
18,317
[ -1 ]
18,318
day11.lisp
blake-watkins_advent-of-code-2021/day11.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-digit) ""))) (defun neighbours (p map) (remove-if-not (lambda (p) (fset:domain-contains? map p)) (mapcar (lambda (d) (map 'list #'+ p d)) '((1 0) (-1 0) (0 1) (0 -1) (1 1) (-1 1) (1 -1) (-1 -1))))) (def-state (map flashed flashes)) (defun get-neighbours (octopus) (with-monad (assign map (get-map)) (unit (neighbours octopus map)))) (defun set-brightness (octopus op) "Either increment octopus brightness if OP is :INC, or set to zero if OP is :RESET. Returns new brightness. " (with-monad (assign map (get-map)) (let ((brightness (ecase op (:reset 0) (:inc (1+ (fset:lookup map octopus)))))) (with-monad (set-map (fset:with map octopus brightness)) (unit brightness))))) (defun reset-flashed () "Reset the brightness of flashed octopuses. Clear the set of flashed octopuses. Increase and return the count of flashes. " (with-monad (assign flashed (get-flashed)) (mapfsetm_ (lambda (octopus) (set-brightness octopus :reset)) flashed) (set-flashed (fset:empty-set)) (assign flashes (get-flashes)) (let ((num-flashed (fset:size flashed))) (with-monad (set-flashes (+ flashes num-flashed)) (unit num-flashed))))) (defun increase (octopus) "Increase octopus brightness. Flash the octopus if it's more than 9. " (with-monad (assign brightness (set-brightness octopus :inc)) (whenm (> brightness 9) (flash octopus)))) (defun flash (octopus) "If the octopus hasn't already flashed, flash it and increase its neighbours. " (with-monad (assign flashed (get-flashed)) (whenm (not (fset:contains? flashed octopus)) (with-monad (set-flashed (fset:with flashed octopus)) (assign neighbours (get-neighbours octopus)) (mapm_ #'increase neighbours))))) (defun step-octopuses () "Increase all octopuses, flashing when necessary. Reset flashed. Return number of flashed. " (with-monad (assign map (get-map)) (mapfsetm_ #'increase map) (reset-flashed))) (defun step-octopuses-until (steps flashes-target) "Step octopuses until flashes-target octopuses flash. Return number of steps. " (with-monad (assign flashes (step-octopuses)) (if (= flashes flashes-target) (unit (1+ steps)) (step-octopuses-until (1+ steps) flashes-target)))) (defun day11 (input &optional (part1 nil)) (let* ((parsed (run-parser (parse-file) input)) (map (map-from-list-list parsed))) (run-state (if part1 (with-monad (n-of 100 (step-octopuses)) (get-flashes)) (step-octopuses-until 0 (fset:size map))) (make-state :map map :flashed (fset:empty-set) :flashes 0))))
2,903
Common Lisp
.lisp
76
31.842105
125
0.633132
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
840fd0cc49d0599559dc59e44d8d80279c0296310da7d26c968f32c9b8184ba9
18,318
[ -1 ]
18,319
game.lisp
blake-watkins_advent-of-code-2021/game.lisp
(in-package :aoc-2021) ;;; Game a s :: s -> ((a, s) -> r) -> r ;;; Combination of continuation and state monads ;;; A game monad takes a state (s) and a continuation ((a, s) -> r). It performs ;;; a computation with result type a and then calls its continuation with the ;;; result and the (possibly changed) state. (defun game-unit (a) (lambda (s k) (funcall k (list a s)))) (defun game-bind (ma f) (lambda (s k) (funcall ma s (lambda (as) (destructuring-bind (a s-dash) as (let ((mb (funcall f a))) (funcall mb s-dash (lambda (bs) (funcall k bs))))))))) ;; *CONT-STACK* contains the call stack of continuations generated by AMB (defparameter *cont-stack* nil) (defmacro run-game (m s &optional (k '#'(lambda (x) x))) "Run game M with initial state S. K is called on failure of amb handling." `(let ((aoc:*bind-function* 'game-bind) (aoc:*unit-function* 'game-unit)) (funcall (with-monad (call/cc (lambda (k) (setf *cont-stack* (list k)) ,m))) ,s ,k))) ;;; Primitive functions (defun get-state () (lambda (s k) (funcall k (list s s)))) (defun set-state (new-state) (lambda (s k) (declare (ignore s)) (funcall k (list nil new-state)))) (defun call/cc (f) (lambda (s k) (funcall (funcall f (lambda (a) (lambda (s2 bk) (declare (ignore bk)) (declare (ignore s2)) (funcall k (list a s))))) s k))) ;;; AMB operator ;;; https://mitpress.mit.edu/sites/default/files/sicp/full-text/sicp/book/node88.html (defun amb (l) "Return first item of list that subsequent code won't call (AMB-FAIL) on. " (with-monad (call/cc (lambda (k) (push k *cont-stack*) (unit nil))) (if (null l) (progn (pop *cont-stack*) (amb-fail)) (let ((ret (car l))) (setf l (cdr l)) (unit ret))))) (defun amb-fail () "Backtrack to most recently bound amb and try then next value." (with-monad (funcall (car *cont-stack*) nil))) (defun guard (condition) "Ensure that condition is true. If not AMB-FAIL is called to backtrack. " (if condition (unit nil) (amb-fail)))
2,187
Common Lisp
.lisp
70
26.542857
86
0.611058
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
d0f1f83e3e56785b2dbd0267287aa0efc361ea15afe72dfa643318d9a3d7dea9
18,319
[ -1 ]
18,320
day10.lisp
blake-watkins_advent-of-code-2021/day10.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (parse-list (parse-character "({[<>]})") ""))) (defun closing-char (char) (ecase char (#\( #\)) (#\[ #\]) (#\{ #\}) (#\< #\>))) (defun parse-syntax (chars) (iter (with closing = ()) (for char in chars) (cond ((find char "({[<") (push (closing-char char) closing)) ((char= char (first closing)) (pop closing)) (t (leave (list :corrupted char)))) (finally (return (if (= 0 (length closing)) (list :complete) (list :incomplete closing)))))) (defun score-char (char) (ecase char (#\) 3) (#\] 57) (#\} 1197) (#\> 25137))) (defun score-closing (closing) (reduce (lambda (acc c) (+ (* acc 5) (ecase c (#\) 1) (#\] 2) (#\} 3) (#\> 4)))) closing :initial-value 0)) (defun median (scores) (setf scores (sort scores #'<)) (elt scores (floor (length scores) 2))) (defun day10 (input) (iter (for line in (run-parser (parse-file) input)) (for (result item) = (parse-syntax line)) (case result (:corrupted (summing (score-char item) into part1)) (:incomplete (collecting (score-closing item) into part2-scores))) (finally (return (list part1 (median part2-scores))))))
1,293
Common Lisp
.lisp
35
30.742857
72
0.550759
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ff22d62cb3c2e7da1cd72e3ce58db7d33c03e92e5e1d6be0023994b4c3aab4d8
18,320
[ -1 ]
18,321
day7.lisp
blake-watkins_advent-of-code-2021/day7.lisp
(in-package :aoc-2021) (defun day7 (input &optional (part1 nil)) (let ((parsed (run-parser (parse-number-list) input))) (iter (for pos from (reduce #'min parsed) to (reduce #'max parsed)) (for dist = (if part1 (lambda (v) (abs (- v pos))) (lambda (v) (let ((d (abs (- v pos)))) (/ (* d (1+ d)) 2))))) (minimizing (reduce #'+ (mapcar dist parsed))))))
452
Common Lisp
.lisp
12
28.25
67
0.482916
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
f2b32a80bdd393d50add59ae238668b4c1dcbf5927396fd5fca55bc4271c4954
18,321
[ -1 ]
18,322
day1.lisp
blake-watkins_advent-of-code-2021/day1.lisp
(in-package :aoc-2021) (defun parse-file () (parse-list (parse-number) (parse-newline))) (defun sum-between (nums a b) (reduce #'+ (subseq nums a b))) (defun day1 (input) (let ((parsed (run-parser (parse-file) input))) (iter (with part1 = 0) (with part2 = 0) (for idx from 0) (for num in parsed) (when (>= idx 1) (when (> (elt parsed idx) (elt parsed (1- idx))) (incf part1))) (when (>= idx 3) (when (> (sum-between parsed (- idx 2) (1+ idx)) (sum-between parsed (- idx 3) idx)) (incf part2))) (finally (return (list part1 part2))))))
625
Common Lisp
.lisp
21
24.47619
49
0.582038
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
4fc78eac8a121f93120909c4a1e3bb22eec7548d8863799d84071e2f0977f5a8
18,322
[ -1 ]
18,323
day2.lisp
blake-watkins_advent-of-code-2021/day2.lisp
(in-package :aoc-2021) (defun parse-file () (parse-lines (with-monad (assign dir (parse-keyword)) (parse-space) (assign amount (parse-number)) (unit (list dir amount))))) (defun day2 (input) (let ((parsed (run-parser (parse-file) input))) (iter (with pos = 0) (with depth = 0) (for (dir amount) in parsed) (case dir (:forward (incf pos amount)) (:up (decf depth amount)) (:down (incf depth amount))) (finally (return (* pos depth)))))) (defun day2 (input) (let ((parsed (run-parser (parse-file) input))) (iter (with pos = 0) (with depth = 0) (with aim = 0) (for (dir amount) in parsed) (case dir (:forward (incf pos amount) (incf depth (* aim amount))) (:up (decf aim amount)) (:down (incf aim amount))) (finally (return (* pos depth))))))
930
Common Lisp
.lisp
35
20.142857
49
0.544843
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
ce6178ccc08b3bfe7442b0bbe6f41d9ecc1cb673f75437c992b206940eec002e
18,323
[ -1 ]
18,324
day8.lisp
blake-watkins_advent-of-code-2021/day8.lisp
(in-package :aoc-2021) (defun parse-pattern () (with-monad (assign word (parse-characters #'lower-case-p)) (unit (fset:convert 'fset:set word)))) (defun parse-file () (parse-lines (parse-list (parse-list (parse-pattern) #\Space) (parse-string " | ")))) (defun day8 (input) (let ((parsed (run-parser (parse-file) input))) (iter (for (patterns words) in parsed) (summing (iter (for word in words) (count (member (fset:size word) '(2 3 4 7)))))))) ;; PICK and DECODE-PATTERNS are Game monad functions. PICK uses the AMB operator ;; to choose an element from a list that will pass subsequent GUARD calls. ;; The state in the game monad is the list of the (initially) 10 different patterns. (defun pick (&key size) (with-monad (assign remaining (get-state)) (assign choice (amb remaining)) (guard (= size (fset:size choice))) (set-state (remove choice remaining)) (unit choice))) (defun decode-patterns () (with-monad (assign one (pick :size 2)) (assign four (pick :size 4)) (assign seven (pick :size 3)) (assign eight (pick :size 7)) (assign six (pick :size 6)) (guard (= 1 (num-intersections-with six one))) (assign nine (pick :size 6)) (guard (= 4 (num-intersections-with nine four))) (assign zero (pick :size 6)) (assign three (pick :size 5)) (guard (= 2 (num-intersections-with three one))) (assign two (pick :size 5)) (guard (= 2 (num-intersections-with two four))) (assign five (pick :size 5)) (unit (list zero one two three four five six seven eight nine)))) (defun day8-2 (input) (let ((parsed (run-parser (parse-file) input))) (iter (for (patterns words) in parsed) (for mapping = (first (run-game (decode-patterns) patterns))) (summing (digits-to-int (mapcar (lambda (w) (fset:lookup (convert-to-map mapping) w)) words) :base 10))))) (defun num-intersections-with (a b) (fset:size (fset:intersection a b))) (defun convert-to-map (words) (fset:convert 'fset:map (iter (for val from 0) (for word in words) (collect (cons word val)))))
2,285
Common Lisp
.lisp
60
31.316667
84
0.610131
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2035192b83818910469b60aa7d7f2b3d747dfb73649ce7d594e022dcf9a0b603
18,324
[ -1 ]
18,325
advent-of-code-2021.asd
blake-watkins_advent-of-code-2021/advent-of-code-2021.asd
(asdf:defsystem "advent-of-code-2021" :description "Advent of Code 2021" :version "0.0.1" :author "Blake Watkins <[email protected]>" :licence "GNU General Public License (GPL) version 3" :depends-on ("advent-of-code" "iterate" "fset") :components ((:file "package") (:file "game" :depends-on ("package")) (:file "day1" :depends-on ("package")) (:file "day2" :depends-on ("package")) (:file "day3" :depends-on ("package")) (:file "day4" :depends-on ("package")) (:file "day5" :depends-on ("package")) (:file "day6" :depends-on ("package")) (:file "day7" :depends-on ("package")) (:file "day8" :depends-on ("package" "game")) (:file "day9" :depends-on ("package")) (:file "day10" :depends-on ("package")) (:file "day11" :depends-on ("package")) (:file "day12" :depends-on ("package")) (:file "day13" :depends-on ("package")) (:file "day14" :depends-on ("package")) (:file "day15" :depends-on ("package")) (:file "day16" :depends-on ("package")) (:file "day17" :depends-on ("package")) (:file "day18" :depends-on ("package")) (:file "day19" :depends-on ("package")) (:file "day20" :depends-on ("package")) (:file "day21" :depends-on ("package")) (:file "day22" :depends-on ("package")) (:file "day23" :depends-on ("package"))))
1,603
Common Lisp
.asd
31
38.709677
60
0.503817
blake-watkins/advent-of-code-2021
3
0
0
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
131da826e44d386d529041776f5962e434c0f82be9cef182521d96c1256adb5a
18,325
[ -1 ]
18,363
package.lisp
scymtym_language_smarts/test/smiles/package.lisp
;;;; package.lisp --- Package definition for SMILES tests. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:defpackage #:language.smiles.test (:use #:cl #:fiveam) (:export #:run-tests)) (cl:in-package #:language.smiles.test) (def-suite :language.smiles) (defun run-tests () (run! :language.smiles))
384
Common Lisp
.lisp
15
23.2
61
0.68595
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c94d93d0bfbdff829d68fe0cfedc90cb558fcc1764f3921cfb6eacb36861c8be
18,363
[ -1 ]
18,364
package.lisp
scymtym_language_smarts/test/smiles/parser/package.lisp
(cl:defpackage #:language.smiles.parser.test (:use #:cl #:fiveam #:language.smiles.parser) (:import-from #:parser.common-rules.test #:define-rule-test #:parses-are)) (cl:in-package #:language.smiles.parser.test) (def-suite :language.smiles.parser :in :language.smiles)
295
Common Lisp
.lisp
11
23.454545
45
0.716846
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
44906ecf941d050243eed40c9f257974d59f77f3f03ce03ec328e8ec7a094389
18,364
[ -1 ]
18,365
grammar.lisp
scymtym_language_smarts/test/smiles/parser/grammar.lisp
;;;; grammar.lisp --- Tests for the SMILES parser. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:in-package #:language.smiles.parser.test) (in-suite :language.smiles.parser) (test rule.atom-pattern "Smoke test for the `atom-pattern' rule." (architecture.builder-protocol:with-builder ('list) (parses-are (modified-atom) ("[C++]" '(:bracketed-expression (:expression (((:atom (:modifier (((:charge () :which :positive :value 2 :bounds (2 . 4))))) :symbol (:atom () :kind :organic :symbol "C" :bounds (1 . 2)) :weight nil :class nil :bounds (1 . 4))))) :bounds (0 . 5))) ("[Na]" '(:bracketed-expression (:expression (((:atom () :symbol (:atom () :kind :inorganic :symbol "Na" :bounds (1 . 3)) :weight nil :class nil :bounds (1 . 3))))) :bounds (0 . 4))))))
1,163
Common Lisp
.lisp
29
27.448276
91
0.469027
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
27c944f060cf02a03236e437d32abdb2e95607c3feb036cdc945d6ba64ed1b5c
18,365
[ -1 ]
18,366
package.lisp
scymtym_language_smarts/test/smarts/package.lisp
;;;; package.lisp --- Package definition for SMART tests. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:defpackage #:language.smarts.test (:use #:cl #:fiveam) (:export #:run-tests)) (cl:in-package #:language.smarts.test) (def-suite :language.smarts) (defun run-tests () (run! :language.smarts))
383
Common Lisp
.lisp
15
23.133333
61
0.685083
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6f9943003cecee66f702d5b541a8417525ede93355aee5fc3bc7def23881bb98
18,366
[ -1 ]
18,367
package.lisp
scymtym_language_smarts/test/smarts/parser/package.lisp
;;;; package.lisp --- Package definition for tests of the SMARTS parser. ;;;; ;;;; Copyright (C) 2018, 2019 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:defpackage #:language.smarts.parser.test (:use #:cl #:fiveam #:language.smarts.parser) (:import-from #:parser.common-rules.test #:define-rule-test #:parses-are)) (cl:in-package #:language.smarts.parser.test) (def-suite :language.smarts.parser :in :language.smarts)
484
Common Lisp
.lisp
16
27.5625
72
0.709957
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
778e3350d74f0f8b21ef7234b12bc73088bd79a49013ab4d17f3ab26f2f3177b
18,367
[ -1 ]
18,368
grammar.lisp
scymtym_language_smarts/test/smarts/parser/grammar.lisp
;;;; grammar.lisp --- Tests for the SMARTS grammar. ;;;; ;;;; Copyright (C) 2018, 2019 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:in-package #:language.smarts.parser.test) (in-suite :language.smarts.parser) (test rule.atom-pattern "Smoke test for the `atom-pattern' rule." (let ((language.smiles.parser:*atom-maps?* t)) (architecture.builder-protocol:with-builder ('list) (parses-are (atom-pattern) ;; Bracketed ("[C++]" '(:bracketed-expression (:expression (((:binary-operator (:operand (((:atom () :kind :organic :symbol "C" :bounds (1 . 2))) ((:charge () :which :positive :value 2 :bounds (2 . 4))))) :operator :implicit-and :bounds (1 . 4))))) :bounds (0 . 5))) ("[C+2]" '(:bracketed-expression (:expression (((:binary-operator (:operand (((:atom () :kind :organic :symbol "C" :bounds (1 . 2))) ((:charge () :which :positive :value 2 :bounds (2 . 4))))) :operator :implicit-and :bounds (1 . 4))))) :bounds (0 . 5))) ("C1" '(:binary-operator (:operand (((:atom () :kind :organic :symbol "C" :bounds (0 . 1))) ((:atom-map-class () :class 1 :bounds (1 . 2))))) :operator :implicit-and :bounds (0 . 2))) ("[C]1" '(:binary-operator (:operand (((:bracketed-expression (:expression (((:atom () :kind :organic :symbol "C" :bounds (1 . 2))))) :bounds (0 . 3))) ((:atom-map-class () :class 1 :bounds (3 . 4))))) :operator :implicit-and :bounds (0 . 4))) ("[C:1]" '(:bracketed-expression (:expression (((:binary-operator (:operand (((:atom () :kind :organic :symbol "C" :bounds (1 . 2))) ((:atom-map-class () :class 1 :bounds (2 . 4))))) :operator :implicit-and :bounds (1 . 4))))) :bounds (0 . 5))) ("[Na]" '(:bracketed-expression (:expression (((:atom () :kind :inorganic :symbol "Na" :bounds (1 . 3))))) :bounds (0 . 4))) ;; Non-literal patterns ("[x]" '(:bracketed-expression (:expression (((:atom () :ring-connectivity nil :bounds (1 . 2))))) :bounds (0 . 3))) ("[x2]" '(:bracketed-expression (:expression (((:atom () :ring-connectivity 2 :bounds (1 . 3))))) :bounds (0 . 4))))))) (test rule.bond-pattern "Smoke test for the `bond-pattern' rule." (architecture.builder-protocol:with-builder ('list) (parses-are (bond-pattern) ("." :none) ("~~" :wildcard) ("@" :same-ring) ("/?" :up-or-unspecified) ("\\?" :down-or-unspecified)))) (test rule.recursive "Smoke test for the `recursive' rule." (architecture.builder-protocol:with-builder ('list) (parses-are (recursive) ("$" nil) ("$(" nil) ("$()" nil) ("$(C)" '(:recursive (:pattern (((:atom () :kind :organic :symbol "C" :bounds (2 . 3))))) :bounds (0 . 4))))))
3,592
Common Lisp
.lisp
77
32.376623
103
0.449073
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
91a3c6c6eab889562f8cddd9bb48a20c568b976d01ab1547e651194b7319d5b7
18,368
[ -1 ]
18,369
package.lisp
scymtym_language_smarts/src/smiles/parser/package.lisp
;;;; package.lisp --- Package definition for the smiles.parser module. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:defpackage #:language.smiles.parser (:use #:cl #:alexandria #:esrap) (:local-nicknames (#:bp #:architecture.builder-protocol)) (:shadow #:parse) ;; Variables (:export #:*atom-maps?*) ;; Entry point rule (:export #:smiles) ;; Chain rules (:export #:chain #:branch #:atom) ;; Atom rules (:export #:atom-symbol #:organic-atom-symbol #:aromatic-atom-symbol #:inorganic-atom-symbol) ;; Modified atom rules (:export #:modified-atom #:modified-atom-body) ;; Atom modifier rules (:export #:atom-weight #:atom-modifier #:hydrogen-count #:charge #:chirality #:atom-map-class #:atom-map-class/no-colon) ;; Bond rules (:export #:bond #:bond-none #:bond-single #:bond-double #:bond-quadruple #:bond-aromatic #:bond-up #:bond-down) ;; Parser protocol (:export #:parse))
1,088
Common Lisp
.lisp
57
15.491228
70
0.643068
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
677efbc2890e91cc4ed448b4bcd2d2c823ecc3636da1bbe347de0723ecdd6377
18,369
[ -1 ]
18,370
protocol.lisp
scymtym_language_smarts/src/smiles/parser/protocol.lisp
;;;; protocol.lisp --- Protocol provided by the smiles.parser module. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:in-package #:language.smiles.parser) (defgeneric parse (input builder &key atom-maps?) (:documentation "Parse INPUT as a SMILES expression, build result using BUILDER. ATOM-MAPS? controls whether the […:N] construct may be used in INPUT to assign atom map classes to individual atoms.")) (defmethod parse ((input string) (builder t) &key atom-maps?) (let ((*atom-maps?* atom-maps?)) (bp:with-builder (builder) (esrap:parse 'smiles input))))
655
Common Lisp
.lisp
15
40.733333
69
0.710692
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
7f27a1d88e282e197db0a1956d281742e1de8cbe22d897cd116cb6fdd8aca7c2
18,370
[ -1 ]
18,371
grammar.lisp
scymtym_language_smarts/src/smiles/parser/grammar.lisp
;;;; grammar.lisp --- Grammar for the SMILES language. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> ;;;; Esrap parser for the SMILES language. ;;;; ;;;; See https://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system ;;;; http://www.daylight.com/dayhtml/doc/theory/index.html (cl:in-package #:language.smiles.parser) (defrule smiles (and (? atom) (? chain)) (:destructure (atom chain) (cond ; TODO ((and atom chain) (bp:node* (:chain) (* :element (list* atom (bp:node-relation* :element chain))))) (atom) (chain)))) (defrule chain (+ (or bond-atom branch)) (:lambda (elements &bounds start end) (bp:node* (:chain :bounds (cons start end)) (* :element elements)))) (defrule branch (and #\( chain #\)) (:function second)) (defrule bond-atom (and (? bond) atom) (:destructure (bond atom &bounds start end) (bp:node* (:bond :kind (or bond :single) :bounds (cons start end)) (1 :atom atom)))) (defrule atom (and acyclic-atom (? parser.common-rules:integer-literal/decimal)) (:destructure (atom label &bounds start end) (if label (bp:node* (:labeled :label label :bounds (cons start end)) (1 :atom atom)) atom))) (defrule acyclic-atom (or modified-atom atom-symbol)) ;;; Daylight Theory Manual 3.2.1 Atoms (defrule atom-symbol (or inorganic-atom-symbol organic-atom-symbol aromatic-atom-symbol)) (defrule organic-atom-symbol ; TODO macro (or "Br" "B" "Cl" "C" "F" "I" "N" "O" "P" "S") (:lambda (symbol &bounds start end) (bp:node* (:atom :kind :organic :symbol symbol :bounds (cons start end))))) (defrule aromatic-atom-symbol (or "br" "b" "cl" "c" "f" "i" "n" "o" "p" "s") (:lambda (symbol &bounds start end) (bp:node* (:atom :kind :aromatic :symbol symbol :bounds (cons start end))))) ;; msmarts_Parser.yy:869 (defrule inorganic-atom-symbol (or "Al" "Ca" "Co" "Cu" "Fe" "Na") (:lambda (symbol &bounds start end) (bp:node* (:atom :kind :inorganic :symbol symbol :bounds (cons start end))))) ;;; Daylight Theory Manual 3.5 Atom expression ;;; ;;; "modified" in the sense of element symbol/atomic mass plus ;;; modifiers. (defrule modified-atom (and #\[ modified-atom-body #\]) (:function second) (:lambda (expression &bounds start end) (bp:node* (:bracketed-expression :bounds (cons start end)) (1 :expression expression)))) (defrule modified-atom-body (and (or (and atom-weight atom-symbol) (and atom-weight (and)) (and (and) atom-symbol)) (* atom-modifier) (? atom-map-class)) (:destructure ((weight symbol) modifiers class &bounds start end) (bp:node* (:atom :symbol symbol :weight weight :class class :bounds (cons start end)) (* :modifier modifiers)))) (defrule atom-weight parser.common-rules::integer-literal/decimal/no-sign) (defrule atom-modifier (or hydrogen-count charge chirality)) (defrule hydrogen-count ; TODO is this SMILES or SMARTS? (and "H" parser.common-rules:integer-literal/decimal)) ; TODO predicate for non-negative or positive (defrule charge (or charge-positive charge-negative)) (macrolet ((define-repeat-rules (name character &optional (value (make-keyword name))) (let ((rule-name (symbolicate '#:charge- name)) (rule-name/number (symbolicate '#:charge- name '#:/number)) (rule-name/repeat (symbolicate '#:charge- name '#:/repeat))) `(progn (defrule ,rule-name (or ,rule-name/number ,rule-name/repeat)) (defrule ,rule-name/number (and ,character parser.common-rules::integer-literal/decimal/no-sign) (:function second) (:lambda (count &bounds start end) (bp:node* (:charge :which ',value :value count :bounds (cons start end))))) (defrule ,rule-name/repeat (+ ,character) (:function length) (:lambda (count &bounds start end) (bp:node* (:charge :which ',value :value count :bounds (cons start end))))))))) (define-repeat-rules positive #\+) (define-repeat-rules negative #\-)) ;;; Daylight Theory Manual 3.3.4 General Chiral Specification (defrule chirality (or chirality/number chirality/repeat)) (defrule chirality/number (and #\@ (? (or "TH" "AL" "SP" "TB" "OH")) parser.common-rules:integer-literal/decimal) (:function rest) (:destructure (class count &bounds start end) (bp:node* (:chirality :class class :count count :bounds (cons start end))))) (defrule chirality/repeat (+ #\@) (:function length) (:lambda (count &bounds start end) (bp:node* (:chirality :count count :bounds (cons start end))))) ;;; Daylight Theory Manual, page 17 (macrolet ((define-atom-map-class-rule (name &body expression-and-options) `(defrule ,name ,@expression-and-options (:lambda (class &bounds start end) (bp:node* (:atom-map-class :class class :bounds (cons start end)))) (:when *atom-maps?*)))) (define-atom-map-class-rule atom-map-class (and #\: parser.common-rules::integer-literal/decimal/no-sign) (:function second)) (define-atom-map-class-rule atom-map-class/no-colon parser.common-rules::integer-literal/decimal/no-sign)) ;;; Daylight Theory Manual 3.2.2 Bonds (macrolet ((define-rules (&body clauses) (let ((rules '())) (flet ((process-clause (name string &optional (value (make-keyword name))) (let ((rule-name (symbolicate '#:bond- name))) (push rule-name rules) `(defrule ,rule-name ,string (:constant ,value))))) `(progn ,@(map 'list (curry #'apply #'process-clause) clauses) (defrule bond (or ,@ (nreverse rules)))))))) (define-rules (none #\.) (single #\-) (double #\=) (triple #\#) (quadruple #\$) (aromatic #\:) (up #\/) (down #\\)))
6,391
Common Lisp
.lisp
159
32.855346
104
0.60142
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cce099f60ea361bcc94f23951df2991fdc7c13a4c71f070ca60a89cf53e12cca
18,371
[ -1 ]
18,372
variables.lisp
scymtym_language_smarts/src/smiles/parser/variables.lisp
;;;; variables.lisp --- Variables used by the smiles.parser module. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:in-package #:language.smiles.parser) (defvar *atom-maps?* nil)
246
Common Lisp
.lisp
7
33.857143
67
0.708861
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b95e1cd3d40577617cefd1bb19a044f8823dfed6480672cd2dbd88bd578e14ad
18,372
[ -1 ]
18,373
package.lisp
scymtym_language_smarts/src/smarts/parser/package.lisp
;;;; package.lisp --- Package definition for the smarts.parser module. ;;;; ;;;; Copyright (C) 2018, 2019 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:defpackage #:language.smarts.parser (:use #:cl #:alexandria #:esrap) (:shadow #:parse) (:local-nicknames (#:bp #:architecture.builder-protocol) (#:smiles #:language.smiles.parser)) ;; Exported rules (:export #:atom-pattern #:bond-pattern #:recursive) ;; Parser protocol (:export #:parse))
532
Common Lisp
.lisp
23
20
70
0.662698
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2dbdfe8ee3ef2ba6549cfe5adbf58b4a552e497b2914ef3ce67caf531b95b5d8
18,373
[ -1 ]
18,374
protocol.lisp
scymtym_language_smarts/src/smarts/parser/protocol.lisp
;;;; protocol.lisp --- Protocol provided by the smarts.parser module. ;;;; ;;;; Copyright (C) 2018 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> (cl:in-package #:language.smarts.parser) (defgeneric parse (input builder) (:documentation "Parse INPUT as a SMARTS expression, build result using BUILDER.")) (defmethod parse ((input string) (builder t)) (let ((smiles:*atom-maps?* t)) (bp:with-builder (builder) (esrap:parse 'smarts input))))
493
Common Lisp
.lisp
13
35.384615
70
0.706499
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
bd361e0dd8f2ca2f75a062b00fd1d554eb2cd8aec6bafbc9366f60ea4f1ed345
18,374
[ -1 ]
18,375
grammar.lisp
scymtym_language_smarts/src/smarts/parser/grammar.lisp
;;;; grammar.lisp --- Grammar for the SMARTS language. ;;;; ;;;; Copyright (C) 2018, 2019 Jan Moringen ;;;; ;;;; Author: Jan Moringen <[email protected]> ;;;; Esrap parser for the SMARTS language as an extension of the Esrap ;;;; parser for the SMILES language. ;;;; ;;;; See https://en.wikipedia.org/wiki/Smiles_arbitrary_target_specification ;;;; https://docs.eyesopen.com/toolkits/cpp/oechemtk/SMARTS.html ;;;; http://www.daylight.com/cheminformatics/index.html (cl:in-package #:language.smarts.parser) (defrule smarts (and atom-pattern (? chain-elements)) (:destructure (atom elements &bounds start end) (if elements (bp:node* (:chain :bounds (cons start end)) (* :element (list* atom elements))) atom))) (defrule chain-pattern chain-elements (:lambda (elements &bounds start end) (bp:node* (:chain :bounds (cons start end)) (* :element elements)))) (defrule chain-elements (+ (or bond-atom-pattern branch))) (defrule branch (and #\( chain-pattern #\)) ; TODO ast node for this? (:function second)) (defrule bond-atom-pattern (and (? bond-pattern) atom-pattern) (:destructure (bond atom &bounds start end) (bp:node* (:bond :kind (or bond :single) :bounds (cons start end)) (1 :atom atom)))) (defrule atom-pattern ; TODO duplicated from SMILES? ;; The trailing integer is an atom map class, but in contrast to ;; `language.simles.parser:atom-map-class', there is no #\: ;; preceding the integer. (and acyclic-atom-pattern (? smiles:atom-map-class/no-colon)) (:destructure (atom class &bounds start end) (if class (bp:node* (:binary-operator :operator :implicit-and :bounds (cons start end)) (1 :operand atom) (1 :operand class)) atom))) (defrule acyclic-atom-pattern (or modified-atom-pattern smiles:atom-symbol)) (defrule modified-atom-pattern (and #\[ weak-and-expression #\]) (:function second) (:lambda (expression &bounds start end) (bp:node* (:bracketed-expression :bounds (cons start end)) (1 :expression expression)))) ;;; SMARTS 4.1 Atomic Primitives ;;; There are no modifiers: 4.3 Logical Operators ;;; ;;; All atomic expressions which are not simple primitives must be ;;; enclosed in brackets. The default operation is & (high precedence ;;; "and"), i.e., two adjacent primitives without an intervening ;;; logical operator must both be true for the expression (or ;;; subexpression) to be true. (defrule modified-atom-pattern-body (or smiles:atom-weight ; TODO this is just a number, i.e. (node* ) is missing smiles:atom-symbol ; smiles:hydrogen-count smiles:charge smiles:chirality atom-pattern/non-literal smiles:atom-map-class recursive)) (macrolet ((define-rules (&body clauses) (let ((rules '())) (flet ((process-clause (name expression &key parameter (kind (make-keyword name))) (let ((rule-name (symbolicate '#:atom-rule- name))) (push rule-name rules) (ecase parameter ((t &optional) `(defrule ,rule-name (and ,expression ,(if (eq parameter '&optional) `(? parser.common-rules:integer-literal/decimal) 'parser.common-rules:integer-literal/decimal)) (:function second) (:lambda (value &bounds start end) (bp:node* (:atom ,kind value :bounds (cons start end)))))) ((nil) `(defrule ,rule-name ,expression (:lambda (value &bounds start end) (declare (ignore value)) (bp:node* (:atom :kind ',kind :bounds (cons start end)))))))))) `(progn ,@(map 'list (curry #'apply #'process-clause) clauses) (defrule atom-pattern/non-literal (or ,@(nreverse rules)))))))) (define-rules (wildcard #\*) (aromatic #\a) (aliphatic #\A) (degree #\D :parameter t) (total-hydrogen-count #\H :parameter &optional) (implicit-hydrogen-count #\h :parameter &optional) (ring-bond-count #\R :parameter &optional) (ring-connectivity #\x :parameter &optional) (smallest-ring-size #\r :parameter &optional) (valence #\v :parameter t) (connectivity #\X :parameter t) (atomic-number #\# :parameter t))) ;;; SMARTS 4.2 Bonds Primitives (defrule bond-pattern (or bond-pattern/non-literal smiles:bond)) ;;; Only additions to SMILES 3.2.2. (macrolet ((define-rules (&body clauses) (let ((rules '())) (flet ((process-clause (name expression &key (kind (make-keyword name))) (let ((rule-name (symbolicate '#:bond-pattern- name))) (push rule-name rules) `(defrule ,rule-name ,expression (:constant ,kind))))) `(progn ,@(map 'list (curry #'apply #'process-clause) clauses) (defrule bond-pattern/non-literal (or ,@(nreverse rules)))))))) (define-rules (wildcard #\~) (same-ring #\@) ; added in SMARTS 4.6 (up-or-unspecified "/?") (down-or-unspecified "\\?"))) ;;; SMARTS 4.3 Logical Operators (macrolet ((define-operator-rule (name expression) (let ((rule-name (symbolicate '#:operator- name)) (value (make-keyword name))) `(defrule ,rule-name ,expression (:constant ,value))))) (define-operator-rule weak-and #\;) (define-operator-rule or #\,) (define-operator-rule strong-and #\&) (define-operator-rule not #\!) (define-operator-rule implicit-and (and))) (parser.common-rules.operators:define-operator-rules (:skippable?-expression nil) (2 weak-and-expression operator-weak-and) (2 or-expression operator-or) (2 strong-and-expression operator-strong-and) (1 not-expression operator-not) (2 implicit-and-expression operator-implicit-and) modified-atom-pattern-body) ;;; SMARTS 4.4 Recursive SMARTS (defrule recursive (and #\$ #\( smarts #\)) (:function third) (:lambda (pattern &bounds start end) (bp:node* (:recursive :bounds (cons start end)) (1 :pattern pattern))))
6,918
Common Lisp
.lisp
162
33.395062
91
0.570218
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
b1e22ee8b66a7c1caff74137b90ec18d28d7bc6cbfe9e0a25563194b3c694331
18,375
[ -1 ]
18,376
language.smiles.asd
scymtym_language_smarts/language.smiles.asd
(defsystem "language.smiles" :description "A parser for the SMILES language." :license "GPLv3" :author "Jan Moringen <[email protected]>" :version (:read-file-form "version-string.sexp") :depends-on ("alexandria" (:version "esrap" "0.16") (:version "parser.common-rules" "0.4") (:version "architecture.builder-protocol" "0.9")) :components ((:module "parser" :pathname "src/smiles/parser" :serial t :components ((:file "package") (:file "variables") (:file "protocol") (:file "grammar")))) :in-order-to ((test-op (test-op "language.smiles/test")))) (defsystem "language.smiles/test" :depends-on ("alexandria" (:version "fiveam" "1.4") (:version "parser.common-rules/test" "0.3") "language.smiles") :components ((:module "test" :pathname "test/smiles" :serial t :components ((:file "package"))) (:module "parser" :depends-on ("test") :pathname "test/smiles/parser" :serial t :components ((:file "package") (:file "grammar" )))) :perform (test-op (operation component) (uiop:symbol-call '#:language.smiles.test '#:run-tests)))
1,618
Common Lisp
.asd
34
33.705882
73
0.46374
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3905b9bbe1e257da015c3e68cd9c6d1ba1612555949fc4088592bb90afad2a28
18,376
[ -1 ]
18,377
language.smarts.asd
scymtym_language_smarts/language.smarts.asd
(defsystem "language.smarts" :description "A parser for the SMARTS language." :license "GPLv3" :author "Jan Moringen <[email protected]>" :version (:read-file-form "version-string.sexp") :depends-on ("alexandria" (:version "esrap" "0.16") (:version "parser.common-rules" "0.4") (:version "parser.common-rules.operators" "0.4") (:version "architecture.builder-protocol" "0.9") (:version "language.smiles" (:read-file-form "version-string.sexp"))) :components ((:module "parser" :pathname "src/smarts/parser" :serial t :components ((:file "package") (:file "grammar") (:file "protocol")))) :in-order-to ((test-op (test-op "language.smarts/test")))) (defsystem "language.smarts/test" :depends-on ("alexandria" (:version "fiveam" "1.4") (:version "parser.common-rules/test" "0.3") "language.smarts") :components ((:module "test" :pathname "test/smarts" :serial t :components ((:file "package"))) (:module "parser" :depends-on ("test") :pathname "test/smarts/parser" :serial t :components ((:file "package") (:file "grammar" )))) :perform (test-op (operation component) (uiop:symbol-call '#:language.smarts.test '#:run-tests)))
1,727
Common Lisp
.asd
35
35.742857
99
0.47707
scymtym/language.smarts
3
1
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
19bc111f3df744b8a7e041b63a112ec1f0bb42476c2c34eacd3d044a6e92f764
18,377
[ -1 ]
18,407
package.lisp
ikbenlike_cl-keycloak/package.lisp
;;;; package.lisp (defpackage #:cl-keycloak (:use #:cl) (:export #:register-client #:get-well-known #:get-auth-redirect #:get-user-info #:with-client #:request-token #:client-id #:client-secret #:server-url #:key-realm #:logout-user))
350
Common Lisp
.lisp
14
15.785714
30
0.486567
ikbenlike/cl-keycloak
3
0
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
e56133d9c4d7073dbf6237912af0b974f7db56851a3d49b4cd005ea7ed8bc67a
18,407
[ -1 ]
18,408
authenticate.lisp
ikbenlike_cl-keycloak/authenticate.lisp
(in-package #:cl-keycloak) (defclass client () ((client-id :initarg :client-id :accessor client-id) (client-secret :initarg :client-secret :accessor client-secret) (server-url :initarg :server-url :accessor server-url) (key-realm :initarg :key-realm :accessor key-realm) (server-settings :initarg nil :accessor server-settings))) (defun request-configuration (client) (setf (server-settings client) (yason:parse (flexi-streams:octets-to-string (drakma:http-request (format nil "~a/realms/~a/.well-known/openid-configuration" (server-url client) (key-realm client))))))) (defun register-client (&key client-id client-secret server-url key-realm) (let ((client (make-instance 'client :client-id client-id :client-secret client-secret :server-url server-url :key-realm key-realm))) (request-configuration client) client)) (defun get-well-known (client well-known) (gethash well-known (server-settings client))) (defmacro with-client (name args &body body) `(let ((,name (register-client ,@args))) ,@body)) (defun get-auth-redirect (client &key scope redirect) (format nil "~a?~a" (get-well-known client "authorization_endpoint") (url-encode `("client_id" . ,(client-id client)) `("response_type" . "code") `("scope" . ,(or scope "openid")) `("redirect_uri" . ,redirect)))) (defun request-token (client code redirect) (yason:parse (flexi-streams:octets-to-string (drakma:http-request (get-well-known client "token_endpoint") :method :post :parameters `(("grant_type" . "authorization_code") ("code" . ,code) ("redirect_uri" . ,redirect) ("client_id" . ,(client-id client)) ("client_secret" . ,(client-secret client))))))) (defun get-user-info (client token) (yason:parse (flexi-streams:octets-to-string (drakma:http-request (get-well-known client "userinfo_endpoint") :method :get :additional-headers `(("Authorization" . ,(format nil "Bearer ~a" token))))))) (defun logout-user (client token) (let ((response (drakma:http-request (get-well-known client "end_session_endpoint") :method :post :parameters `(("refresh_token" . ,token) ("client_id" . ,(client-id client)) ("client_secret" . ,(client-secret client)))))) (if (= 0 (length response)) nil (yason:parse (flexi-streams:octets-to-string response)))))
2,872
Common Lisp
.lisp
74
28.783784
86
0.570814
ikbenlike/cl-keycloak
3
0
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
6a79f50f22b37e29e579cac0cfc2ac7b901a75705f98ddcbee567daca85dfe5d
18,408
[ -1 ]
18,409
cl-keycloak.asd
ikbenlike_cl-keycloak/cl-keycloak.asd
;;;; cl-keycloak.asd (asdf:defsystem #:cl-keycloak :description "Describe cl-keycloak here" :author "Your Name <[email protected]>" :license "GPLv3" :version "0.0.1" :serial t :depends-on (#:drakma #:flexi-streams #:yason) :components ((:file "package") (:file "authenticate") (:file "url-encode")))
350
Common Lisp
.asd
11
26.727273
48
0.627219
ikbenlike/cl-keycloak
3
0
1
GPL-3.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2340741b08d81befeeb4156dc7ac14820f2c1c1fac958c3864173f189a04d5c1
18,409
[ -1 ]
18,429
movitz-render.lisp
spacebat_lice/src/movitz-render.lisp
(in-package "LICE") ;; TTY rendering routines (in-package "LICE") (defclass movitz-frame (frame) ((double-buffer :type (array character 1) :initarg :double-buffer :accessor frame-double-buffer :documentation "The display double buffer. This structure is compared to the characters we want to blit. Only differences are sent to the video hardware.") ;; (2d-double-buffer :type (array character 2) :initarg :2d-double-buffer :accessor frame-2d-double-buffer :documentation ;; "Displaced from DISPLAY. This array is divided into rows and columns.") )) (defmethod frame-start-render ((frame movitz-frame)) ) (defmethod frame-end-render ((frame movitz-frame)) ) (defvar *current-attribute* 0 "The currently set character attribute. Used while rendering a window.") (defun window-move-cursor (window x y) (muerte.x86-pc::move-vga-cursor (+ x (window-x window)) (+ y (window-y window)))) (defmethod frame-move-cursor ((frame movitz-frame) win x y) (window-move-cursor win x y)) (defun setxy (x y n) "A very raw character & attribute blitter" (setf (muerte::memref-int muerte.x86-pc::*screen* :index (+ x (* y muerte.x86-pc::*screen-stride*)) :type :unsigned-byte16) n)) (defun set-char-attr (x y ch attr) "" (setxy x y (logior (ash attr 8) (char-code ch)))) (defun putch (ch x y window frame) (set-char-attr (+ x (window-x window)) (+ y (window-y window)) ch *current-attribute*) (setf (aref (frame-double-buffer frame) (+ (* (+ y (window-y window)) (frame-width frame)) (+ x (window-x window)))) ch)) (defun putstr (s x y w frame) (loop for i from 0 below (length s) for j from x by 1 ;;if (char/= (aref (window-2d-display w) y j) (aref s i)) do (putch (aref s i) j y w frame))) (defun clear-line-between (w y start end frame) "insert LEN spaces from START on line Y." ;;(window-move-cursor w start y) ;; FIXME: this could be done faster (loop for i from start to end do (putch #\Space i y w frame))) ;; Helper function for window-render (defun clear-to-eol (y start window frame) (declare (type window window) (type fixnum y start)) (let (;; (display (frame-2d-double-buffer frame)) ;; (linear (frame-double-buffer frame)) ) (clear-line-between window y start (1- (window-width window nil)) frame) ;; draw the seperator (when (window-seperator window) (putch #\| (+ (window-x window) (1- (window-width window t))) y window frame)))) (defun turn-on-attributes (buffer point) "Given the buffer and point, turn on the appropriate colors based on the text properties present." ;; These are hardcoded for now (setf *current-attribute* (case (get-text-property point :face buffer) (:face-1 7) (:face-2 112) (:face-3 14) (:face-4 34) (:face-5 8) (:face-6 9) (:face-7 2) (:face-8 1) (t 7)))) (defmethod window-render (w (frame movitz-frame)) "Render a window." (let ((p (buffer-char-to-aref (window-buffer w) (marker-position (window-top w)))) ;; current point in buffer buffer (bp (marker-position (window-top w))) (buf (window-buffer w)) ;; The cursor point in the buffer. When the buffer isn't ;; current, then use the window's backup of the point. (point (window-point w)) cursor-x cursor-y (cache-size (length (lc-cache (window-cache w)))) (linear (frame-double-buffer frame)) ;; (display (frame-2d-double-buffer frame)) ) ;; rxvt draws black on black if i don't turn on a color (setf *current-attribute* 7) ;; Special case: when the buffer is empty (if (= (buffer-size (window-buffer w)) 0) (progn (dotimes (y (window-height w nil)) (clear-to-eol y 0 w frame)) (setf cursor-x 0 cursor-y 0)) (let ((end (loop named row for y below (window-height w nil) for line from (window-top-line w) below cache-size ;; return the last line, so we can erase the rest finally (return-from row y) ;; go to the next line do (let* ((line-end (cache-item-end (item-in-cache w line))) (line-start (cache-item-start (item-in-cache w line))) (next-prop (next-single-property-change line-start :face (window-buffer w) line-end))) (setf bp (cache-item-start (item-in-cache w line)) p (buffer-char-to-aref (window-buffer w) bp)) ;; setup the display properties. (turn-on-attributes (window-buffer w) bp) (loop named col for x below (window-width w nil) do (progn ;; Skip the gap (when (= p (buffer-gap-start buf)) (incf p (buffer-gap-size buf))) ;; Record point position on screen (when (eq bp point) (setf cursor-x x) (setf cursor-y y)) (when (or (> bp line-end) (>= p (length (buffer-data buf)))) ;; gotta turn off attributes to do this (setf *current-attribute* 7) ;; Check if the rest of the line is blank (clear-to-eol y x w frame) (return-from col)) ;; update attributes (when (>= bp next-prop) (turn-on-attributes (window-buffer w) bp)) (let ((ch (elt (buffer-data buf) p))) ;; Update display (cond ((char= ch #\Newline) (putch #\Space x y w frame)) (t (putch ch x y w frame))) ;; go to the next character in the buffer (incf p) (incf bp)))))))) ;; Check if the bottom of the window needs to be erased. (when (< end (1- (window-height w nil))) (loop for i from end below (window-height w nil) do (clear-to-eol i 0 w frame))))) ;; rxvt draws black on black if i don't turn on a color (setf *current-attribute* 7) ;; Update the mode-line if it exists. FIXME: Not the right place ;; to update the mode-line. (when (buffer-mode-line (window-buffer w)) (update-mode-line (window-buffer w)) ;;(cl-ncurses::attron cl-ncurses::A_REVERSE) (setf *current-attribute* 18) (putstr (truncate-mode-line (window-buffer w) (window-width w nil)) 0 (window-height w nil) w frame) (setf *current-attribute* 7) ;;(cl-ncurses::attroff cl-ncurses::A_REVERSE) ;; don't forget the seperator on the modeline line (when (window-seperator w) (putch #\| (+ (window-x w) (window-width w nil)) (window-height w nil) w frame))) (reset-line-state w) ;; Set the cursor at the right spot (values cursor-x cursor-y))) ;;; keyboard stuff (defmethod frame-read-event ((frame movitz-frame)) "Return a key structure." (let (control meta shift) (loop (multiple-value-bind (key release) (muerte.x86-pc.keyboard::get-key) (when (and key (characterp key) (not release)) (return-from frame-read-event (make-key :char key :control (logbitp muerte.x86-pc.keyboard::+qualifier-ctrl+ muerte.x86-pc.keyboard::*qualifier-state*) :meta (logbitp muerte.x86-pc.keyboard::+qualifier-alt+ muerte.x86-pc.keyboard::*qualifier-state*)))))))) ;;; some frame stuff (defun init-movitz () ) (defun shutdown-movitz () ) (defun make-default-movitz-frame (buffer) (let* ((lines muerte.x86-pc::*screen-height*) (height (1- lines)) (cols muerte.x86-pc::*screen-width*) (l (make-array (* lines cols) :element-type 'character)) ;; (d (make-array (list lines cols) ;; :element-type 'character ;; :displaced-to l :displaced-index-offset 0)) (w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer)) (mb (make-minibuffer-window lines cols)) (frame (make-instance 'movitz-frame :width cols :height lines :window-tree (list w mb) :selected-window w :minibuffer-window mb :double-buffer l ;; :2d-double-buffer d ))) (setf (window-frame w) frame (window-frame mb) frame) frame)) ;; (defun make-test-frame (buffer) ;; "This can be used to create a frame configuration for testing." ;; (let* ((lines 20) ;; (height (1- lines)) ;; (cols 78) ;; (l (make-array (* lines cols) ;; :element-type 'character ;; :initial-element #\Space)) ;; (d (make-array (list lines cols) ;; :element-type 'character ;; :displaced-to l :displaced-index-offset 0)) ;; (w (make-window :x 0 :y 0 :cols cols :rows height :buffer buffer)) ;; (mb (make-minibuffer-window lines cols)) ;; (frame (make-instance 'tty-frame ;; :width cols ;; :height lines ;; :window-tree (list w mb) ;; :current-window w ;; :minibuffer-window mb ;; :double-buffer l ;; :2d-double-buffer d))) ;; (setf (window-frame w) frame ;; (window-frame mb) frame) ;; frame)) (provide :lice-0.1/movitz-render)
8,911
Common Lisp
.lisp
224
34.178571
129
0.625924
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
cf1fad271a42aa2846b940e1bb8436648d5ba79fb08e27963b96aa750221e01b
18,429
[ -1 ]
18,430
syntax.lisp
spacebat_lice/src/syntax.lisp
;;; Cheap syntax functions (in-package "LICE") (defparameter +syntax-classes+ '(:whitespace :punctuation :word-constituent :symbol-constituent :open :close :quote :string :math :escape :character-quote :comment :end-comment :inherit :comment-fence :string-fence)) (deftype syntax-class () '(member :whitespace ; for a whitespace character :punctuation ; for random punctuation characters :word-constituent ; for a word constituent :symbol-constituent ; symbol constituent but not word constituent :open ; for a beginning delimiter :close ; for an ending delimiter :quote ; for a prefix character like Lisp ' :string ; for a string-grouping character like Lisp " :math ; for delimiters like $ in Tex. :escape ; for a character that begins a C-style escape :character-quote ; for a character that quotes the ; following character :comment ; for a comment-starting character :end-comment ; for a comment-ending character :inherit ; use the standard syntax table for ; this character :comment-fence ; Starts/ends comment which is ; delimited on the other side by any ; char with the same syntaxcode. :string-fence ; Starts/ends string which is delimited ; on the other side by any char with ; the same syntaxcode. )) (defclass syntax-table () ((hash :initform (make-hash-table :test 'equal) :initarg :hash :accessor syntax-table-hash) (parent :initform nil :initarg :parent :accessor syntax-table-parent)) (:documentation "A syntax table class.")) (defstruct syntax-descriptor (class nil :type syntax-class) ;; FIXME: this will be a bitvector at some point but for now just ;; make it a list. (flags nil :type list) ;; this is where the terminator paren char etc is stored extra) (defun set-raw-syntax-entry (table char descriptor) (setf (gethash char (syntax-table-hash table)) descriptor)) (defvar *syntax-code-object* (loop for i in +syntax-classes+ collect i collect (make-syntax-descriptor :class i :flags nil)) "A pool of syntax descriptors to be shared in the standard syntax table in an attempt to save memory. FIXME: premature optimization?") (defvar *standard-syntax-table* (let ((table (make-instance 'syntax-table :parent nil)) tmp) ;; Control characters should not be whitespace. (setf tmp (getf *syntax-code-object* :punctuation)) (loop for i below (char-code #\Space) do (set-raw-syntax-entry table (code-char i) tmp)) ;; Except that a few really are whitespace. (setf tmp (getf *syntax-code-object* :whitespace)) (set-raw-syntax-entry table #\Space tmp) (set-raw-syntax-entry table #\Tab tmp) (set-raw-syntax-entry table #\Newline tmp) (set-raw-syntax-entry table #\Return tmp) (set-raw-syntax-entry table #\Page tmp) (setf tmp (getf *syntax-code-object* :word-constituent)) (loop for i from (char-code #\a) to (char-code #\z) for j from (char-code #\A) to (char-code #\Z) do (set-raw-syntax-entry table (code-char i) tmp) (set-raw-syntax-entry table (code-char j) tmp)) (loop for i from (char-code #\0) to (char-code #\9) do (set-raw-syntax-entry table (code-char i) tmp)) (set-raw-syntax-entry table #\$ tmp) (set-raw-syntax-entry table #\% tmp) (set-raw-syntax-entry table #\( (make-syntax-descriptor :class :open :extra ")")) (set-raw-syntax-entry table #\) (make-syntax-descriptor :class :close :extra "(")) (set-raw-syntax-entry table #\[ (make-syntax-descriptor :class :open :extra "]")) (set-raw-syntax-entry table #\] (make-syntax-descriptor :class :close :extra "[")) (set-raw-syntax-entry table #\{ (make-syntax-descriptor :class :open :extra "}")) (set-raw-syntax-entry table #\} (make-syntax-descriptor :class :close :extra "{")) (set-raw-syntax-entry table #\" (make-syntax-descriptor :class :string)) (set-raw-syntax-entry table #\\ (make-syntax-descriptor :class :escape)) (setf tmp (getf *syntax-code-object* :symbol-constituent)) (loop for i across "_-+*/&|<>=" do (set-raw-syntax-entry table i tmp)) (setf tmp (getf *syntax-code-object* :punctuation)) (loop for i across ".,;:?!#@~^'`" do (set-raw-syntax-entry table i tmp)) ;; TODO: i18n characters table) "The standard syntax table") (defun make-syntax-table (&optional (parent *standard-syntax-table*)) "Return a new syntax table. Create a syntax table which inherits from parent (if non-nil) or from `standard-syntax-table' otherwise." (make-instance 'syntax-table :parent parent)) (defun copy-syntax-table (&optional (table *standard-syntax-table*)) "Construct a new syntax table and return it. It is a copy of the TABLE, which defaults to the standard syntax table." (let* ((hash (make-hash-table))) (maphash (lambda (k v) (setf (gethash k hash) v)) (syntax-table-hash table)) (make-instance 'syntax-table :hash hash :parent (syntax-table-parent table)))) (defun syntax-table (&aux (buffer (current-buffer))) (buffer-syntax-table buffer)) (defun modify-syntax-entry (char class &key flags extra (table (syntax-table))) "Set syntax for character CHAR according to CLASS, FLAGS, and EXTRA." (check-type char character) (check-type class syntax-class) (check-type flags list) (check-type table syntax-table) (set-raw-syntax-entry table char (make-syntax-descriptor :class class :flags flags :extra extra))) (defun char-syntax (character &optional (table (syntax-table))) "Return the syntax code of CHARACTER, described by a character. For example, if CHARACTER is a word constituent, the symbol `:WORD-CONSTITUENT' is returned." (let ((descr (gethash character (syntax-table-hash table)))) (when descr (syntax-descriptor-class descr)))) (defparameter +word-constituents+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") (defvar *words-include-escapes* nil "Non-nil means `forward-word', etc., should treat escape chars part of words.") (defun syntax-after (pos &aux (buffer (current-buffer))) "Return the raw syntax of the char after POS. If POS is outside the buffer's accessible portion, return nil." (unless (or (< pos (begv buffer)) (>= pos (zv buffer))) (let* ((ch (buffer-char-after buffer pos)) (descr (and ch (gethash ch (syntax-table buffer))))) descr))) ;; FIXME: having the flags as a list is memory intensive. How about a ;; bit vector or number and a function that converts between the two? (defun (setf syntax-table) (value &aux (buffer (current-buffer))) "Select a new syntax table for the current buffer. One argument, a syntax table." (check-type value syntax-table) (setf (buffer-syntax-table buffer) value)) (depricate set-syntax-table (setf syntax-table)) (defun set-syntax-table (value) "Select a new syntax table for the current buffer. One argument, a syntax table." (setf (syntax-table) value)) (defun &syntax-with-flags (ch table &optional (default :whitespace)) (or (gethash ch (syntax-table-hash table)) ;; try the parent (and (syntax-table-parent table) (&syntax-with-flags ch (syntax-table-parent table) default)) ;; return the default (make-syntax-descriptor :class default))) (defun &syntax (ch table &optional (default :whitespace)) (let ((descr (&syntax-with-flags ch table default))) (if descr (syntax-descriptor-class descr) default))) (defun &syntax-flags-syntax (syntax) (syntax-descriptor-class syntax)) (defun &syntax-comment-start-first (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-start-first (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-start-first (syntax) (and (find :comment-start-first (syntax-descriptor-flags syntax)) t)) (defun &syntax-comment-start-second (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-start-second (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-start-second (syntax) (and (find :comment-start-second (syntax-descriptor-flags syntax)) t)) (defun &syntax-comment-end-first (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-end-first (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-end-first (syntax) (and (find :comment-end-first (syntax-descriptor-flags syntax)) t)) (defun &syntax-comment-end-second (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-end-second (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-end-second (syntax) (and (find :comment-end-second (syntax-descriptor-flags syntax)) t)) (defun &syntax-prefix (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :prefix (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-prefix (syntax) (and (find :prefix (syntax-descriptor-flags syntax)) t)) (defun &syntax-comment-style (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-style (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-style (syntax) (and (find :comment-style (syntax-descriptor-flags syntax)) t)) (defun &syntax-comment-nested (ch table) (let ((descr (&syntax-with-flags ch table))) (when descr (and (find :comment-nested (syntax-descriptor-flags descr)) t)))) (defun &syntax-flags-comment-nested (syntax) (and (find :comment-nested (syntax-descriptor-flags syntax)) t)) (defmacro with-syntax-table (table &body body) "Evaluate BODY with syntax table of current buffer set to TABLE. The syntax table of the current buffer is saved, BODY is evaluated, and the saved table is restored, even in case of an abnormal exit. Value is what BODY returns." (let ((old-table (gensym "TABLE")) (old-buffer (gensym "BUFFER"))) `(let ((,old-table (syntax-table)) (,old-buffer (current-buffer))) (unwind-protect (progn (set-syntax-table ,table) ,@body) (save-current-buffer (set-buffer ,old-buffer) (set-syntax-table ,old-table)))))) (defun syntax-class (syntax) "Return the syntax class part of the syntax descriptor SYNTAX. If SYNTAX is nil, return nil." (&syntax-flags-syntax syntax)) (defun scan-words (from count) "Return the position across COUNT words from FROM. If that many words cannot be found before the end of the buffer, return NIL. COUNT negative means scan backward and stop at word beginning." (let* ((buffer (current-buffer)) (beg (begv buffer)) (end (zv buffer)) (from-aref (buffer-char-to-aref buffer from)) (table (syntax-table)) ch code) (while (> count 0) (loop (when (= from end) (return-from scan-words nil)) (setf ch (buffer-fetch-char from-aref buffer) code (&syntax ch table)) (inc-both from from-aref buffer) (when (or (and *words-include-escapes* (or (eq code :escape) (eq code :character-quote))) (eq code :word-constituent)) (return nil))) (loop (when (= from end) (return nil)) (setf ch (buffer-fetch-char from-aref buffer) code (&syntax from-aref table)) (when (and (and (not *words-include-escapes*) (or (eq code :escape) (eq code :character-quote))) (or (not (eq code :word-constituent)))) ;; (word-boundary-p ..) (return nil)) (inc-both from from-aref buffer)) (decf count)) (while (< count 0) (loop (when (= from beg) (return-from scan-words nil)) (dec-both from from-aref buffer) (setf ch (buffer-fetch-char from-aref buffer) code (&syntax ch table)) (when (or (and *words-include-escapes* (or (eq code :escape) (eq code :character-quote))) (eq code :word-constituent)) (return nil))) (loop (when (= from beg) (return nil)) (setf ch (buffer-fetch-char from-aref buffer) code (&syntax ch table)) (when (and (and (not *words-include-escapes*) (or (eq code :escape) (eq code :character-quote))) (not (eq code :word-constituent))) (return nil)) (dec-both from from-aref buffer)) (incf count)) from)) (defvar *parse-sexp-ignore-comments* t "Non-nil means `forward-sexp', etc., should treat comments as whitespace.") (defvar *open-paren-in-column-0-is-defun-start* t "*Non-nil means an open paren in column 0 denotes the start of a defun.") ;; Conditions used by the syntax code because the parsing is so bloody ;; hairy. (define-condition syntax-done () ()) (define-condition syntax-lossage () ()) (define-condition expression-ends-prematurely (lice-condition) ()) (define-condition unbalanced-parenthesis (lice-condition) ((last-good :initarg :last-good :accessor unbalanced-parenthesis-last-good) (from :initarg :from :accessor unbalanced-parenthesis-from))) (defun &char-quoted (char-pos aref-pos buffer table) "Returns TRUE if char at CHAR-POS is quoted. Global syntax-table data should be set up already to be good at CHAR-POS or after. On return global syntax data is good for lookup at CHAR-POS." (let ((beg (begv buffer)) quoted) (dec-both char-pos aref-pos buffer) (while (>= char-pos beg) (let* ((ch (buffer-fetch-char aref-pos buffer)) (code (&syntax ch table))) (when (not (find code '(:character-quote :escape))) (return nil)) (dec-both char-pos aref-pos buffer) (setf quoted (not quoted)))) quoted)) (defstruct parse-state buffer depth min-depth this-level-start prev-level-start location level-starts quoted in-comment comment-style comment-string-start in-string start-value start-value-aref) (defun find-defun-start (pos pos-aref buffer table) "Return a defun-start position before POS and not too far before. It should be the last one before POS, or nearly the last. When open_paren_in_column_0_is_defun_start is nonzero, only the beginning of the buffer is treated as a defun-start. We record the information about where the scan started and what its result was, so that another call in the same area can return the same value very quickly. There is no promise at which position the global syntax data is valid on return from the subroutine, so the caller should explicitly update the global data." (declare (ignore pos-aref)) (unless *open-paren-in-column-0-is-defun-start* (return-from find-defun-start (make-parse-state :start-value (begv buffer) :start-value-aref (begv-aref buffer)))) ;; Back up to start of line. (let* ((begv (begv buffer)) (pt (buffer-scan-newline buffer pos (begv buffer) -1)) (pt-aref (buffer-char-to-aref buffer pt))) (while (> pt begv) (let ((ch (buffer-fetch-char pt-aref buffer))) (when (eq (&syntax ch table) :open) (return nil)) ;; Move to beg of previous line. (setf pt (buffer-scan-newline buffer pt (begv buffer) -2) pt-aref (buffer-char-to-aref buffer pt)))) ;; Return what we found (make-parse-state :start-value pt :start-value-aref pt-aref :buffer buffer ;; :modiff MODIFF :start-begv (begv buffer) :start-pos pos))) ;; FIXME: doesn't handle ^. Maybe if :not is the first symbol in the list? (defun skip-syntax-forward (syntax-list &optional (lim (zv))) "Move point forward across chars in specified syntax classes. SYNTAX-LIST is a string of syntax code characters. Stop before a char whose syntax is not in SYNTAX-LIST, or at position LIM. If SYNTAX-LIST starts with ^, skip characters whose syntax is NOT in SYNTAX-LIST. This function returns the distance traveled, either zero or positive." (check-type lim integer) (let* ((buffer (current-buffer)) (table (syntax-table)) (pos (pt)) (start pos) (pos-aref (buffer-char-to-aref buffer pos)) ch syntax) (while (< pos lim) (setf ch (buffer-fetch-char pos-aref buffer) syntax (&syntax ch table)) (unless (find syntax syntax-list) (return nil)) (inc-both pos pos-aref buffer)) (goto-char pos) (- pos start))) (defun skip-chars (forwardp syntaxp string lim) (declare (ignore syntaxp)) (labels ((match-char (c negate ranges chars) ;; check ranges (catch :continue (loop for r in ranges do (if negate (when (<= (car r) (char-code c) (cdr r)) (throw :done nil)) (when (<= (car r) (char-code c) (cdr r)) (throw :continue nil)))) ;; check chars (if negate (when (find c chars :test 'char=) (throw :done nil)) (when (find c chars :test 'char=) (throw :continue nil))) (unless negate ;; if the char fell through all that then we're done (throw :done nil))))) (check-type string string) (check-number-coerce-marker lim) (let ((idx 0) negate ranges chars (start-point (pt))) ;; don't allow scan outside bounds of buffer. (setf lim (min (max lim (begv)) (zv))) (when (char= (char string 0) #\^) (setf negate t) (incf idx)) ;; compile the ranges and chars (while (< idx (length string)) (let ((c (char string idx))) ;; (if syntaxp ;; ;; TODO: handle syntaxp ;; nil ;; (progn ;; ;; TODO: handle iso classes ;; )) (when (char= c #\\) (incf idx) (when (= idx (length string)) (return nil)) (setf c (char string idx))) (incf idx) ;; Treat `-' as range character only if another character ;; follows. (if (and (< (1+ idx) (length string)) (char= (char string idx) #\-)) (progn (incf idx) (let* ((c2 (char string idx)) (code1 (char-code c)) (code2 (char-code c2))) (when (<= code1 code2) (push (cons code1 code2) ranges)) (incf idx))) (progn (push c chars))))) ;; scan (let* ((buffer (current-buffer)) (pos (pt buffer)) (pos-aref (buffer-char-to-aref buffer pos))) (catch :done (if forwardp (while (< pos lim) (match-char (buffer-fetch-char pos-aref buffer) negate ranges chars) (inc-both pos pos-aref buffer)) (progn ;; do a little dance to end up in the right spot (dec-both pos pos-aref buffer) (unwind-protect (while (> pos lim) (match-char (buffer-fetch-char pos-aref buffer) negate ranges chars) (dec-both pos pos-aref buffer)) (inc-both pos pos-aref buffer))))) (set-point pos buffer) ;; return the number of chars we scanned (- pos start-point))))) (defun skip-chars-forward (string &optional (lim (zv))) "Move point forward, stopping before a char not in string." (skip-chars t nil string lim)) (defun skip-chars-backward (string &optional (lim (begv))) "Move point backward, stopping after a char not in string." (skip-chars nil nil string lim)) (defun skip-whitespace-forward (&optional (lim (zv))) "Move point forward, stopping before a char that is not a space or tab." (skip-chars-forward (coerce '(#\Space #\Tab) 'string) lim)) (defun &forward-comment (from from-aref stop nesting style prev-syntax buffer table) "Jump over a comment, assuming we are at the beginning of one. FROM is the current position. FROM_BYTE is the bytepos corresponding to FROM. Do not move past STOP (a charpos). The comment over which we have to jump is of style STYLE (either SYNTAX_COMMENT_STYLE(foo) or ST_COMMENT_STYLE). NESTING should be positive to indicate the nesting at the beginning for nested comments and should be zero or negative else. ST_COMMENT_STYLE cannot be nested. PREV_SYNTAX is the SYNTAX_WITH_FLAGS of the previous character (or nil If the search cannot start in the middle of a two-character). If successful, return 1 and store the charpos of the comment's end into *CHARPOS_PTR and the corresponding bytepos into *BYTEPOS_PTR. Else, return 0 and store the charpos STOP into *CHARPOS_PTR, the corresponding bytepos into *BYTEPOS_PTR and the current nesting (as defined for state.incomment) in *INCOMMENT_PTR. The comment end is the last character of the comment rather than the character just after the comment. Global syntax data is assumed to initially be valid for FROM and remains valid for forward search starting at the returned position." (let (c c1 code (syntax prev-syntax)) (labels ((forward () (when (= from stop) (return-from &forward-comment (values nil from from-aref nesting))) (setf c (buffer-fetch-char from-aref buffer) code (&syntax c table) syntax (&syntax-with-flags c table)) (when (and (eq code :end-comment) (eq (&syntax-flags-comment-style syntax) style) (if (&syntax-flags-comment-nested syntax) (and (> nesting 0) (progn (decf nesting) (zerop nesting))) (< nesting 0))) ;; we have encountered a comment end of the same ;; style as the comment sequence which began this ;; comment section. (throw :done nil)) (when (and (eq code :comment-fence) (eq style :st-comment-style)) ;; we have encountered a comment end of the same style ;; as the comment sequence which began this comment ;; section. (throw :done nil)) (when (and (> nesting 0) (eq code :comment) (&syntax-flags-comment-nested syntax) (eq (&syntax-flags-comment-style syntax) style)) ;; we have encountered a nested comment of the same style ;; as the comment sequence which began this comment section (incf nesting)) (inc-both from from-aref buffer)) (do-comment () (when (and (< from stop) (&syntax-flags-comment-end-first syntax) (eq (&syntax-flags-comment-style syntax) style) (progn (setf c1 (buffer-fetch-char from-aref buffer)) (&syntax-comment-end-second c1 table)) (if (or (&syntax-flags-comment-nested syntax) (&syntax-comment-nested c1 table)) (> nesting 0) (< nesting 0))) (decf nesting) (if (<= nesting 0) ;; we have encountered a comment end of the same style ;; as the comment sequence which began this comment ;; section (throw :done nil) (inc-both from from-aref buffer))) (when (and (> nesting 0) (< from stop) (&syntax-flags-comment-start-first syntax) (progn (setf c1 (buffer-fetch-char from-aref buffer)) (eq (&syntax-comment-style c1 table) style)) (or (&syntax-flags-comment-nested syntax) (&syntax-comment-nested c1 table))) ;; we have encountered a nested comment of the same style ;; as the comment sequence which began this comment ;; section (inc-both from from-aref buffer) (incf nesting)))) ;; normalize nesting (cond ((or (null nesting) (<= nesting 0)) (setf nesting -1)) ((not (numberp nesting)) (setf nesting 1))) ;; Enter the loop in the middle so that we find ;; a 2-char comment ender if we start in the middle of it. (catch :done (if syntax (progn (do-comment) (loop (forward) (do-comment))) (loop (forward) (do-comment)))) (values t from from-aref)))) (defstruct syntax-level last prev) ;; this function cries out for continuations. you almost have to look ;; at the C code to understand what's going on here, i bet. Hell, I ;; don't even understand it. (defun scan-sexps-forward (from from-aref end target-depth stop-before old-state comment-stop buffer table) "Parse forward from FROM / FROM_BYTE to END, assuming that FROM has state OLDSTATE (nil means FROM is start of function), and return a description of the state of the parse at END. If STOPBEFORE is nonzero, stop at the start of an atom. If COMMENTSTOP is 1, stop at the start of a comment. If COMMENTSTOP is -1, stop at the start or end of a comment, after the beginning of a string, or after the end of a string." ;;(message "scan-sexps-forward ~@{~a ~}" from from-aref end target-depth stop-before old-state comment-stop buffer table) (let ((state (make-parse-state)) (prev-from from) (prev-from-aref from-aref) prev-from-syntax (boundary-stop (null comment-stop)) no-fence c1 code comment-nested depth min-depth temp start-quoted levels) (labels ((inc-from () (setf prev-from from prev-from-aref from-aref temp (buffer-fetch-char prev-from-aref buffer) prev-from-syntax (&syntax-with-flags temp table)) (inc-both from from-aref buffer)) (cur-level () "Return the current level struct" (car levels)) (do-start-in-comment () ;; The (from == BEGV) test was to enter the loop in the middle so ;; that we find a 2-char comment ender even if we start in the ;; middle of it. We don't want to do that if we're just at the ;; beginning of the comment (think of (*) ... (*)). (multiple-value-bind (found out-char out-aref in-comment) (&forward-comment from from-aref end (parse-state-in-comment state) (parse-state-comment-style state) (if (or (eq from (begv buffer)) (< from (+ (parse-state-comment-string-start state) 3))) nil prev-from-syntax) buffer table) (setf from out-char from-aref out-aref (parse-state-in-comment state) in-comment) ;; Beware! prev_from and friends are invalid now. ;; Luckily, the `done' doesn't use them and the INC_FROM ;; sets them to a sane value without looking at them. (unless found (throw :end :done)) (inc-from) (setf (parse-state-in-comment state) nil (parse-state-comment-style state) nil) ; reset the comment style (when boundary-stop (throw :end :done)))) (do-sym-done () ;;(message "do-sym-done ~s" (parse-state-level-starts state)) (setf (syntax-level-prev (cur-level)) (syntax-level-last (cur-level)))) (do-sym-started () ;; (message "do-sym-started") (while (< from end) (case (&syntax (buffer-fetch-char from-aref buffer) table) ((:escape :character-quote) (inc-from) (when (= from end) (throw :end :end-quoted))) ((:word-constituent :symbol-constituent :quote)) (t (do-sym-done) (return nil))) (inc-from))) (do-start-quoted () (when (= from end) (throw :end :end-quoted)) (inc-from) (do-sym-started)) (do-in-string-loop () (loop (let (c) (when (>= from end) (throw :end :done)) (setf c (buffer-fetch-char from-aref buffer) temp (&syntax c table)) ;; Check TEMP here so that if the char has ;; a syntax-table property which says it is NOT ;; a string character, it does not end the string. (when (and no-fence (equal c (parse-state-in-string state)) (eq temp :string)) (return nil)) (case temp (:string-fence (unless no-fence (return nil))) ((:character-quote :escape) (inc-from) (when (>= from end) (throw :end :end-quoted)))) (inc-from)))) (do-string-end () ;;(message "do-string-end ~s" (parse-state-level-starts state)) (setf (parse-state-in-string state) nil (syntax-level-prev (cur-level)) (syntax-level-last (cur-level))) (inc-from) (when boundary-stop (throw :end :done))) (do-start-in-string () (setf no-fence (not (eq (parse-state-in-string state) :st-string-style))) (do-in-string-loop) (do-string-end)) (do-start-quoted-in-string () (when (>= from end) (throw :end :end-quoted)) (inc-from) (do-in-string-loop))) (when (/= from (begv buffer)) (dec-both prev-from prev-from-aref buffer)) (if old-state (progn (setf state old-state start-quoted (parse-state-quoted state) depth (or (parse-state-depth state) 0) start-quoted (parse-state-quoted state)) (dolist (i (parse-state-level-starts state)) (push (make-syntax-level :last i) levels)) ;; make sure we have at least one in the list (unless levels (push (make-syntax-level) levels))) (setf depth 0 state (make-parse-state) levels (list (make-syntax-level)))) ;;(message "top ~s" (parse-state-level-starts state)) (setf (parse-state-quoted state) nil min-depth depth) (setf temp (buffer-fetch-char prev-from-aref buffer) prev-from-syntax (&syntax-with-flags temp table)) ;; "Enter" the loop at a place appropriate for initial state. In ;; the C code this is a bunch of goto's. Here we call the ;; appropriate function that sync's us so we're ready to enter ;; the loop. (cond ((parse-state-in-comment state) (do-start-quoted)) ((parse-state-in-string state) (setf no-fence (not (eq (parse-state-in-string state) :st-string-style))) (if start-quoted (do-start-quoted-in-string) (do-start-in-string))) (start-quoted (do-start-quoted))) ;; (message "sane here") (case (catch :end (while (< from end) (catch :continue (inc-from) (setf code (&syntax-flags-syntax prev-from-syntax)) ;; (message "here the code is ~s" code) (cond ((and (< from end) (&syntax-flags-comment-start-first prev-from-syntax) (progn (setf c1 (buffer-fetch-char from-aref buffer)) (&syntax-comment-start-second c1 table))) ;; (message "here 1") ;; Record the comment style we have entered so that only ;; the comment-end sequence of the same style actually ;; terminates the comment section. (setf (parse-state-comment-style state) (&syntax-comment-style c1 table) comment-nested (&syntax-flags-comment-nested prev-from-syntax) comment-nested (or comment-nested (&syntax-comment-nested c1 table)) (parse-state-in-comment state) comment-nested (parse-state-comment-string-start state) prev-from) (inc-from) (setf code :comment)) ((eq code :comment-fence) ;; (message "here 2") ;; Record the comment style we have entered so that only ;; the comment-end sequence of the same style actually ;; terminates the comment section. (setf (parse-state-comment-style state) :st-comment-style (parse-state-in-comment state) -1 ; XXX (parse-state-comment-string-start state) prev-from code :comment)) ((eq code :comment) ;; (message "here 3") (setf (parse-state-comment-style state) (&syntax-flags-comment-style prev-from-syntax) (parse-state-in-comment state) (&syntax-flags-comment-nested prev-from-syntax) (parse-state-comment-string-start state) prev-from))) (when (&syntax-flags-prefix prev-from-syntax) (throw :continue nil)) ;;(message "code: ~s" code) (case code ((:escape :character-quote) ;; this arg means stop at sexp start (when stop-before (throw :end :stop)) ;;(message ":escae ~s" (parse-state-level-starts state)) (setf (syntax-level-last (cur-level)) prev-from) (do-start-quoted)) ((:word-constituent :symbol-constituent) (when stop-before (throw :end :stop)) ;;(message ":word-con ~s" (parse-state-level-starts state)) (setf (syntax-level-last (cur-level)) prev-from) (do-sym-started)) ((:comment-fence :comment) (when (or comment-stop boundary-stop) (throw :end :done)) (do-start-in-comment)) (:open (when stop-before (throw :end :stop)) (incf depth) ;;(message ":open ~s" (parse-state-level-starts state)) (setf (syntax-level-last (cur-level)) prev-from) ;; (message ":open ~a" (parse-state-level-starts state)) (push (make-syntax-level) levels) ;; (when (> (length level-list) 100) ; XXX hardcoded ;; (error "nesting too deep for parser")) (when (= target-depth depth) (throw :end :done))) (:close (decf depth) (when (< depth min-depth) (setf min-depth depth)) (unless (= (length levels) 1) ;;(message "XXX: popping when levels is 1!") (pop levels)) (setf (syntax-level-prev (cur-level)) (syntax-level-last (cur-level))) (when (= target-depth depth) (throw :end :done))) ((:string :string-fence) (setf (parse-state-comment-string-start state) (1- from)) (when stop-before (throw :end :stop)) (setf (syntax-level-last (cur-level)) prev-from) (setf (parse-state-in-string state) (if (eq code :string) (buffer-fetch-char prev-from-aref buffer) :st-string-style)) (when boundary-stop (throw :end :done)) (do-start-in-string)) (:math ;; FIXME: We should do something with it. ) (t ;; Ignore whitespace, punctuation, quote, endcomment. )))) :done) (:stop ;; Here if stopping before start of sexp. ;; We have just fetched the char that starts it ;; but return the position before it. (setf from prev-from)) (:end-quoted (setf (parse-state-quoted state) t))) ;;(message ":end ~s" (parse-state-level-starts state)) ;; done (setf (parse-state-depth state) depth (parse-state-min-depth state) min-depth (parse-state-this-level-start state) (syntax-level-prev (cur-level)) (parse-state-prev-level-start state) (if (<= (length levels) 1) nil (syntax-level-last (second levels))) (parse-state-location state) from (parse-state-level-starts state) (mapcar 'syntax-level-last (cdr levels))) state))) (defun &back-comment (from from-aref stop comment-nested comment-style buffer table) "Checks whether charpos FROM is at the end of a comment. FROM_BYTE is the bytepos corresponding to FROM. Do not move back before STOP. Return a positive value if we find a comment ending at FROM/FROM_BYTE; return -1 otherwise. If successful, return the charpos of the comment's beginning, and the aref pos. **Global syntax data remains valid for backward search starting at **the returned value (or at FROM, if the search was not successful)." ;; Look back, counting the parity of string-quotes, ;; and recording the comment-starters seen. ;; When we reach a safe place, assume that's not in a string; ;; then step the main scan to the earliest comment-starter seen ;; an even number of string quotes away from the safe place. ;; ;; OFROM[I] is position of the earliest comment-starter seen ;; which is I+2X quotes from the comment-end. ;; PARITY is current parity of quotes from the comment end. (let ((string-style :none) (string-lossage nil) ;; Not a real lossage: indicates that we have passed a matching comment ;; starter plus a non-matching comment-ender, meaning that any matching ;; comment-starter we might see later could be a false positive (hidden ;; inside another comment). ;; Test case: { a (* b } c (* d *) (comment-lossage nil) (comment-end from) (comment-end-aref from-aref) (comment-start-pos 0) comment-start-aref ;; Place where the containing defun starts, ;; or nil if we didn't come across it yet. (defun-start 0) (defun-start-aref 0) code (nesting 1) ; current comment nesting ch (syntax nil)) (handler-case (progn ;; FIXME: A }} comment-ender style leads to incorrect behavior ;; in the case of {{ c }}} because we ignore the last two chars which are ;; assumed to be comment-enders although they aren't. ;; ;; At beginning of range to scan, we're outside of strings; ;; that determines quote parity to the comment-end. (while (/= from stop) (catch :continue (let (temp-aref prev-syntax com2start com2end) (dec-both from from-aref buffer) (setf prev-syntax syntax ch (buffer-fetch-char from-aref buffer) syntax (&syntax-with-flags ch table) code (&syntax ch table) ;; Check for 2-char comment markers. com2start (and (&syntax-flags-comment-start-first syntax) (&syntax-flags-comment-start-second prev-syntax) (eq comment-style (&syntax-flags-comment-style prev-syntax)) (eq (or (&syntax-flags-comment-nested prev-syntax) (&syntax-flags-comment-nested syntax)) comment-nested)) com2end (and (&syntax-flags-comment-end-first syntax) (&syntax-flags-comment-end-second prev-syntax))) ;; Nasty cases with overlapping 2-char comment markers: ;; - snmp-mode: -- c -- foo -- c -- ;; --- c -- ;; ------ c -- ;; - c-mode: *||* ;; |* *|* *| ;; |*| |* |*| ;; /// */ ;; If a 2-char comment sequence partly overlaps with ;; another, we don't try to be clever. (when (and (> from stop) (or com2end com2start)) (let ((next from) (next-aref from-aref) next-c next-syntax) (dec-both next next-aref buffer) (setf next-c (buffer-fetch-char next-aref buffer) next-syntax (&syntax-with-flags next-c table)) (when (or (and (or com2start comment-nested) (&syntax-flags-comment-end-second syntax) (&syntax-flags-comment-end-first next-syntax)) (and (or com2end comment-nested) (&syntax-flags-comment-start-second syntax) (eq comment-style (&syntax-flags-comment-style syntax)) (&syntax-flags-comment-start-first next-syntax))) (signal 'syntax-lossage)))) (when (and com2start (= comment-start-pos 0)) ;; We're looking at a comment starter. But it might be a comment ;; ender as well (see snmp-mode). The first time we see one, we ;; need to consider it as a comment starter, ;; and the subsequent times as a comment ender. (setf com2end 0)) ;; Turn a 2-char comment sequences into the appropriate syntax. (cond (com2end (setf code :end-comment)) (com2start (setf code :comment)) ;; Ignore comment starters of a different style. ((and (eq code :comment) (or (not (eq comment-style (&syntax-flags-comment-style syntax))) (not (eq comment-nested (&syntax-flags-comment-nested syntax))))) (throw :continue nil))) ;; Ignore escaped characters, except comment-enders. (when (and (not (eq code :end-comment)) (&char-quoted from from-aref buffer table)) (throw :continue nil)) (case code ((:string-fence :comment-fence :string) (when (find code '(:string-fence :comment-fence)) (setf ch (if (eq code :string-fence) :string-style :comment-style))) ;; Track parity of quotes. (cond ((eq string-style :none) ;; Entering a string. (setf string-style ch)) ((eq string-style ch) ;; leaving the string (setf string-style :none)) (t ;; If we have two kinds of string delimiters. ;; There's no way to grok this scanning backwards. (setf string-lossage t)))) (:comment ;; We've already checked that it is the relevant comstyle. (when (or (eq string-style :none) comment-lossage string-lossage) ;; There are odd string quotes involved, so let's be careful. ;; Test case in Pascal: " { " a { " } */ (signal 'syntax-lossage)) (if (not comment-nested) ;; Record best comment-starter so far. (setf comment-start-pos from comment-start-aref from-aref) (progn (decf nesting) (when (<= nesting 0) ;; nested comments have to be balanced, so we don't need to ;; keep looking for earlier ones. We use here the same (slightly ;; incorrect) reasoning as below: since it is followed by uniform ;; paired string quotes, this comment-start has to be outside of ;; strings, else the comment-end itself would be inside a string. (signal 'syntax-done))))) (:end-comment (cond ((and (eq comment-style (&syntax-flags-comment-style syntax)) (or (and com2end (&syntax-flags-comment-nested prev-syntax)) (eq comment-nested (&syntax-flags-comment-nested syntax)))) ;; This is the same style of comment ender as ours. (if comment-nested (incf nesting) ;; Anything before that can't count because it would match ;; this comment-ender rather than ours. (setf from stop))) ((or (/= comment-start-pos 0) (char/= ch #\Newline)) ;; We're mixing comment styles here, so we'd better be careful. ;; The (comstart_pos != 0 || c != '\n') check is not quite correct ;; (we should just always set comment_lossage), but removing it ;; would imply that any multiline comment in C would go through ;; lossage, which seems overkill. ;; The failure should only happen in the rare cases such as ;; { (* } *) (setf comment-lossage t)))) (:open ;; Assume a defun-start point is outside of strings. (when (and *open-paren-in-column-0-is-defun-start* (or (= from stop) (progn (setf temp-aref (aref-minus-1 from-aref buffer)) (char= (buffer-fetch-char temp-aref buffer) #\Newline)))) (setf defun-start from defun-start-aref from-aref ;; Break out of the loop. from stop))))))) (if (= comment-start-pos 0) (setf from comment-end from-aref comment-end-aref) ;; If comstart_pos is set and we get here (ie. didn't jump to `lossage' ;; or `done'), then we've found the beginning of the non-nested comment. (setf from comment-start-pos from-aref comment-start-aref))) (syntax-lossage () ;; We had two kinds of string delimiters mixed up ;; together. Decode this going forwards. ;; Scan fwd from a known safe place (beginning-of-defun) ;; to the one in question; this records where we ;; last passed a comment starter. ;; If we did not already find the defun start, find it now. (when (= defun-start 0) (let ((ret (find-defun-start comment-end comment-end-aref buffer table))) (setf defun-start (parse-state-start-value ret) defun-start-aref (parse-state-start-value-aref ret)))) (loop do (let ((state (scan-sexps-forward defun-start defun-start-aref comment-end -10000 0 nil 0 buffer table))) (setf defun-start comment-end) (if (and (eq (parse-state-in-comment state) comment-nested) (eq (parse-state-comment-style state) comment-style)) (setf from (parse-state-comment-string-start state)) (progn (setf from comment-end) (when (parse-state-in-comment state) ; XXX ;; If comment_end is inside some other comment, maybe ours ;; is nested, so we need to try again from within the ;; surrounding comment. Example: { a (* " *) (setf defun-start (+ (parse-state-comment-string-start state) 2) defun-start-aref (buffer-char-to-aref buffer defun-start)))))) while (< defun-start comment-end)) (setf from-aref (buffer-char-to-aref buffer from)))) (values (if (= from comment-end) -1 from) from-aref))) (defun prev-char-comment-end-first (pos pos-aref buffer table) "Return the SYNTAX_COMEND_FIRST of the character before POS, POS_BYTE." (dec-both pos pos-aref buffer) (&syntax-comment-end-first (buffer-fetch-char pos-aref buffer) table)) (defun &scan-lists (from count depth sexpflag &aux (buffer (current-buffer))) "This is from the emacs function" ;; the big TODO here is to use the CL readtable (labels ((lose (last-good from) (signal 'unbalanced-parenthesis :last-good last-good :from from))) (let ((stop (if (> count 0) (zv buffer) (begv buffer))) (from-aref (buffer-char-to-aref buffer from)) (min-depth (min 0 depth)) (table (syntax-table)) (last-good from) quoted math-exit comment-start-first code ch ch1 temp-code temp-pos comment-nested comment-style found prefix) ;; normalize FROM (setf from (max (min (zv buffer) from) (begv buffer))) (while (> count 0) ;; the code needs to be able to jump out of the mess it got ;; in. (handler-case (progn (while (< from stop) (catch :continue (setf ch (buffer-fetch-char from-aref buffer) code (&syntax ch table) comment-start-first (&syntax-comment-start-first ch table) comment-nested (&syntax-comment-nested ch table) comment-style (&syntax-comment-style ch table) prefix (&syntax-prefix ch table)) (when (= depth min-depth) (setf last-good from)) (inc-both from from-aref buffer) (when (and (< from stop) comment-start-first (progn (setf ch (buffer-fetch-char from-aref buffer)) (&syntax-comment-start-second ch table)) *parse-sexp-ignore-comments*) ;; we have encountered a comment start sequence and ;; we are ignoring all text inside comments. We ;; must record the comment style this sequence ;; begins so that later, only a comment end of the ;; same style actually ends the comment section (setf code :comment ch1 (buffer-fetch-char from-aref buffer) comment-style (&syntax-comment-style ch1 table) comment-nested (or comment-nested (&syntax-comment-nested ch1 table))) (inc-both from from-aref buffer)) (when prefix (throw :continue nil)) (when (or (eq code :escape) (eq code :character-quote)) (when (= from stop) (lose last-good from)) (inc-both from from-aref buffer) ;; treat following character as a word constituent (setf code :word-constituent)) (case code ((:word-constituent :symbol-constituent) (unless (or (not (zerop depth)) (not sexpflag)) (let (temp) (while (< from stop) (setf ch (buffer-fetch-char from-aref buffer) temp (&syntax ch table)) (case temp ((:escape :character-quote) (inc-both from from-aref buffer) (when (= from stop) (lose last-good from))) ((:word-constituent :symbol-constituent :quote)) (t (signal 'syntax-done))) (inc-both from from-aref buffer))) (signal 'syntax-done))) ((:comment-fence :comment) (when (eq code :comment-fence) (setf comment-style :st-comment-style)) (multiple-value-setq (found from from-aref) (&forward-comment from from-aref stop comment-nested comment-style nil buffer table)) (unless found (when (zerop depth) (signal 'syntax-done)) (lose last-good from)) (inc-both from from-aref buffer)) (:math (when sexpflag (when (and (/= from stop) (char= ch (buffer-fetch-char from-aref buffer))) (inc-both from from-aref buffer)) (if math-exit (progn (setf math-exit nil) (decf depth) (when (zerop depth) (signal 'syntax-done)) (when (< depth min-depth) (signal 'expression-ends-prematurely))) ; XXX (progn (setf math-exit t) (incf depth) (when (zerop depth) (signal 'syntax-done)))))) (:open (incf depth) (when (zerop depth) (signal 'syntax-done))) (:close (decf depth) (when (zerop depth) (signal 'syntax-done)) (when (< depth min-depth) (signal 'expression-ends-prematurely))) ((:string :string-fence) (let* ((tmp-pos (aref-minus-1 from-aref buffer)) (string-term (buffer-fetch-char tmp-pos buffer)) temp) (loop (when (>= from stop) (lose last-good from)) (setf ch (buffer-fetch-char from-aref buffer)) (when (if (eq code :string) (and (char= ch string-term) (eq (&syntax ch table) :string)) (eq (&syntax ch table) :string-fence)) (return nil)) (setf temp (&syntax ch table)) (case temp ((:character-quote :escape) (inc-both from from-aref buffer))) (inc-both from from-aref buffer)) (inc-both from from-aref buffer) (when (and (zerop depth) sexpflag) (signal 'syntax-done)))) (t ;; Ignore whitespace, punctuation, quote, endcomment. )))) (unless (zerop depth) (lose last-good from)) (return-from &scan-lists nil)) (syntax-done () (decf count)))) (while (< count 0) (handler-case (progn (while (> from stop) (catch :continue (dec-both from from-aref buffer) (setf ch (buffer-fetch-char from-aref buffer) code (&syntax ch table)) (when (= depth min-depth) (setf last-good from)) (setf comment-style nil comment-nested (&syntax-comment-nested ch table)) (when (eq code :end-comment) (setf comment-style (&syntax-comment-style ch table))) (when (and (> from stop) (&syntax-comment-end-second ch table) (prev-char-comment-end-first from from-aref buffer table) *parse-sexp-ignore-comments*) ;; We must record the comment style ;; encountered so that later, we can match ;; only the proper comment begin sequence of ;; the same style. (dec-both from from-aref buffer) (setf code :end-comment ch1 (buffer-fetch-char from-aref buffer) comment-nested (or comment-nested (&syntax-comment-nested ch1 table)))) ;; Quoting turns anything except a comment-ender ;; into a word character. Note that this cannot ;; be true if we decremented FROM in the ;; if-statement above. (cond ((and (not (eq code :end-comment)) (&char-quoted from from-aref buffer table)) (dec-both from from-aref buffer) (setf code :word)) ((&syntax-prefix ch table) ;; loop around again. I think this is nasty but fuckit. (throw :continue nil))) (case code ((:word-constituent :symbol-constituent :escape :character-quote) (unless (or (not (zerop depth)) (not sexpflag)) ;; This word counts as a sexp; count ;; object finished after passing it. (while (> from stop) (setf temp-pos from-aref) (decf temp-pos) (setf ch1 (buffer-fetch-char temp-pos buffer) temp-code (&syntax ch1 table)) ;; Don't allow comment-end to be quoted. (when (eq temp-code :end-comment) (signal 'syntax-done)) (setf quoted (&char-quoted (1- from) temp-pos buffer table)) (when quoted (dec-both from from-aref buffer) (setf temp-pos (aref-minus-1 temp-pos buffer))) (setf ch1 (buffer-fetch-char temp-pos buffer) temp-code (&syntax ch1 table)) (when (not (or quoted (eq temp-code :word-constituent) (eq temp-code :symbol-constituent) (eq temp-code :quote))) (signal 'syntax-done)) (dec-both from from-aref buffer)) (signal 'syntax-done))) (:math (when sexpflag (setf temp-pos (aref-minus-1 from-aref buffer)) (when (and (/= from stop) (char= ch (buffer-fetch-char temp-pos buffer))) (dec-both from from-aref buffer)) (if math-exit (progn (setf math-exit nil) (decf depth) (when (zerop depth) (signal 'syntax-done)) (when (< depth min-depth) (signal 'expression-ends-prematurely))) (progn (setf math-exit t) (incf depth) (when (zerop depth) (signal 'syntax-done)))))) (:close (incf depth) (when (zerop depth) (signal 'syntax-done))) (:open (decf depth) (when (zerop depth) (signal 'syntax-done)) (when (< depth min-depth) (signal 'expression-ends-prematurely))) (:end-comment (when *parse-sexp-ignore-comments* (multiple-value-bind (found char-pos aref-pos) (&back-comment from from-aref stop comment-nested comment-style buffer table) (when (eq found :not-comment-end) (setf from char-pos from-aref aref-pos))))) ((:comment-fence :string-fence) (loop (when (= from stop) (lose last-good from)) (dec-both from from-aref buffer) (when (and (not (&char-quoted from from-aref buffer table)) (progn (setf ch (buffer-fetch-char from-aref buffer)) (eq (&syntax ch table) code))) (return nil))) (when (and (eq code :string-fence) (zerop depth) sexpflag) (signal 'syntax-done))) (:string (let ((string-term (buffer-fetch-char from-aref buffer))) (loop (when (= from stop) (lose last-good from)) (dec-both from from-aref buffer) (when (and (not (&char-quoted from from-aref buffer table)) (progn (setf ch (buffer-fetch-char from-aref buffer)) (char= string-term ch)) (eq (&syntax ch table) :string)) (return nil))) (when (and (zerop depth) sexpflag) (signal 'syntax-done)))) (t ;; Ignore whitespace, punctuation, quote, endcomment. )))) (when (not (zerop depth)) (lose last-good from)) (return-from &scan-lists nil)) (syntax-done () (incf count)))) from))) (defun scan-lists (from count depth) "Scan from character number FROM by COUNT lists. Returns the character number of the position thus found. If DEPTH is nonzero, paren depth begins counting from that value, only places where the depth in parentheses becomes zero are candidates for stopping; COUNT such places are counted. Thus, a positive value for DEPTH means go out levels. Comments are ignored if `*parse-sexp-ignore-comments*' is non-nil. If the beginning or end of (the accessible part of) the buffer is reached and the depth is wrong, an error is signaled. If the depth is right but the count is not used up, nil is returned." (check-type from number) (check-type count number) (check-type depth number) (&scan-lists from count depth nil)) (defun scan-sexps (from count) "Scan from character number FROM by COUNT balanced expressions. If COUNT is negative, scan backwards. Returns the character number of the position thus found. Comments are ignored if `parse-sexp-ignore-comments' is non-nil. If the beginning or end of (the accessible part of) the buffer is reached in the middle of a parenthetical grouping, an error is signaled. If the beginning or end is reached between groupings but before count is used up, nil is returned." (check-type from number) (check-type count number) (&scan-lists from count 0 t)) (defun backward-prefix-chars (&aux (buffer (current-buffer)) (table (syntax-table))) "Move point backward over any number of chars with prefix syntax. This includes chars with \"quote\" or \"prefix\" syntax (' or p)." (let* ((beg (begv buffer)) (pos (pt buffer)) (pos-aref (buffer-char-to-aref buffer pos)) (opoint (pt buffer)) (opoint-aref (buffer-char-to-aref buffer pos)) c) (when (<= pos beg) ;; SET_PT_BOTH (opoint, opoint_byte); (return-from backward-prefix-chars nil)) (dec-both pos pos-aref buffer) (while (and (not (&char-quoted pos pos-aref buffer table)) (progn (setf c (buffer-fetch-char pos-aref buffer)) (or (eq (&syntax c table) :quote) (&syntax-prefix c table)))) (setf opoint pos opoint-aref pos-aref) (when (> (1+ pos) beg) (dec-both pos pos-aref buffer))) (set-point-both buffer opoint opoint-aref) nil)) (defun parse-partial-sexp (from to &key (target-depth -100000) stop-before old-state comment-stop &aux (buffer (current-buffer)) (table (syntax-table))) "Parse Lisp syntax starting at FROM until TO; return status of parse at TO. Parsing stops at TO or when certain criteria are met; point is set to where parsing stops. If fifth arg OLDSTATE is omitted or nil, parsing assumes that FROM is the beginning of a function. Value is a list of elements describing final state of parsing: 0. depth in parens. parse-state-depth 1. character address of start of innermost containing list; nil if none. parse-state-prev-level-start 2. character address of start of last complete sexp terminated. parse-state-this-level-start 3. non-nil if inside a string. (it is the character that will terminate the string, or t if the string should be terminated by a generic string delimiter.) parse-state-in-string 4. nil if outside a comment, t if inside a non-nestable comment, else an integer (the current comment nesting). parse-state-in-comment 5. t if following a quote character. parse-state-quoted 6. the minimum paren-depth encountered during this scan. parse-state-min-depth 7. t if in a comment of style b; symbol `syntax-table' if the comment should be terminated by a generic comment delimiter. parse-state-comment-style 8. character address of start of comment or string; nil if not in one. parse-state-in-comment 9. Intermediate data for continuation of parsing (subject to change). parse-state-level-starts If third arg TARGETDEPTH is non-nil, parsing stops if the depth in parentheses becomes equal to TARGETDEPTH. Fourth arg STOPBEFORE non-nil means stop when come to any character that starts a sexp. Fifth arg OLDSTATE is a list like what this function returns. It is used to initialize the state of the parse. Elements number 1, 2, 6 and 8 are ignored. Sixth arg COMMENTSTOP non-nil means stop at the start of a comment. If it is symbol `syntax-table', stop after the start of a comment or a string, or after end of a comment or a string." (check-type target-depth number) (multiple-value-setq (from to) (validate-region from to buffer)) (let ((state (scan-sexps-forward from (buffer-char-to-aref buffer from) to target-depth (not (null stop-before)) old-state ;; XXX (if comment-stop (if (eq comment-stop 'syntax-table) -1 1) 0) buffer table))) (set-point (parse-state-location state) buffer) state))
71,450
Common Lisp
.lisp
1,426
35.13885
152
0.534353
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
3a5fd9c0e9d162ed3331b7ec33a2a41cf385e38347632b5eb02a0cdafdbe747d
18,430
[ -1 ]
18,431
package.lisp
spacebat_lice/src/package.lisp
(cl:defpackage "LICE" (:use :cl) (:export ;;; Base symbols. In Emacs these are implemented in C ;; abbrev.c #:make-abbrev-table #:clear-abbrev-table #:define-abbrev #:define-global-abbrev #:define-mode-abbrev #:abbrev-expansion #:abbrev-symbol #:expand-abbrev #:unexpand-abbrev #:insert-abbrev-table-description #:define-abbrev-table ;; alloc.c #:cons #:list #:vector #:make-byte-code #:make-list #:make-vector #:make-char-table #:make-string #:make-bool-vector #:make-symbol #:make-marker #:purecopy #:garbage-collect #:memory-limit #:memory-use-counts #:gc-status ;; buffer.c #:buffer-live-p #:buffer-list #:get-buffer #:get-file-buffer #:get-buffer-create #:make-indirect-buffer #:generate-new-buffer-name #:buffer-name #:buffer-number #:buffer-file-name #:buffer-base-buffer #:buffer-local-value #:buffer-local-variables #:buffer-modified-p #:set-buffer-modified-p #:buffer-modified-tick #:buffer-chars-modified-tick #:rename-buffer #:other-buffer #:buffer-enable-undo #:kill-buffer #:set-buffer-major-mode #:switch-to-buffer #:pop-to-buffer #:current-buffer #:set-buffer #:barf-if-buffer-read-only #:bury-buffer #:erase-buffer #:set-buffer-multibyte #:kill-all-local-variables #:overlayp #:make-overlay #:delete-overlay #:move-overlay #:overlay-start #:overlay-end #:overlay-buffer #:overlay-properties #:overlays-at #:overlays-in #:next-overlay-change #:previous-overlay-change #:overlay-recenter #:overlay-lists #:overlay-get #:overlay-put #:restore-buffer-modified-p ;; bytecode.c #:byte-code ;; callint.c #:interactive #:call-interactively #:prefix-numeric-value ;; callproc.c #:call-process #:getenv-internal #:call-process-region ;; casefiddle.c #:upcase #:downcase #:capitalize #:upcase-initials #:upcase-region #:downcase-region #:capitalize-region #:upcase-initials-region #:upcase-word #:downcase-word #:capitalize-word ;; casetab.c #:case-table-p #:current-case-table #:standard-case-table #:set-case-table #:set-standard-case-table ;; category.c #:make-category-set #:define-category #:category-docstring #:get-unused-category #:category-table-p #:category-table #:standard-category-table #:copy-category-table #:make-category-table #:set-category-table #:char-category-set #:category-set-mnemonics #:modify-category-entry ;; ccl.c #:ccl-program-p #:ccl-execute #:ccl-execute-on-string #:register-ccl-program #:register-code-conversion-map ;; charset.c #:define-charset #:generic-character-list #:get-unused-iso-final-char #:declare-equiv-charset #:find-charset-region #:find-charset-string #:make-char-internal #:split-char #:char-charset #:charset-after #:iso-charset #:char-valid-p #:unibyte-char-to-multibyte #:multibyte-char-to-unibyte #:char-bytes #:char-width #:string-width #:char-direction #:string #:setup-special-charsets ;; cmds.c #:forward-point #:forward-char #:backward-char #:forward-line #:beginning-of-line #:end-of-line #:delete-char #:delete-backward-char #:self-insert-command ;; coding.c #:coding-system-p #:read-coding-system #:read-non-nil-coding-system #:check-coding-system #:detect-coding-region #:detect-coding-string #:find-coding-systems-region-internal #:unencodable-char-position #:decode-coding-region #:encode-coding-region #:decode-coding-string #:encode-coding-string #:decode-sjis-char #:encode-sjis-char #:decode-big5-char #:encode-big5-char #:set-terminal-coding-system-internal #:set-safe-terminal-coding-system-internal #:terminal-coding-system #:set-keyboard-coding-system-internal #:keyboard-coding-system #:find-operation-coding-system #:update-coding-systems-internal #:set-coding-priority-internal #:define-coding-system-internal ;; composite.c #:compose-region-internal #:compose-string-internal #:find-composition-internal ;; data.c #:indirect-variable #:interactive-form #:eq #:null #:type-of #:listp #:nlistp #:consp #:atom #:integerp #:integer-or-marker-p #:numberp #:number-or-marker-p #:floatp #:natnump #:symbolp #:keywordp #:stringp #:multibyte-string-p #:vectorp #:char-table-p #:vector-or-char-table-p #:bool-vector-p #:arrayp #:sequencep #:bufferp #:markerp #:subrp #:byte-code-function-p #:char-or-string-p #:car #:cdr #:car-safe #:cdr-safe #:setcar #:setcdr #:symbol-function #:indirect-function #:symbol-plist #:symbol-name #:makunbound #:fmakunbound #:boundp #:fboundp #:fset #:defalias #:setplist #:symbol-value #:set #:default-boundp #:default-value #:set-default #:setq-default #:make-variable-buffer-local #:make-local-variable #:kill-local-variable #:make-variable-frame-local #:local-variable-p #:local-variable-if-set-p #:variable-binding-locus #:aref #:aset #:number-to-string #:string-to-number #:eqlsign #:lss #:gtr #:leq #:geq #:neq #:zerop #:plus #:minus #:times #:quo #:rem #:mod #:max #:min #:logand #:logior #:logxor #:lsh #:ash #:add1 #:sub1 #:lognot #:byteorder #:subr-arity #:subr-name ;; dired.c #:directory-files #:directory-files-and-attributes #:file-name-completion #:file-name-all-versions #:file-version-limit #:file-name-all-completions #:file-attributes #:file-attributes-lessp ;; dispnew.c #:redraw-frame #:redraw-display #:frame-or-buffer-changed-p #:open-termscript #:ding #:redisplay #:sleep-for #:send-string-to-terminal #:internal-show-cursor #:internal-show-cursor-p #:dump-redisplay-history ;; doc.c #:documentation #:documentation-property #:snarf-documentation #:substitute-command-keys ;; dosfns.c #:int86 #:dos-memget #:dos-memput #:msdos-mouse-init #:msdos-mouse-enable #:msdos-set-keyboard #:insert-startup-screen #:msdos-mouse-disable #:file-system-info #:msdos-mouse-p ;; editfns.c #:propertize #:char-equal #:goto-char #:string-to-char #:char-to-string #:buffer-substring #:buffer-substring-no-properties #:buffer-string #:point-marker #:mark-marker #:point #:region-beginning #:region-end #:field-beginning #:field-end #:field-string #:field-string-no-properties #:delete-field #:constrain-to-field #:line-beginning-position #:line-end-position #:mark #:set-mark #:save-excursion #:save-current-buffer #:bufsize #:point-max #:point-min #:point-min-marker #:point-max-marker #:gap-position #:gap-size #:position-bytes #:byte-to-position #:bobp #:eobp #:bolp #:eolp #:following-char #:previous-char #:char-after #:char-before #:insert #:insert-before-markers #:insert-and-inherit #:insert-and-inherit-before-markers #:insert-char #:user-login-name #:user-real-login-name #:user-uid #:user-real-uid #:user-full-name #:emacs-pid #:current-time #:get-internal-run-time #:format-time-string #:float-time #:decode-time #:encode-time #:current-time-string #:current-time-zone #:set-time-zone-rule #:system-name #:message #:message-box #:message-or-box #:current-message #:format #:insert-buffer-substring #:compare-buffer-substrings #:subst-char-in-region #:translate-region-internal #:delete-region #:delete-and-extract-region #:widen #:narrow-to-region #:save-restriction #:transpose-regions ;; emacs.c #:dump-emacs-data #:dump-emacs #:kill-emacs #:invocation-name #:invocation-directory ;; eval.c #:or #:and #:if #:cond #:progn #:prog1 #:prog2 #:setq #:quote #:function #:defun #:defmacro #:defvar #:defvaralias #:defconst #:user-variable-p #:let #:letX #:while #:macroexpand #:catch #:throw #:unwind-protect #:condition-case #:signal #:interactive-p #:called-interactively-p #:commandp #:autoload #:eval #:apply #:funcall #:run-hooks #:run-hook-with-args #:run-hook-with-args-until-success #:run-hook-with-args-until-failure #:fetch-bytecode #:backtrace-debug #:backtrace #:backtrace-frame ;; fileio.c #:find-file-name-handler #:file-name-directory #:file-name-nondirectory #:unhandled-file-name-directory #:file-name-as-directory #:directory-file-name #:make-temp-name #:expand-file-name #:substitute-in-file-name #:copy-file #:make-directory-internal #:delete-directory #:delete-file #:rename-file #:add-name-to-file #:make-symbolic-link #:define-logical-name #:sysnetunam #:file-name-absolute-p #:file-exists-p #:file-executable-p #:file-readable-p #:file-writable-p #:access-file #:file-symlink-p #:file-directory-p #:file-accessible-directory-p #:file-regular-p #:file-modes #:set-file-modes #:set-file-times #:set-default-file-modes #:default-file-modes #:file-newer-than-file-p #:insert-file-contents #:write-region #:car-less-than-car #:verify-visited-file-modtime #:clear-visited-file-modtime #:visited-file-modtime #:set-visited-file-modtime #:do-auto-save #:set-buffer-auto-saved #:clear-buffer-auto-save-failure #:recent-auto-save-p #:read-file-name-internal #:read-file-name #:next-read-file-uses-dialog-p #:unix-sync ;; filelock.c #:unlock-buffer #:lock-buffer #:file-locked-p ;; floatfns.c #:acos #:asin #:atan #:cos #:sin #:tan #:acosh #:asinh #:atanh #:cosh #:sinh #:tanh #:bessel-y0 #:bessel-y1 #:bessel-yn #:bessel-j0 #:bessel-j1 #:bessel-jn #:erf #:erfc #:log-gamma #:cube-root #:fceiling #:ffloor #:fround #:ftruncate #:exp #:expt #:log #:log10 #:sqrt #:abs #:float #:logb #:ceiling #:floor #:round #:truncate ;; fns.c #:sxhash #:make-hash-table #:copy-hash-table #:hash-table-count #:hash-table-rehash-size #:hash-table-rehash-threshold #:hash-table-size #:hash-table-test #:hash-table-weakness #:hash-table-p #:clrhash #:gethash #:puthash #:remhash #:maphash #:define-hash-table-test #:identity #:random #:length #:safe-length #:string-bytes #:string-equal #:compare-strings #:string-lessp #:append #:concat #:vconcat #:copy-sequence #:string-make-multibyte #:string-make-unibyte #:string-as-multibyte #:string-as-unibyte #:string-to-multibyte #:copy-alist #:substring #:substring-no-properties #:nthcdr #:nth #:elt #:member #:memq #:memql #:assq #:assoc #:rassq #:rassoc #:delq #:delete #:nreverse #:reverse #:sort #:plist-get #:get #:plist-put #:put #:lax-plist-get #:lax-plist-put #:eql #:equal #:equal-including-properties #:fillarray #:clear-string #:char-table-subtype #:char-table-parent #:set-char-table-parent #:char-table-extra-slot #:set-char-table-extra-slot #:char-table-range #:set-char-table-range #:set-char-table-default #:optimize-char-table #:map-char-table #:nconc #:mapcar #:mapc #:mapconcat #:y-or-n-p #:yes-or-no-p #:load-average #:featurep #:require #:provide #:plist-member #:widget-put #:widget-get #:widget-apply #:base64-encode-region #:base64-decode-region #:base64-encode-string #:base64-decode-string #:md5 #:locale-info ;; fontset.c #:query-fontset #:new-fontset #:set-fontset-font #:font-info #:internal-char-font #:fontset-info #:fontset-font #:fontset-list #:set-overriding-fontspec-internal ;; frame.c #:active-minibuffer-window #:framep #:frame-live-p #:make-terminal-frame #:handle-switch-frame #:select-frame #:selected-frame #:window-frame #:frame-root-window #:frame-first-window #:frame-selected-window #:set-frame-selected-window #:frame-list #:next-frame #:previous-frame #:delete-frame #:mouse-position #:mouse-pixel-position #:set-mouse-position #:set-mouse-pixel-position #:frame-configuration #:restore-frame-configuration #:make-frame-visible #:make-frame-invisible #:iconify-frame #:frame-visible-p #:visible-frame-list #:raise-frame #:lower-frame #:redirect-frame-focus #:frame-focus #:frame-parameters #:frame-parameter #:modify-frame-parameters #:frame-char-height #:frame-char-width #:frame-pixel-height #:frame-pixel-width #:set-frame-height #:set-frame-width #:set-frame-size #:set-frame-position #:x-get-resource #:x-parse-geometry ;; fringe.c #:destroy-fringe-bitmap #:define-fringe-bitmap #:fringe-bitmaps-at-pos #:set-fringe-bitmap-face ;; image.c #:init-image-library #:clear-image-cache #:image-size #:image-mask-p #:image-extension-data #:imagep #:lookup-image ;; indent.c #:current-indentation #:indent-to #:current-column #:move-to-column #:vertical-motion #:compute-motion ;; insdel.c #:combine-after-change-execute ;; keyboard.c #:current-idle-time #:event-convert-list #:read-key-sequence #:read-key-sequence-vector #:recursive-edit #:track-mouse #:input-pending-p #:command-execute #:recent-keys #:this-command-keys #:this-command-keys-vector #:this-single-command-keys #:this-single-command-raw-keys #:reset-this-command-lengths #:clear-this-command-keys #:suspend-emacs #:abort-recursive-edit #:exit-recursive-edit #:recursion-depth #:top-level #:discard-input #:open-dribble-file #:set-input-mode #:current-input-mode #:execute-extended-command #:posn-at-point #:posn-at-x-y ;; keymap.c #:keymapp #:keymap-parent #:keymap-prompt #:set-keymap-parent #:make-keymap #:make-sparse-keymap #:map-keymap #:copy-keymap #:command-remapping #:key-binding #:local-key-binding #:global-key-binding #:minor-mode-key-binding #:define-key #:lookup-key #:define-prefix-command #:use-global-map #:use-local-map #:current-local-map #:current-global-map #:current-minor-mode-maps #:current-active-maps #:accessible-keymaps #:key-description #:describe-vector #:single-key-description #:text-char-description #:where-is-internal #:describe-buffer-bindings #:apropos-internal ;; lread.c #:ame #:read #:read-from-string #:intern #:intern-soft #:unintern #:get-load-suffixes #:load #:eval-buffer #:eval-region #:read-char #:read-char-exclusive #:read-event #:get-file-char #:mapatoms #:locate-file-internal ;; mac.c #:mac-coerce-ae-data #:mac-get-preference #:mac-code-convert-string #:mac-process-hi-command #:mac-set-file-creator #:mac-set-file-type #:mac-get-file-creator #:mac-get-file-type #:do-applescript #:mac-file-name-to-posix #:posix-file-name-to-mac ;; macfns.c #:x-change-window-property #:x-delete-window-property #:x-window-property #:xw-display-color-p #:x-display-grayscale-p #:xw-color-defined-p #:xw-color-values #:x-server-max-request-size #:x-server-vendor #:x-server-version #:x-display-pixel-width #:x-display-pixel-height #:x-display-mm-width #:x-display-mm-height #:x-display-screens #:x-display-planes #:x-display-color-cells #:x-display-visual-class #:x-display-backing-store #:x-display-save-under #:x-create-frame #:x-open-connection #:x-close-connection #:x-display-list #:x-synchronize #:x-focus-frame #:x-show-tip #:x-hide-tip #:x-file-dialog #:mac-clear-font-name-table #:mac-set-font-panel-visibility #:mac-atsu-font-face-attributes ;; macmenu.c #:x-popup-menu #:menu-or-popup-active-p #:x-popup-dialog ;; macros.c #:start-kbd-macro #:end-kbd-macro #:call-last-kbd-macro #:execute-kbd-macro #:cancel-kbd-macro-events #:store-kbd-macro-event ;; macselect.c #:x-get-selection-internal #:x-own-selection-internal #:x-disown-selection-internal #:x-selection-owner-p #:x-selection-exists-p #:mac-process-deferred-apple-events #:mac-cleanup-expired-apple-events #:mac-resume-apple-event #:mac-ae-set-reply-parameter ;; marker.c #:marker-position #:marker-buffer #:set-marker #:copy-marker #:marker-insertion-type #:set-marker-insertion-type #:buffer-has-markers-at ;; minibuf.c #:set-minibuffer-window #:read-from-minibuffer #:eval-minibuffer #:read-minibuffer #:read-string #:read-command #:read-variable #:internal-complete-buffer #:read-buffer #:read-no-blanks-input #:minibuffer-depth #:minibuffer-prompt #:minibufferp #:minibuffer-prompt-end #:minibuffer-contents #:minibuffer-contents-no-properties #:minibuffer-completion-contents #:delete-minibuffer-contents #:try-completion #:all-completions #:test-completion #:assoc-string #:completing-read #:minibuffer-complete #:minibuffer-complete-word #:minibuffer-complete-and-exit #:display-completion-list #:minibuffer-completion-help #:self-insert-and-exit #:exit-minibuffer #:minibuffer-message ;; msdos.c #:recent-doskeys #:msdos-long-file-names #:msdos-downcase-filename #:msdos-remember-default-colors #:msdos-set-mouse-buttons ;; print.c #:prin1 #:prin1-to-string #:error-message-string #:princ #:print #:terpri #:write-char #:external-debugging-output #:redirect-debugging-output #:with-output-to-temp-buffer ;; process.c #:processp #:get-process #:get-buffer-process #:delete-process #:process-status #:process-exit-status #:process-id #:process-name #:process-tty-name #:process-command #:set-process-buffer #:process-buffer #:process-mark #:set-process-filter #:process-filter #:set-process-sentinel #:process-sentinel #:set-process-window-size #:set-process-inherit-coding-system-flag #:process-inherit-coding-system-flag #:set-process-query-on-exit-flag #:process-query-on-exit-flag #:process-contact #:process-plist #:set-process-plist #:list-processes #:process-list #:start-process #:set-network-process-option #:make-network-process #:format-network-address #:network-interface-list #:network-interface-info #:process-datagram-address #:set-process-datagram-address #:accept-process-output #:process-send-region #:process-send-string #:interrupt-process #:kill-process #:quit-process #:stop-process #:continue-process #:process-running-child-p #:process-send-eof #:signal-process #:waiting-for-user-input-p #:process-connection #:set-process-coding-system #:process-coding-system #:set-process-filter-multibyte #:process-filter-multibyte-p #:get-buffer-process #:process-inherit-coding-system-flag ;; search.c #:looking-at #:posix-looking-at #:string-match #:posix-string-match #:search-forward #:search-backward #:word-search-forward #:word-search-backward #:re-search-forward #:re-search-backward #:posix-search-forward #:posix-search-backward #:replace-match #:match-beginning #:match-end #:match-data #:set-match-data #:regexp-quote ;; sound.c #:play-sound-internal ;; sunfns.c #:un-window-init #:it-for-millisecs #:leep-for-millisecs #:pdate-display #:un-change-cursor-icon #:un-set-selection #:un-get-selection #:un-menu-internal ;; syntax.c #:syntax-table-p #:syntax-table #:standard-syntax-table #:copy-syntax-table #:set-syntax-table #:char-syntax #:matching-paren #:string-to-syntax #:modify-syntax-entry #:internal-describe-syntax-value #:forward-word #:skip-chars-forward #:skip-chars-backward #:skip-syntax-forward #:skip-syntax-backward #:forward-comment #:scan-lists #:scan-sexps #:backward-prefix-chars #:parse-partial-sexp ;; term.c #:tty-display-color-p #:tty-display-color-cells #:tty-no-underline ;; textprop.c #:text-properties-at #:get-text-property #:get-char-property #:get-char-property-and-overlay #:next-char-property-change #:previous-char-property-change #:next-single-char-property-change #:previous-single-char-property-change #:next-property-change #:next-single-property-change #:previous-property-change #:previous-single-property-change #:add-text-properties #:put-text-property #:set-text-properties #:remove-text-properties #:remove-list-of-text-properties #:text-property-any #:text-property-not-all #:erase-text-properties #:copy-text-properties ;; undo.c #:primitive-undo #:undo-boundary ;; w16select.c #:w16-set-clipboard-data #:w16-get-clipboard-data #:x-selection-exists-p ;; w32console.c #:set-screen-color #:set-cursor-size #:set-message-beep ;; w32fns.c #:x-change-window-property #:x-delete-window-property #:x-window-property #:xw-display-color-p #:x-display-grayscale-p #:xw-color-defined-p #:xw-color-values #:x-server-max-request-size #:x-server-vendor #:x-server-version #:x-display-pixel-width #:x-display-pixel-height #:x-display-mm-width #:x-display-mm-height #:x-display-screens #:x-display-planes #:x-display-color-cells #:x-display-visual-class #:x-display-backing-store #:x-display-save-under #:x-create-frame #:x-open-connection #:x-close-connection #:x-display-list #:x-synchronize #:w32-focus-frame #:w32-select-font #:w32-define-rgb-color #:w32-default-color-map #:w32-load-color-file #:w32-send-sys-command #:w32-shell-execute #:w32-register-hot-key #:w32-unregister-hot-key #:w32-registered-hot-keys #:w32-reconstruct-hot-key #:w32-toggle-lock-key #:w32-window-exists-p #:w32-find-bdf-fonts #:file-system-info #:default-printer-name #:x-show-tip #:x-hide-tip #:x-file-dialog ;; w32menu.c #:x-popup-menu #:menu-or-popup-active-p #:x-popup-dialog #:w32-has-winsock #:w32-unload-winsock #:w32-short-file-name #:w32-long-file-name #:w32-set-process-priority #:w32-get-locale-info #:w32-get-current-locale-id #:w32-get-default-locale-id #:w32-get-valid-locale-ids #:w32-set-current-locale #:w32-get-console-codepage #:w32-set-console-codepage #:w32-get-console-output-codepage #:w32-set-console-output-codepage #:w32-get-valid-codepages #:w32-get-codepage-charset #:w32-get-valid-keyboard-layouts #:w32-get-keyboard-layout #:w32-set-keyboard-layout ;; w32select.c #:w32-set-clipboard-data #:w32-get-clipboard-data #:x-selection-exists-p ;; window.c #:selected-window #:minibuffer-window #:window-minibuffer-p #:windowp #:window-live-p #:pos-visible-in-window-p #:window-line-height #:window-buffer #:window-height #:window-width #:window-hscroll #:set-window-hscroll #:window-redisplay-end-trigger #:set-window-redisplay-end-trigger #:window-edges #:window-pixel-edges #:window-inside-edges #:window-inside-pixel-edges #:coordinates-in-window-p #:window-at #:window-point #:window-start #:window-end #:set-window-point #:set-window-start #:window-dedicated-p #:set-window-dedicated-p #:window-display-table #:set-window-display-table #:next-window #:previous-window #:other-window #:get-lru-window #:get-largest-window #:get-buffer-window #:delete-other-windows #:delete-windows-on #:replace-buffer-in-windows #:delete-window #:set-window-buffer #:select-window #:special-display-p #:same-window-p #:display-buffer #:force-window-update #:split-window #:enlarge-window #:shrink-window #:adjust-window-trailing-edge #:scroll-up #:scroll-down #:scroll-left #:scroll-right #:other-window-for-scrolling #:scroll-other-window #:minibuffer-selected-window #:recenter #:window-text-height #:move-to-window-line #:window-configuration-p #:window-configuration-frame #:set-window-configuration #:current-window-configuration #:save-window-excursion #:window-tree #:set-window-margins #:window-margins #:set-window-fringes #:window-fringes #:set-window-scroll-bars #:window-scroll-bars #:window-vscroll #:set-window-vscroll #:compare-window-configurations #:window-list ;; xdisp.c #:dump-frame-glyph-matrix #:dump-glyph-matrix #:dump-glyph-row #:dump-tool-bar-row #:trace-redisplay #:trace-to-stderr #:tool-bar-lines-needed #:lookup-image-map #:format-mode-line ;; xfaces.c #:internal-make-lisp-face #:internal-lisp-face-p #:internal-set-lisp-face-attribute #:internal-set-lisp-face-attribute-from-resource #:color-gray-p #:color-supported-p #:face-attribute-relative-p #:merge-face-attribute #:internal-get-lisp-face-attribute #:internal-lisp-face-attribute-values #:internal-lisp-face-equal-p #:internal-lisp-face-empty-p #:internal-copy-lisp-face #:internal-merge-in-global-face #:face-font #:frame-face-alist #:display-supports-face-attributes-p #:color-distance #:internal-set-font-selection-order #:internal-set-alternative-font-family-alist #:internal-set-alternative-font-registry-alist #:face-attributes-as-vector #:dump-face #:show-face-resources #:clear-face-cache #:tty-suppress-bold-inverse-default-colors #:dump-colors #:bitmap-spec-p #:x-list-fonts #:internal-face-x-get-resource #:x-family-fonts #:x-font-family-list ;; xfns.c #:x-change-window-property #:x-delete-window-property #:x-window-property #:xw-display-color-p #:x-display-grayscale-p #:xw-color-defined-p #:xw-color-values #:x-server-max-request-size #:x-server-vendor #:x-server-version #:x-display-pixel-width #:x-display-pixel-height #:x-display-mm-width #:x-display-mm-height #:x-display-screens #:x-display-planes #:x-display-color-cells #:x-display-visual-class #:x-display-backing-store #:x-display-save-under #:x-create-frame #:x-open-connection #:x-close-connection #:x-display-list #:x-synchronize #:x-focus-frame #:x-backspace-delete-keys-p #:x-show-tip #:x-hide-tip #:x-uses-old-gtk-dialog #:x-file-dialog ;; xmenu.c #:x-popup-menu #:menu-or-popup-active-p #:menu-bar-open #:x-popup-dialog ;; xselect.c #:x-get-selection-internal #:x-own-selection-internal #:x-disown-selection-internal #:x-selection-owner-p #:x-selection-exists-p #:x-get-cut-buffer-internal #:x-store-cut-buffer-internal #:x-rotate-cut-buffers-internal #:x-get-atom-name #:x-send-client-message #:x-register-dnd-atom ;; xsmfns.c #:handle-save-session ;;; ))
29,026
Common Lisp
.lisp
1,294
17.435858
57
0.640127
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
26ce14558ca7a9f9c26d54edb0af7cfc906b36153f537298b18d2ddc5f973781
18,431
[ -1 ]
18,432
emacs.lisp
spacebat_lice/src/emacs.lisp
(in-package "LICE") ;; FIXME: figure out the system type (defvar system-type :undefined "Value is symbol indicating type of operating system you are using. Special values: `:gnu/linux' compiled for a GNU/Linux system. `:darwin' compiled for Darwin (GNU-Darwin, Mac OS X, ...). `:macos' compiled for Mac OS 9. `:ms-dos' compiled as an MS-DOS application. `:windows-nt' compiled as a native W32 application. `:cygwin' compiled using the Cygwin library. `:vax-vms' or `:axp-vms' compiled for a (Open)VMS system. Anything else indicates some sort of Unix system. */); Vsystem_type = intern (SYSTEM_TYPE") (defvar kill-emacs-hook nil "Hook to be run when kill-emacs is called. Since `kill-emacs' may be invoked when the terminal is disconnected (or in other similar situations), functions placed on this hook should not expect to be able to interact with the user. To ask for confirmation, see `kill-emacs-query-functions' instead. The hook is not run in batch mode, i.e., if `noninteractive' is non-nil.") (defun kill-emacs (&optional arg) "Exit the Emacs job and kill it. If ARG is an integer, return ARG as the exit program code. If ARG is a string, stuff it as keyboard input. The value of `kill-emacs-hook', if not void, is a list of functions (of no args), all of which are called before Emacs is actually killed." (run-hooks 'kill-emacs-hook) (throw 'lice-quit arg))
1,432
Common Lisp
.lisp
31
44.129032
74
0.732092
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
530c57b707b95bf2c6d8d32c456fd4acb309155c8b9a83543d5f6d2ae022c0fd
18,432
[ -1 ]
18,433
mcl-load.lisp
spacebat_lice/src/mcl-load.lisp
(require 'quickdraw) (defpackage :lice (:use :cl)) (labels ((load-file (module) ;;(format t "~&Loading ~a...~%" module) (load (merge-pathnames (make-pathname :name module :type "lisp") *load-pathname*) :verbose t :external-format :unix))) (load-file "wrappers") (load-file "global") (load-file "major-mode") (load-file "buffer") (load-file "window") (load-file "frame") (load-file "mcl-render") (load-file "intervals") (load-file "textprop") (load-file "editfns") (load-file "input") (load-file "recursive-edit") (load-file "minibuffer") (load-file "subr") (load-file "simple") (load-file "wm") (load-file "lisp-mode") (load-file "files") (load-file "main"))
723
Common Lisp
.lisp
1
722
723
0.614108
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
428f568ee16f65f5b16cae6bae7c9a0778ffe7ea35f5846c63c2d9d241b584a8
18,433
[ -1 ]
18,434
keymap.lisp
spacebat_lice/src/keymap.lisp
;;; keymaps for lice (in-package "LICE") ;; for mouse click events (defstruct click where button) (defstruct key char control meta alt shift hyper super) ;; (defclass key () ;; ((char :type character :initarg :char :reader key-char) ;; (control :type boolean :initform nil :initarg :control :reader key-control) ;; (meta :type boolean :initform nil :initarg :meta :reader key-meta) ;; (alt :type boolean :initform nil :initarg :alt :reader key-alt) ;; (shift :type boolean :initform nil :initarg :shift :reader key-shift) ;; (hyper :type boolean :initform nil :initarg :hyper :reader key-hyper) ;; (super :type boolean :initform nil :initarg :super :reader key-super)) ;; (:documentation "A key event.")) (defun print-mods (key) (concatenate 'string (when (key-control key) "C-") (when (key-meta key) "M-") (when (key-alt key) "A-") (when (key-shift key) "S-") (when (key-super key) "s-") (when (key-hyper key) "H-"))) (defun print-key (key) (format nil "~a~a" (print-mods key) (key-char key))) (defmethod print-object ((obj key) stream) (print-unreadable-object (obj stream :type t :identity t) (format stream "~s" (print-key obj)))) (define-condition kbd-parse (lice-condition) () (:documentation "Raised when a kbd string failed to parse.")) (defun parse-mods (mods end) "MODS is a sequence of <MOD CHAR> #\- pairs. Return a list suitable for passing as the last argument to (apply #'make-key ...)" (unless (evenp end) (signal 'kbd-parse)) (apply #'nconc (loop for i from 0 below end by 2 if (char/= (char mods (1+ i)) #\-) do (signal 'kbd-parse) collect (case (char mods i) (#\M (list :meta t)) (#\A (list :alt t)) (#\C (list :control t)) (#\H (list :hyper t)) (#\s (list :super t)) (#\S (list :shift t)) (t (signal 'kbd-parse)))))) (defvar *keysyms* nil "An alist of keysyms that map a string to either a character or a symbol.") (defmacro define-keysym (string thing) `(pushnew (cons ,string ,thing) *keysyms* :test 'equal)) (define-keysym "RET" #\Newline) (define-keysym "TAB" #\Tab) (define-keysym "SPC" #\Space) (define-keysym "up" :up) (define-keysym "down" :down) (define-keysym "left" :left) (define-keysym "right" :right) (define-keysym "prior" :prior) (defun parse-char-name (string) "Return the character whose name is STRING." (or (let ((sym (find string *keysyms* :test 'string= :key 'car))) (when sym (cdr sym))) (name-char string) (and (= (length string) 1) (char string 0)))) (defun parse-key (string) "Parse STRING and return a key structure." ;; FIXME: we want to return NIL when we get a kbd-parse error ;;(ignore-errors (let* ((p (when (> (length string) 2) (position #\- string :from-end t :end (- (length string) 1)))) (mods (parse-mods string (if p (1+ p) 0))) (ch (parse-char-name (subseq string (if p (1+ p) 0))))) (and ch (apply #'make-key :char ch mods)))) (defun parse-key-seq (keys) "KEYS is a key sequence. Parse it and return the list of keys." (mapcar 'parse-key (split-string keys))) (defun kbd (keys) "Convert KEYS to the internal Emacs key representation. KEYS should be a string constant in the format used for saving keyboard macros ***(see `insert-kbd-macro')." ;; XXX: define-key needs to be fixed to handle a list of keys (first (parse-key-seq keys))) ;; ;; XXX: This is hacky. Convert the class into a sequence. Maybe we should ;; ;; use defstruct then? ;; (defun key-hashid (event) ;; (typecase event ;; (key (list (key-char event) ;; (key-control event) ;; (key-meta event) ;; (key-alt event) ;; (key-hyper event) ;; (key-super event))) ;; (t t))) (defvar *current-keymap-theme* :lice) (defvar *overriding-terminal-local-map* nil "Per-terminal keymap that overrides all other local keymaps. If this variable is non-nil, it is used as a keymap instead of the buffer's local map, and the minor mode keymaps and text property keymaps. It also replaces `overriding-local-map'. This variable is intended to let commands such as `universal-argument' set up a different keymap for reading the next command.") (defvar *overriding-local-map* nil "Keymap that overrides all other local keymaps. If this variable is non-nil, it is used as a keymap--replacing the buffer's local map, the minor mode keymaps, and char property keymaps.") (defclass keymap () ((parent :initform nil :initarg :parent :accessor keymap-parent) (prompt :initform nil :initarg :prompt :accessor keymap-prompt) (themes :initform (make-hash-table) :accessor keymap-themes))) (defun keymapp (object) (typep object 'keymap)) (defun make-sparse-keymap (&optional prompt) "Construct and return a new sparse keymap. The optional arg STRING supplies a menu name for the keymap in case you use it as a menu with `x-popup-menu'." (make-instance 'keymap :prompt prompt)) (defun get-keymap-theme (keymap theme) (gethash theme (keymap-themes keymap))) (defun get-keymap-theme-create (keymap theme) (or (get-keymap-theme keymap theme) (setf (gethash theme (keymap-themes keymap)) (make-hash-table :size 200 :test 'equalp)))) (defgeneric define-key (keymap key def &optional theme) (:documentation "In keymap, define key sequence key as def. keymap is a keymap.")) (defmethod define-key (keymap (key vector) def &optional (theme :lice)) "for some weirdness in bindings.lisp" (warn "unimplemented define-key")) (defmethod define-key (keymap (key click) def &optional (theme :lice)) "Mouse click events" (warn "unimplemented define-key")) (defmethod define-key (keymap (key string) (def string) &optional (theme :lice)) "alias a key to another key." (warn "unimplemented define-key")) (defmethod define-key (keymap (key symbol) def &optional (theme :lice)) "Special events are represented as symbols." (warn "unimplemented define-key")) (defmethod define-key (keymap (key string) def &optional (theme :lice)) (define-key keymap (parse-key-seq key) def theme)) (defmethod define-key (keymap (key list) def &optional (theme :lice)) (let ((map (lookup-key-internal keymap key nil theme nil t nil))) ;; FIXME: do this error properly (unless map (error "Key sequence %s starts with non-prefix key %s")) (define-key map (car (last key)) def theme))) (defmethod define-key (keymap (key key) def &optional (theme :lice)) (let ((map (get-keymap-theme-create keymap theme))) (setf (gethash #|(key-hashid key)|# key map) def))) (defun lookup-key-internal (keymap key accept-default theme norecurse return-kmap check-parents) "RETURN-KMAP means return the key's keymap." (let* ((map (get-keymap-theme keymap theme)) ;; some maps may not have a hash table for the theme. (cmd (and map (gethash (if (consp key) (car key) key) map)))) (or ;; if the binding is another keymap, then lookup the rest of the key sequence (cond ((and return-kmap (= (length key) 1) keymap)) ((and (keymapp cmd) (not norecurse)) (lookup-key-internal cmd (cdr key) accept-default theme norecurse return-kmap check-parents)) (t cmd)) ;; check parent for binding (when (and check-parents (keymap-parent keymap)) (lookup-key-internal (keymap-parent keymap) key nil theme norecurse return-kmap check-parents)) (when accept-default (and map (gethash t map)))))) (defun lookup-key (keymap key &optional accept-default (theme :lice)) "In keymap KEYMAP, look up key sequence KEY. Return the definition. nil means undefined. See doc of `define-key' for kinds of definitions. Normally, `lookup-key' ignores bindings for t, which act as default bindings, used when nothing else in the keymap applies; this makes it usable as a general function for probing keymaps. However, if the third optional argument ACCEPT-DEFAULT is non-nil, `lookup-key' will recognize the default bindings, just as `read-key-sequence' does." (check-type keymap keymap) (lookup-key-internal keymap key accept-default theme nil nil t)) (depricate set-keymap-parent (setf keymap-parent)) (defun set-keymap-parent (keymap parent) "Modify keymap to set its parent map to parent. Return parent. parent should be nil or another keymap." (setf (keymap-parent keymap) parent)) (defun make-keymap (&optional string) (declare (ignore string)) (error "unimplemented make-keymap")) (defun map-keymap (function keymap &optional (theme :lice)) "Call FUNCTION once for each event binding in KEYMAP. FUNCTION is called with two arguments: the event that is bound, and the definition it is bound to. If the event is an integer, it may be a generic character (see Info node `(elisp)Splitting Characters'), and that means that all actual character events belonging to that generic character are bound to the definition. If KEYMAP has a parent, the parent's bindings are included as well. This works recursively: if the parent has itself a parent, then the grandparent's bindings are also included and so on." (let ((map (get-keymap-theme keymap theme))) (maphash function map) (when (keymap-parent keymap) (map-keymap function (keymap-parent keymap) theme)))) (defvar *esc-map* (make-sparse-keymap) "Default keymap for ESC (meta) commands. The normal global definition of the character ESC indirects to this keymap.") (defvar *global-map* (make-sparse-keymap) "The top level global keymap.") (defvar *ctl-x-4-map* (make-sparse-keymap) "The C-x 4 keymap.") (defvar *ctl-x-5-map* (make-sparse-keymap) "The C-x 4 keymap.") (defvar *ctl-x-map* (make-sparse-keymap) "The C-x keymap.") (defvar *ctl-c-map* (make-sparse-keymap) "The C-c keymap.") (defvar *ctl-h-map* (make-sparse-keymap) "The C-h keymap.") (defvar *function-key-map* (make-sparse-keymap) "Keymap that translates key sequences to key sequences during input. This is used mainly for mapping ASCII function key sequences into real Emacs function key events (symbols). The `read-key-sequence' function replaces any subsequence bound by `function-key-map' with its binding. More precisely, when the active keymaps have no binding for the current key sequence but `function-key-map' binds a suffix of the sequence to a vector or string, `read-key-sequence' replaces the matching suffix with its binding, and continues with the new sequence. If the binding is a function, it is called with one argument (the prompt) and its return value (a key sequence) is used. The events that come from bindings in `function-key-map' are not themselves looked up in `function-key-map'. For example, suppose `function-key-map' binds `ESC O P' to [f1]. Typing `ESC O P' to `read-key-sequence' would return [f1]. Typing `C-x ESC O P' would return [?\\C-x f1]. If [f1] were a prefix key, typing `ESC O P x' would return [f1 x].") (defvar *current-global-map* *global-map*) (defvar *current-kmap* nil "The key map that the next key event will use to find a corresponding command.") ;; initialize a skeleton structure for the keymaps (define-key *global-map* "ESC" *esc-map*) (define-key *esc-map* "ESC" (make-sparse-keymap)) (define-key *global-map* "C-x" *ctl-x-map*) (define-key *ctl-x-map* "n" (make-sparse-keymap)) (define-key *global-map* "C-c" *ctl-c-map*) (define-key *global-map* "C-h" *ctl-h-map*) (define-key *ctl-x-map* "r" (make-sparse-keymap)) (define-key *ctl-x-map* "a" (make-sparse-keymap)) (define-key *ctl-x-map* "a i" (make-sparse-keymap)) (defun copy-keymap (keymap) (declare (ignore keymap)) (error "unimplemented copy-keymap")) (defun command-remapping () (error "unimplemented command-remapping")) (defun key-binding (key &optional accept-default no-remap) (declare (ignore key accept-default no-remap)) (error "unimplemented key-binding")) (defun local-key-binding () (error "unimplemented local-key-binding")) (defun global-key-binding () (error "unimplemented global-key-binding")) (defun minor-mode-key-binding () (error "unimplemented minor-mode-key-binding")) (defun define-prefix-command () (error "unimplemented define-prefix-command")) (defun use-global-map (keymap) (check-type keymap keymap) (setf *current-global-map* keymap)) (defun use-local-map (keymap) "Select KEYMAP as the local keymap. If KEYMAP is nil, that means no local keymap." (check-type keymap keymap) (setf (buffer-local-map (current-buffer)) keymap)) (defun current-local-map () "Return current buffer's local keymap, or nil if it has none. LICE: the local map in really the major mode map. Except it might not be in the future." (buffer-local-map (current-buffer))) (defun current-global-map () "Return the current global keymap." *current-global-map*) (defun current-minor-mode-maps () (error "unimplemented current-minor-mode-maps")) (defun current-active-maps () (error "unimplemented current-active-maps")) (defun accessible-keymaps () (error "unimplemented" accessible-keymaps)) (defun key-description () (error "unimplemented key-description")) (defun describe-vector () (error "unimplemented describe-vector")) (defun single-key-description () (error "unimplemented single-key-description")) (defun text-char-description () (error "unimplemented text-char-description")) (defun where-is-internal () (error "unimplemented where-is-internal")) (defun describe-buffer-bindings () (error "unimplemented describe-buffer-bindings")) (defun apropos-internal () (error "unimplemented apropos-internal")) ;; This is a struct to make it easier to add new elements to, should ;; we want to. Also, it makes code easier to read, I think. (defstruct minor-mode-map variable keymap) (defvar *minor-mode-map-list* nil "Alist of keymaps to use for minor modes. Each element looks like (VARIABLE . KEYMAP); KEYMAP is used to read key sequences and look up bindings iff VARIABLE's value is non-nil. If two active keymaps bind the same key, the keymap appearing earlier in the list takes precedence.") (define-buffer-local *minor-mode-overriding-map-list* nil "Alist of keymaps to use for minor modes, in current major mode. This variable is an alist just like `*minor-mode-map-list*', and it is used the same way (and before `*minor-mode-map-list*'); however, it is provided for major modes to bind locally.") ;; (defun make-ctrl-h-map () ;; (let ((kmap (make-sparse-keymap))) ;; (define-key kmap (make-key :char #\f) 'describe-symbol) ;; kmap)) ;; (defun make-ctrl-x-4-map () ;; (let ((kmap (make-sparse-keymap))) ;; (define-key kmap (make-key :char #\b) 'switch-to-buffer-other-window) ;; kmap)) ;; (defun make-ctrl-x-map (ctl-x-4-map) ;; (let ((kmap (make-sparse-keymap))) ;; (define-key kmap (make-key :char #\e :control t) 'eval-last-sexp) ;; (define-key kmap (make-key :char #\b) 'switch-to-buffer) ;; (define-key kmap (make-key :char #\c :control t) 'save-buffers-kill-emacs) ;; (define-key kmap (make-key :char #\f :control t) 'find-file) ;; (define-key kmap (make-key :char #\s :control t) 'save-buffer) ;; (define-key kmap (make-key :char #\k) 'kill-buffer) ;; (define-key kmap (make-key :char #\o) 'other-window) ;; (define-key kmap (make-key :char #\1) 'delete-other-windows) ;; (define-key kmap (make-key :char #\2) 'split-window-vertically) ;; (define-key kmap (make-key :char #\3) 'split-window-horizontally) ;; (define-key kmap (make-key :char #\x :control t) 'exchange-point-and-mark) ;; (define-key kmap (make-key :char #\t :control t) 'transpose-lines) ;; (define-key kmap (make-key :char #\4) ctl-x-4-map) ;; kmap)) ;; (defun make-ctrl-c-map () ;; (let ((kmap (make-sparse-keymap))) ;; kmap)) ;; (defun make-global-map (ctl-x-prefix ctl-c-prefix ctl-h-prefix) ;; "Generate self-insert commands for all printable characters. And ;; more." ;; (let ((kmap (make-sparse-keymap))) ;; (loop for i in '(#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9 ;; #\a #\b #\c #\d #\e #\f #\g #\h #\i #\j ;; #\k #\l #\m #\n #\o #\p #\q #\r #\s #\t ;; #\u #\v #\w #\x #\y #\z ;; #\A #\B #\C #\D #\E #\F #\G #\H #\I #\J ;; #\K #\L #\M #\N #\O #\P #\Q #\R #\S #\T ;; #\U #\V #\W #\X #\Y #\Z ;; #\Space #\! #\" #\# #\$ #\% #\& #\' #\( ;; #\) #\* #\+ #\, #\- #\. #\/ #\: #\; #\< ;; #\= #\> #\? #\@ #\[ #\\ #\] #\^ #\_ #\` ;; #\| #\} #\~ #\{) ;; do (define-key kmap (make-key :char i) 'self-insert-command)) ;; (define-key kmap (make-key :char #\Return) 'newline) ;; (define-key kmap (make-key :char #\Newline) 'newline) ;; (define-key kmap (make-key :char #\o :control t) 'open-line) ;; (define-key kmap (make-key :char #\j :control t) 'newline) ;; (define-key kmap (make-key :char #\m :control t) 'newline) ;; (define-key kmap (make-key :char #\f :control t) 'forward-char) ;; (define-key kmap (make-key :char #\f :meta t) 'forward-word) ;; (define-key kmap (make-key :char #\f :control t :meta t) 'forward-sexp) ;; (define-key kmap (make-key :char #\b :control t :meta t) 'backward-sexp) ;; (define-key kmap (make-key :char #\n :control t) 'next-line) ;; (define-key kmap (make-key :char #\p :control t) 'previous-line) ;; (define-key kmap (make-key :char #\b :control t) 'backward-char) ;; (define-key kmap (make-key :char #\b :meta t) 'backward-word) ;; (define-key kmap (make-key :char #\d :control t) 'delete-char) ;; (define-key kmap (make-key :char #\d :meta t) 'kill-word) ;; (define-key kmap (make-key :char #\Rubout :meta t) 'backward-kill-word) ;; (define-key kmap (make-key :char #\Rubout) 'delete-backward-char) ;; (define-key kmap (make-key :char #\Delete) 'delete-backward-char) ;; (define-key kmap (make-key :char #\t :meta t) 'transpose-words) ;; (define-key kmap (make-key :char #\t :control t) 'transpose-chars) ;; ;;(define-key kmap (make-key :char #\h :control t) 'delete-backward-char) ;; (define-key kmap (make-key :char #\u :control t) 'universal-argument) ;; (define-key kmap (make-key :char #\a :control t) 'beginning-of-line) ;; (define-key kmap (make-key :char #\e :control t) 'end-of-line) ;; (define-key kmap (make-key :char #\g :control t) 'keyboard-quit) ;; (define-key kmap (make-key :char #\v :control t) 'scroll-up) ;; (define-key kmap (make-key :char #\v :meta t) 'scroll-down) ;; (define-key kmap (make-key :char #\k :control t) 'kill-line) ;; (define-key kmap (make-key :char #\w :control t) 'kill-region) ;; (define-key kmap (make-key :char #\y :control t) 'yank) ;; (define-key kmap (make-key :char #\y :meta t) 'yank-pop) ;; (define-key kmap (make-key :char #\w :meta t) 'kill-ring-save) ;; (define-key kmap (make-key :char #\> :meta t) 'end-of-buffer) ;; (define-key kmap (make-key :char #\< :meta t) 'beginning-of-buffer) ;; (define-key kmap (make-key :char #\x :meta t) 'execute-extended-command) ;; (define-key kmap (make-key :char #\: :meta t) 'eval-expression) ;; (define-key kmap (make-key :char #\Space :control t) 'set-mark-command) ;; (define-key kmap (make-key :char #\` :control t) 'set-mark-command) ;; (define-key kmap (make-key :char #\! :meta t) 'shell-command) ;; (define-key kmap (make-key :char #\Space :meta t) 'just-one-space) ;; (define-key kmap (make-key :char #\\ :control t :meta t) 'indent-region) ;; (define-key kmap (make-key :char #\a :control t :meta t) 'beginning-of-defun) ;; (define-key kmap (make-key :char #\e :control t :meta t) 'end-of-defun) ;; (define-key kmap (make-key :char #\_ :control t) 'undo) ;; (define-key kmap (make-key :char #\/ :control t) 'undo) ;; (define-key kmap (make-key :char #\} :meta t) 'forward-paragraph) ;; (define-key kmap (make-key :char #\{ :meta t) 'backward-paragraph) ;; (define-key kmap (make-key :char #\x :control t) ctl-x-prefix) ;; (define-key kmap (make-key :char #\c :control t) ctl-c-prefix) ;; (define-key kmap (make-key :char #\h :control t) ctl-h-prefix) ;; kmap)) ;; (defun make-global-keymaps () ;; "Create the default global keymaps and store them in *global-kmap ;; *ctl-x-map*, ..." ;; (setf *ctl-x-4-map* (make-ctrl-x-4-map) ;; *ctl-x-map* (make-ctrl-x-map *ctl-x-4-map*) ;; *ctl-c-map* (make-ctrl-c-map) ;; *ctl-h-map* (make-ctrl-h-map) ;; *global-map* (make-global-map *ctl-x-map* *ctl-c-map* *ctl-h-map*)))
20,562
Common Lisp
.lisp
416
46.855769
102
0.676211
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
382c75ec2f09b9bd8d6bafa12ba1a55d216e37e9c389979f58bc1936c413b1cd
18,434
[ -1 ]
18,435
make-image.lisp
spacebat_lice/src/make-image.lisp
;;; SBCL #+sbcl (progn (require 'asdf) (require 'lice)) #+sbcl (sb-ext:save-lisp-and-die "lice" :toplevel (lambda () ;; asdf requires sbcl_home to be set, so set it to the value when the image was built (sb-posix:putenv (format nil "SBCL_HOME=~A" #.(sb-ext:posix-getenv "SBCL_HOME"))) (lice::lice) 0) :executable t) ;;; CLISP ;; asdf needs to be loaded. try putting (load "/path/to/asdf.lisp") in your .clisprc file #+clisp (asdf:oos 'asdf:load-op :lice) #+clisp (progn (ext:saveinitmem "lice" :init-function (lambda () (lice::lice) (ext:quit)) :executable t :keep-global-handlers t :norc t :documentation "Lisp Computing Environment")) #-(or sbcl clisp) (error "This lisp implementation is not supported.")
1,037
Common Lisp
.lisp
23
29.782609
130
0.490585
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
1f25220ad0d1691d1a2f3f7e43738f75b8b5b3657ff4a1cb9cb7aa0dec9760fc
18,435
[ -1 ]
18,436
debug.lisp
spacebat_lice/src/debug.lisp
;;; lice debugging facilities (in-package "LICE") (defun re-op-lice (op) "Perform an asdf operation on :lice and capture the output in a buffer." (with-current-buffer (get-buffer-create "*lice-reload*") (erase-buffer) (insert (with-output-to-string (s) (let ((*debug-io* s) (*error-output* s) (*standard-output* s)) (asdf:oos op :lice))))) (display-buffer "*lice-reload*")) (defcommand recompile-lice () (re-op-lice 'asdf:compile-op)) (defcommand reload-lice () (re-op-lice 'asdf:load-op)) (provide :lice-0.1/debug)
566
Common Lisp
.lisp
19
26.157895
65
0.662362
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
c4d786a12e12727095ad0dfe5d117b0e115d36ab4d3cb71292070243663e29cd
18,436
[ -1 ]
18,437
casefiddle.lisp
spacebat_lice/src/casefiddle.lisp
(in-package "LICE") ;; FIXME: these case functions don't handle characters or propertized strings (defun upcase (obj) "Convert argument to upper case and return that. The argument may be a character or string. The result has the same type. The argument object is not altered--the value is a copy. See also `capitalize', `downcase' and `upcase-initials'." (string-upcase obj)) (defun downcase (obj) "Convert argument to lower case and return that. The argument may be a character or string. The result has the same type. The argument object is not altered--the value is a copy." (string-downcase obj)) (defun capitalize (obj) "Convert argument to capitalized form and return that. This means that each word's first character is upper case and the rest is lower case. The argument may be a character or string. The result has the same type. The argument object is not altered--the value is a copy." (string-capitalize obj)) (defun upcase-initials (obj) "Convert the initial of each word in the argument to upper case. Do not change the other letters of each word. The argument may be a character or string. The result has the same type. The argument object is not altered--the value is a copy." ;; FIXME: don't touch the other letters. only the first one. (string-capitalize obj)) (defun upcase-region (beg end) (declare (ignore beg end)) (error "Unimplemented upcase-region")) (setf (get 'upcase-region 'disabled) t) (defun downcase-region () (error "Unimplemented downcase-region")) (setf (get 'downcase-region 'disabled) t) (defun capitalize-region () (error "Unimplemented capitalize-region")) (defun upcase-initials-region () (error "Unimplemented upcase-initials-region")) (defun upcase-word () (error "Unimplemented upcase-word")) (defun downcase-word () (error "Unimplemented downcase-word")) (defun capitalize-word () (error "Unimplemented apitalize-word")) ;;; Key bindings (define-key *ctl-x-map* "C-u" 'upcase-region) (define-key *ctl-x-map* "C-l" 'downcase-region) (define-key *global-map* "M-u" 'upcase-word) (define-key *global-map* "M-l" 'downcase-word) (define-key *global-map* "M-c" 'capitalize-word)
2,168
Common Lisp
.lisp
50
41.42
77
0.756295
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
56235374ab7ff3c728400c12402f6b3fdbf108791ceb4dc9c4bb9b0dbc4aa0dd
18,437
[ -1 ]
18,438
global.lisp
spacebat_lice/src/global.lisp
(in-package :lice) (defconstant +debug-v+ 1) (defconstant +debug-vv+ 2) (defconstant +debug-vvv+ 3) (defparameter *debug-level* +debug-v+) ;;(defparameter *debug-level* +debug-vvv+) (defun dformat (lvl &rest fmt-args) (when (>= *debug-level* lvl) (with-open-file (f #p"/tmp/debug" :direction :output :if-exists :append :if-does-not-exist :create) (apply 'format f fmt-args)))) (defmacro verbose-body (&body body) "Print each sexpr in BODY and its return value." (let ((ret (gensym "RET"))) (loop for i in body collect `(let ((,ret ,i)) (format t "~s => ~s~%" ,i ,ret) ,ret)))) (defun last1 (l) "Return the last elt of the list." (car (last l))) (defun nconc1 (list item) "destructively append ITEM to the end of L" (nconc list (list item))) ;; (defun grow-vector (vector amt initial-element) ;; "grow the vector's size by AMT elements" ;; (adjust-array vector (+ (length vector) amt) ;; :initial-element initial-element ;; :fill-pointer t)) ;; (defun vector-append (vector1 vector2) ;; "append vector2 to the end of vector1." ;; (let ((len (length vector1))) ;; (grow-vector vector1 (length vector2) (elt vector2 0)) ;; (replace vector1 vector2 :start1 (1+ len) :start2 1))) (define-condition lice-condition () () (:documentation "The base condition for all lice related errors.")) (define-condition wrong-type-argument (lice-condition) ((:type :initarg :type :accessor wrong-type-argument-type))) ;; (defun fmt (fmt &rest args) ;; "A movitz hack function. FORMAT basically doesn't work, so i use this to get around it." ;; (let ((s (make-array 100 :fill-pointer 0 :element-type 'character))) ;; (apply #'format s fmt args) ;; s)) #+movitz (defun read-from-string (string) "Read the string and return an sexpr. This is a MOVITZ hack because it doesn't have read-from-string." (muerte::simple-read-from-string string)) ;;; Lisp function we like to have (defmacro while (test &body body) "If TEST yields non-nil, eval BODY... and repeat. The order of execution is thus TEST, BODY, TEST, BODY and so on until TEST returns nil." (if body `(loop while ,test do ,@body) `(loop while ,test))) (defvar *quit-code* 7 "The terminal char code for the interrupt key.") (defvar *inhibit-quit* nil ;; XXX: this is not correct docs "Non-nil inhibits C-g quitting from happening immediately. Note that `quit-flag' will still be set by typing C-g, so a quit will be signaled as soon as `inhibit-quit' is nil. To prevent this happening, set `quit-flag' to nil before making `inhibit-quit' nil.") (defvar *waiting-for-input* nil "T when we're waiting for .. input") (defvar *quit-flag* nil "Set to T when the user hit the quit key") (defmacro depricate (symbol refer-to) "A macro to mark a symbol as depricated. This is done with function in emacs whose purpose is better done another way. For example, a set- function replaced by a setf function. " `(setf (get (quote ,symbol) :depricated) (quote ,refer-to))) (defun read-string-with-escapes (stream close) "read in a string and handle \\f \\n \\r \\t \\v escape characters." (with-output-to-string (out) (do ((char (read-char stream nil :eof) (read-char stream nil :eof))) ((or (eq char :eof) (char= char close)) (if (eq char :eof) (error 'end-of-file :stream stream))) (when (char= char #\\) (setq char (read-char stream nil :eof)) (case char (:eof (error 'end-of-file :stream stream)) (#\f (setq char #\Page)) (#\n (setq char #\Newline)) (#\r (setq char #\Return)) (#\t (setq char #\Tab)) (#\v (setq char #\Vt)))) (write-char char out)))) ;; LiCE handles a few escape codes like GNU Emacs (set-macro-character #\" #'read-string-with-escapes) (defun run-hooks (&rest hooks) "Run each hook in HOOKS. Each argument should be a symbol, a hook variable. These symbols are processed in the order specified. If a hook symbol has a non-nil value, that value may be a function or a list of functions to be called to run the hook. If the value is a function, it is called with no arguments. If it is a list, the elements are called, in order, with no arguments. Major modes should not use this function directly to run their mode hook; they should use `run-mode-hooks' instead. Do not use `make-local-variable' to make a hook variable buffer-local. Instead, use `add-hook' and specify t for the LOCAL argument." (mapc (lambda (h) (when (symbolp h) (setf h (symbol-value h))) (mapc 'funcall h)) hooks)) (defun add-hook (hook function &optional append local) "Add to the value of HOOK the function function. FUNCTION is not added if already present. FUNCTION is added (if necessary) at the beginning of the hook list unless the optional argument append is non-nil, in which case function is added at the end. The optional fourth argument, LOCAL, if non-nil, says to modify the hook's buffer-local value rather than its default value. This makes the hook buffer-local if needed, and it makes t a member of the buffer-local value. That acts as a flag to run the hook functions in the default value as well as in the local value. HOOK should be a symbol, and FUNCTION may be any valid function. If HOOK is void, it is first set to nil. If HOOK's value is a single function, it is changed to a list of functions." (declare (ignore append local)) (pushnew function (symbol-value hook))) (defun remove-hook (hook function &optional local) "Remove from the value of HOOK the function FUNCTION. HOOK should be a symbol, and FUNCTION may be any valid function. If FUNCTION isn't the value of HOOK, or, if FUNCTION doesn't appear in the list of hooks to run in HOOK, then nothing is done. See `add-hook'. The optional third argument, LOCAL, if non-nil, says to modify the hook's buffer-local value rather than its default value." (declare (ignore local)) (setf (symbol-value hook) (remove function (symbol-value hook)))) (defun int-to-string (n) "Return the decimal representation of number as a string. Uses a minus sign if negative. number may be an integer or a floating point number." (check-type n number) (prin1-to-string n)) (defun split-string (string &optional (separators " ")) "Splits STRING into substrings where there are matches for SEPARATORS. Each match for SEPARATORS is a splitting point. The substrings between the splitting points are made into a list which is returned. ***If SEPARATORS is absent, it defaults to \"[ \f\t\n\r\v]+\". If there is match for SEPARATORS at the beginning of STRING, we do not include a null substring for that. Likewise, if there is a match at the end of STRING, we don't include a null substring for that. Modifies the match data; use `save-match-data' if necessary." ;; FIXME: This let is here because movitz doesn't 'lend optional' (let ((seps separators)) (labels ((sep (c) (find c seps :test #'char=))) (loop for i = (position-if (complement #'sep) string) then (position-if (complement #'sep) string :start j) while i as j = (position-if #'sep string :start i) collect (subseq string i j) while j)))) ;; A cheap memoizer. Obviously, a hashtable would be better. (defstruct memoize-state (data (vector nil nil nil nil nil nil nil nil nil nil nil nil)) (test 'equal) (pt 0)) (defun memoize-store (state thing value) (incf (memoize-state-pt state)) (when (>= (memoize-state-pt state) (length (memoize-state-data state))) (setf (memoize-state-pt state) 0)) (setf (svref (memoize-state-data state) (memoize-state-pt state)) (cons thing value)) value) (defmacro memoize (mem-var thing compute) "Check if we've computed a value for thing. if so, use it. if not compute it, store the result, and return it." (let ((match (gensym "MATCH"))) `(let ((,match (find ,thing (memoize-state-data ,mem-var) :key 'first :test (memoize-state-test ,mem-var)))) (if ,match (cdr ,match) (memoize-store ,mem-var ,thing ,compute))))) (defun add-to-list (list-var element &optional append) "Add ELEMENT to the value of LIST-VAR if it isn't there yet. The test for presence of ELEMENT is done with `equal'. If ELEMENT is added, it is added at the beginning of the list, unless the optional argument APPEND is non-nil, in which case ELEMENT is added at the end. The return value is the new value of LIST-VAR. If you want to use `add-to-list' on a variable that is not defined until a certain package is loaded, you should put the call to `add-to-list' into a hook function that will be run only after loading the package. `eval-after-load' provides one way to do this. In some cases other hooks, such as major mode hooks, can do the job." (if (member element (symbol-value list-var)) (symbol-value list-var) (set list-var (if append (append (symbol-value list-var) (list element)) (cons element (symbol-value list-var)))))) (defmacro defsubst (name lambda-list &body body) "Define an inline function. The syntax is just like that of `defun'." `(progn (declaim (inline ,name)) (defun ,name ,lambda-list ,@body))) (defvar *debug-on-error* t "Non-nil means enter the debugger if an unhandled error is signaled.") (defvar *debug-on-quit* nil "Non-nil means enter the debugger if quit is signaled (C-g, for example).") (defvar debug-ignored-errors nil "*List of errors for which the debugger should not be called. Each element may be a condition-name or a regexp that matches error messages. If any element applies to a given error, that error skips the debugger and just returns to top level. This overrides the variable `debug-on-error'. It does not apply to errors handled by `condition-case'.") (defun purecopy (thing) "Make a copy of object OBJ in pure storage. Recursively copies contents of vectors and cons cells. Does not copy symbols. Copies strings without text properties." thing) (defun garbage-collect () "Reclaim storage for Lisp objects no longer needed." (warn "unimplemented garbage-collect")) (provide :lice-0.1/global)
10,247
Common Lisp
.lisp
226
41.99115
112
0.70927
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
2622b25d59a4769304929e712c186b4a7dafb9d34aebd3e790ad3de47fba6e27
18,438
[ -1 ]
18,439
data.lisp
spacebat_lice/src/data.lisp
;;; data.lisp --- compatibility functions from emacs (in-package "LICE") (defun % (number divisor) "same as mod." (mod number divisor)) (defun setcar (cell newcar) "Set the car of cell to be newcar. Returns newcar." (setf (car cell) newcar)) (depricate aset (setf aref)) (defun aset (array idx newelt) "Store into the element of ARRAY at index IDX the value NEWELT. Return NEWELT. ARRAY may be a vector, a string, a char-table or a bool-vector. IDX starts at 0." (setf (aref array idx) newelt)) (defmacro defalias (to from &optional docstring) "Set SYMBOL's function definition to DEFINITION, and return DEFINITION. Associates the function with the current load file, if any. The optional third argument DOCSTRING specifies the documentation string for SYMBOL; if it is omitted or nil, SYMBOL uses the documentation string determined by DEFINITION." ;; FIXME: implement (declare (ignore to from docstring))) (defun plist-get (plist prop) "Extract a value from a property list. PLIST is a property list, which is a list of the form \(PROP1 VALUE1 PROP2 VALUE2...). This function returns the value corresponding to the given PROP, or nil if PROP is not one of the properties on the list." (getf plist prop)) (defun sequencep (object) "Return t if OBJECT is a sequence (list or array)." (typep object 'sequence)) (defun copy-sequence (seq) "Return a copy of a list, vector, string or char-table. The elements of a list or vector are not copied; they are shared with the original." (copy-seq seq))
1,536
Common Lisp
.lisp
37
39.486486
73
0.75721
spacebat/lice
3
1
0
GPL-2.0
9/19/2024, 11:27:44 AM (Europe/Amsterdam)
371de77d03a50d169c1bce8d5271dd47ad8f4233431228dfc03b1ad1046ab291
18,439
[ -1 ]