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
26,568
debugging.lisp
simoninireland_cl-vhdsl/src/hw/debugging.lisp
;; Some debgging support code ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Component visibility ---------- (defgeneric components-seen-by (c) (:documentation "Return a list of components 'seen' by C. C may be a component, a pin, or some other element. Including a component in the list means that component's pin interface may affect C in some way.")) (defmethod components-seen-by ((w wire)) (uniquify (map 'list #'component (pins w)))) (defmethod components-seen-by ((p pin)) (components-seen-by (wire p))) (defmethod components-seen-by ((b bus)) (uniquify (flatten (map 'list #'components-seen-by (wires b))))) (defmethod components-seen-by ((conn connector)) (uniquify (flatten (map 'list #'components-seen-by (pins conn))))) (defmethod components-seen-by ((s sequence)) (uniquify (flatten (map 'list #'components-seen-by s)))) (defmethod components-seen-by ((c component)) (let* ((pin-slots (pin-interface c)) (pins (flatten (map 'list #'(lambda (slot) (components-seen-by (slot-value c slot))) pin-slots)))) ;; remove the component itself (remove-if #'(lambda (comp) (equal comp c)) (uniquify pins))))
1,933
Common Lisp
.lisp
44
41.272727
75
0.712607
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
dcb45c61efd0b492e0a889ccb4488c05af5cbbcb6141038d3ce1d25c7c1e9226
26,568
[ -1 ]
26,569
package.lisp
simoninireland_cl-vhdsl/src/hw/package.lisp
;; Package for fully-software-emulated hardware ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :common-lisp-user) (defpackage cl-vhdsl/hw (:use :cl :alexandria :serapeum :cl-vhdsl) (:local-nicknames (:def :cl-vhdsl/def)) (:import-from :closer-mop #:standard-class #:class-slots #:class-direct-slots #:finalize-inheritance #:ensure-class-using-class #:compute-slots #:slot-definition-type #:slot-definition-name #:compute-effective-slot-definition #:effective-slot-definition-class #:class-precedence-list #:validate-superclass #:slot-value-using-class #:slot-definition-name) (:import-from :slot-extra-options #:def-extra-options-metaclass #:slot-exists-and-bound-p) (:import-from #:cl-ppcre #:scan-to-strings) (:export ;; ---------- Top-level interface ---------- ;; elements #:wire #:bus #:pin #:connector #:component ;; MOP #:metacomponent #:guarded ;; common generic operations over elements #:name #:pins #:wires #:components #:width #:state #:fully-wired-p #:floating-p ;; standard components and mixins #:enabled #:clocked #:readwrite #:register #:latch #:register-value #:alu #:ram #:ram-size #:ram-elements #:ring-counter ;; well-known pins #:clock #:enable #:readwrite ;; operations #:ensure-pin-state #:ensure-fully-wired #:pin-interface #:pin-interface-p #:pin-states #:pins-value #:configure-pin-for-role #:slot-connector #:enabled-p #:write-enabled-p #:read-enabled-p #:subcomponent-p #:subcomponent-interface #:wiring-diagram #:connect-slots #:connect-pins ;; behavioural callbacks #:on-pin-changed #:on-pin-triggered #:on-enabled #:on-disabled ;; macro interface #:defcomponent #:connect-component ;; debugging #:components-seen-by ;; conditions #:conflicting-asserted-values #:reading-floating-value #:reading-non-reading-pin #:unrecognised-alu-operation #:mismatched-wires #:non-component-type #:non-pin-interface-slot #:invalid-wiring-diagram-slot #:incompatible-pin-widths #:incompatible-pin-slot-widths #:invalid-endpoint #:not-fully-wired ;; ---------- Inner interface ---------- ;; components #:configure-pin-for-role #:pin-role-for-slot #:pin-slots-for-roles ;; wires and pins #:wire-state #:wire-pin-assertions #:wire-add-pin #:pin-tristated-p #:pin-reading-p #:pin-asserted-p #:pin-floating-p #:pin-wired-p #:pin-state ;; micro-instructions #:microinstruction #:run-microinstruction #:defmicroinstruction ))
3,404
Common Lisp
.lisp
138
21.144928
75
0.690366
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4afc24459774b63aeef26d492f9c3879c588998c0e8d3f9a529a0182b5700834
26,569
[ -1 ]
26,570
ram.lisp
simoninireland_cl-vhdsl/src/hw/ram.lisp
;; Software-emulated RAM ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) (defclass ram (component enabled clocked readwrite) ((address-width :documentation "The width of the address bus, in bits." :initarg :address-bus-width :initform 16) (data-width :documentation "The width of the data bus, in bits." :initarg :data-bus-width :initform 8) (address-bus :documentation "The address bus." :initarg :address-bus :pins address-width :role :io :reader ram-address-bus) (data-bus :documentation "The data bus." :initarg :data-bus :pins data-width :role :io :reader ram-data-bus) (elements :documentation "The memory elements." :reader ram-elements)) (:metaclass metacomponent) (:documentation "An emulated random-access memory (RAM). The RAM is parameterised by its address and data bus widths in bits. It needs address and data lines, a clock, an enable, and a write enable.")) (defmethod initialize-instance :after ((mem ram) &rest initargs) (declare (ignore initargs)) (setf (slot-value mem 'elements) (make-array (list (ram-size mem)) :initial-element 0))) (defun ram-size (mem) "Return the size of MEM in elements. The size of elements is determined by the width of the data bus." (floor (expt 2 (slot-value mem 'address-width)))) (defmethod on-pin-triggered ((mem ram) p (v (eql 1))) (declare (ignore p)) ;; we only have one trigger pin (when (write-enabled-p mem) ;; write the data from the data bus to the addressed slot (let ((v (pins-to-value (ram-data-bus mem))) (addr (pins-to-value (ram-address-bus mem)))) (setf (aref (ram-elements mem) addr) v)))) (defmethod on-pin-changed ((mem ram)) (when (not (write-enabled-p mem)) ;; put the value of the memory addressed on the ;; address bus onto the data bus, as long as the ;; address bus is itself stable (when (not (floating-p (ram-address-bus mem))) (let ((addr (pins-value (ram-address-bus mem)))) (setf (pins-value (ram-data-bus mem)) (aref (ram-elements mem) addr)))))) (defmethod on-enable ((mem ram)) ;; read from the buses (setf (pin-states (ram-address-bus mem)) :reading) (setf (pin-states (ram-data-bus mem)) :reading)) (defmethod on-disable ((mem ram)) ;; tristate the buses (setf (pin-states (ram-address-bus mem)) :tristate) (setf (pin-states (ram-data-bus mem)) :tristate))
3,167
Common Lisp
.lisp
80
36.2375
75
0.705442
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4772a7ffaa10c119a1ca018636cd5e7b67bb75bbc19c76482ac12d0c55d37a93
26,570
[ -1 ]
26,571
alu.lisp
simoninireland_cl-vhdsl/src/hw/alu.lisp
;; Software-emulated arithmetic logic unit ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- ALU ---------- (defclass alu (component enabled) ((width :documentation "The width of the ALU." :initarg :width :initform 8 :reader width) (a-bus :documentation "The ALU's A-side data bus." :initarg :a-bus :pins width :role :reading :reader alu-a-bus) (b-bus :documentation "The ALU's B-side data bus." :initarg :b-bus :pins width :role :reading :reader alu-b-bus) (c-bus :documentation "The ALU's C-side (results) bus." :initarg :c-bus :pins width :role :io :reader alu-c-bus) (op-bus :documentation "The ALU's operation-select bus." :initarg :op-bus :pins 3 :role :control :reader alu-op-bus)) (:metaclass metacomponent) (:documentation "An integer arithmetic logic unit. An ALU is connected to four buses: the A- and B-side buses, which provide operands; the C-side bus that generates the output; and the operation-select bus that determines the operation the ALU performs. The available operations are: - #2r000 a (pass-through) - #2r001 a AND b - #2r010 a OR b - #2r011 NOT a - #2r100 a + b - #2r101 a - b - #2r110 a + 1 (increment) - #2r111 a - 1 (decrement) The ALU is an entirely combinatorial component. The value on the C-side represents the results of computing over the A- and B-sides, and is updated whenever those values change and the component is enabled. There is no clock interface.")) ;; TODO Add carry bit (defmethod on-pin-changed ((a alu)) ;; perform the encoded operation (let* ((op (pins-value (alu-op-bus a))) (v (switch (op) ;; pass-through (#2r000 (pins-value (alu-a-bus a))) ;; logical and (#2r001 (logand (pins-value (alu-a-bus a)) (pins-value (alu-b-bus a)))) ;; logical or (#2r010 (logior (pins-value (alu-a-bus a)) (pins-value (alu-b-bus a)))) ;; logical not (#2r011 (lognot (pins-value (alu-a-bus a)))) ;; addition (#2r100 (+ (pins-value (alu-a-bus a)) (pins-value (alu-b-bus a)))) ;; subtraction (#2r101 (- (pins-value (alu-a-bus a)) (pins-value (alu-b-bus a)))) ;; increment (a-side only) (#2r110 (1+ (pins-value (alu-a-bus a)))) ;; decrement (a-side only) (#2r111 (1- (pins-value (alu-a-bus a)))) ;; no need for this at the moment as all bit patterns ;; are meaningful (t (error 'unrecognised-alu-operation :opcode op :a (pins-value (alu-a-bus a)) :b (pins-value (alu-b-bus a))))))) ;; update the output pins (setf (pins-value (alu-c-bus a)) v))) (defmethod on-enable ((a alu)) (setf (pin-states (alu-a-bus a)) :reading) (setf (pin-states (alu-b-bus a)) :reading) (setf (pin-states (alu-op-bus a)) :reading)) ;; TODO This retains the output on the c-bus -- should it be tristated instead? (defmethod on-disable ((a alu)) (setf (pin-states (alu-a-bus a)) :tristate) (setf (pin-states (alu-b-bus a)) :tristate) (setf (pin-states (alu-op-bus a)) :tristate))
3,875
Common Lisp
.lisp
110
31.218182
79
0.657937
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
8f85f2fc8f06707c479d3d4d3933f5732dce6289272f31333134b62801b8dabd
26,571
[ -1 ]
26,572
control.lisp
simoninireland_cl-vhdsl/src/hw/control.lisp
;; Software-emulted control units ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Control units ---------- ;; The controller is a source of micro-instructions, in the sense that ;; it generates a stream of them to control its components. Where ;; those instructions come from is somewhat irrelevent: we chuld be ;; able to abstract over explicit decoding, microcoded instructions, ;; and other forms within the same framework. (defclass control (component clocked) () (:documentation "A control unit. Control units emit micro-instructions to control the rest of the system. The micro-instuctions are themselves composed of nano-instructions that define the states of control lines for components, one nano-instruction per component. The control unit itself is a finite-state machine that emits micro-instructions when triggered by the clock. "))
1,606
Common Lisp
.lisp
35
44.571429
79
0.772379
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c2f3ca3b3c8e5f944bd4729396a53d381410b175ba603e93ac44d0010352ff0f
26,572
[ -1 ]
26,573
ring-counter.lisp
simoninireland_cl-vhdsl/src/hw/ring-counter.lisp
;; Software-emulated ring counter ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) (defclass ring-counter (enabled component clocked) ((width :documentation "The width of the ring counter." :initarg :width :reader width) (count :documentation "The current count." :initform 0 :accessor ring-counter-count) (counter-bus :documentation "The lines taking the count." :initarg :bus :pins width :role :io)) (:metaclass metacomponent) (:documentation "A ring counter. This converts a count of clock edges intoan asserted wire on its counter bus. When reset it asserts line 0; at the next clock pulse it de-asserts line 0 and asserts line 1; and so on, until its width is exceeded and it wraps-around back to 0.")) (defmethod initialize-instance :after ((rc ring-counter) &rest initargs) (declare (ignore initargs)) (ring-counter-reset rc)) (defun ring-counter-reset (rc) "Reset the counter." (setf (ring-counter-count rc) 0)) (defmethod (setf ring-counter-count) (v (rc ring-counter)) ;; wrap the count if needed (if (>= v (width rc)) (setq v 0) (setf (slot-value rc 'count) v)) ;; update the asserted pin (let ((mask (ash 1 v))) (setf (pins-value (slot-value rc 'counter-bus)) mask))) (defmethod on-pin-triggered ((rc ring-counter) p (v (eql 1))) (declare (ignore p)) ;; increment the count (incf (ring-counter-count rc)))
2,157
Common Lisp
.lisp
57
35
75
0.722302
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0a8cb8f92579899b6a687f880a20013bfdc6769d295402a373b0ba945cbc628b
26,573
[ -1 ]
26,574
conditions.lisp
simoninireland_cl-vhdsl/src/hw/conditions.lisp
;; Conditions for emulated hardware components ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Wires and pins ---------- (define-condition conflicting-asserted-values () ((wire :documentation "The wire on which the conflict occurs." :initarg :wire :reader conflicting-asserted-values-wire)) (:report (lambda (c str) (format str "Components are asserting conflicting values on wire ~a" (conflicting-asserted-values-wire c)))) (:documentation "Condition signalled when two conflicting values are asserted on a wire. Values conflict when more than one component attached to a wire asserts a value on it, i.e., is not tri-stated.")) (define-condition reading-floating-value () ((pin :documentation "The pin being read." :initarg :pin :reader reading-floating-value-pin)) (:report (lambda (c str) (let ((p (reading-floating-value-pin c))) (format str "Pin ~a is reading a floating value from ~a" p (wire p))))) (:documentation "Condition signalled when a pin reads a floating value. This is almost certainly an error, as it suggests that the component expects a logic value but isn't getting one, presumably because no other component is asserting a value on the wire.")) (define-condition reading-non-reading-pin () ((pin :documentation "The pin being read." :initarg :pin :reader reading-non-reading-pin-pin)) (:report (lambda (c str) (format str "Pin ~a is not configured for reading." (reading-non-reading-pin-pin c)))) (:documentation "Condition signalled when reading a non-reading pin. This usually happens when a pin is tristated by accident. It is almost certainly an error in wiring or configuraton,")) (define-condition mismatched-wires () ((component :documentation "The component the wires are being attached to." :initarg :component :reader mismatched-wires-component) (slot :documentation "The slot on the component being wired-up." :initarg :slot :reader mismatched-wires-slot) (expected :documentation "The number of wires expected" :initarg :expected :reader mismatched-wires-expected) (got :documentation "The number of wires received." :initarg :received :reader mismatched-wires-received)) (:report (lambda (c str) (format str "Expected ~s wires for slot ~s on component ~s, got ~s" (mismatched-wires-expected c) (mismatched-wires-slot c) (mismatched-wires-component c) (mismatched-wires-received c)))) (:documentation "Condition signalled when an unexpected number of wires is received. This is probably a mismatch between the width of a bus and the width of the pin interface slot it is being attached to.")) ;; ---------- Components ---------- (define-condition non-component-type () ((type :documentation "The type encountered." :initarg :type :reader non-component-type)) (:report (lambda (c str) (format str "The type ~s is not a component type" (non-component-type c)))) (:documentation "Condition signalled when a non-component type is encountered. This typically happens when trying to build a micro-instruction when there is a non-component slot.")) (define-condition non-pin-interface-slot () ((component :documentation "The component." :initarg :component :reader non-pin-interface-component) (slot-name :documentation "The slot name." :initarg :slot :reader non-pin-interface-slot)) (:report (lambda (c str) (format str "The slot ~s is not in component ~s's pin interface" (non-pin-interface-slot c) (non-pin-interface-component c)))) (:documentation "Condition signalled when a slot is not in the pin interface. The pin interface consists of slots with a `:pins' value, representing hardware interfaces. This condition almost certainly comes from the use of the wrong slot name, or a missing declaration in the component's class.")) ;; ---------- Standard components ---------- (define-condition unrecognised-alu-operation () ((opcode :documentation "The opcode for the operation requested." :initarg :opcode :reader unrecognised-alu-operation-opcode) (a :documentation "The a-side operand." :initarg :pin :reader unrecognised-alu-operation-a) (b :documentation "The b-side operand." :initarg :pin :reader unrecognised-alu-operation-b)) (:report (lambda (c str) (format str "ALU operation can't be performed (opcode ~a, a=~a, b=~a)" (unrecognised-alu-operation-opcode c) (unrecognised-alu-operation-a c) (unrecognised-alu-operation-b c)))) (:documentation "Condition signalled when an ALU cannot perform an operation. This is likely to be caused by an unrecognised opcode being presented to the ALU's operation-select bus. It might also be an issue with the operands.")) ;; ---------- Wiring ---------- (define-condition incompatible-pin-widths () ((coonnector :documentation "The connector." :initarg :connector :reader incompatible-pin-widths-connector) (bus :documentation "The bus." :initarg :bus :reader incompatible-pin-widths-bus)) (:report (lambda (c str) (format str "Connector width ~a doesn't match bus width ~s" (width (incompatible-pin-widths-connector c)) (width (incompatible-pin-widths-bus c))))) (:documentation "Condition signalled when wiring incompatible connectors and buses. The widths of buses and connectors need to be the same.")) (define-condition invalid-wiring-diagram-slot () ((slot-name :documentation "The slot name." :initarg :slot :reader wiring-diagram-slot) (component :documentation "The component." :initarg :component :reader wiring-diagram-component)) (:report (lambda (c str) (format str "No slot ~s in wiring diagram for ~s" (witing-diagram-slot c) (wiring-diagram-component c)))) (:documentation "Condition signalled when an invalid slot appears in a wiring diagram. This is certainly an error, typically caused by mis-typing a slot name or using a slot that's not known to be present given the defined type of a sub-component.")) (define-condition incompatible-pin-slot-widths () ((slots-names :documentation "The slot names whose widths are being determined." :initarg :slot-names :reader incompatible-pin-slot-widths-slot-names) (unknown :documentation "Flag as to whether the width is unknown." :initarg :unknown :initform nil :reader incompatible-pin-slot-widths-unknown) (first :documentation "The first known width (if any)." :initarg :first :reader incompatible-pin-slot-widths-first) (second :documentation "The second known width (if any)." :initarg :second :reader incompatible-pin-slot-widths-second)) (:report (lambda (c str) (if (slot-value c 'unknown) ;; no width could be determined (format str "The widths of slots ~a cdan't be determined" (incompatible-pin-slot-widths-slot-names c)) ;; two incompatible widths were determined (format str "The pin slot widths ~a and ~a are incompatible when wiring ~a" (incompatible-pin-slot-widths-first c) (incompatible-pin-slot-widths-second c) (incompatible-pin-slot-widths-slot-names c))))) (:documentation "Condition signalled when two pin slots have incompatible widths. This happens when two slots are wired together but have different widths, or when no wodth can be determined at all. It must be possible to find exactly one width for all the pin slots.")) (define-condition invalid-endpoint () ((component :documentation "The component with the invalid endpoint." :initarg :component :reader invalid-endpoint-component) (endpoint :documentation "The endpoint." :initarg :endpoint :reader invalid-endpoint)) (:report (lambda (c str) (format str "Invalid endpoint ~a on ~a" (invalid-endpoint c) (invalid-endpoint-component c)))) (:documentation "Condition signalled when an invalid endpoint appears in a wiring diagram. Each endpoint must either be a symbol on the component that identofies a pin slot, or a pair of symbols identifying a slot containing a sub-component and a pin slot on that component.")) (define-condition not-fully-wired () ((elements :documentation "The elements that remain fully or partially unwired." :initarg :elements :reader not-fully-wired-elements) (pins :documentation "The unwired pins." :initarg :pins :reader not-fully-wired-pins)) (:report (lambda (c str) (format str "Some elements remain unwired: ~a (pins ~a)" (not-fully-wired-elements c) (not-fully-wired-pins c)))) (:documentation "Condition signalled when some elements remain unwired. Unwired elements may not be an error -- but usually are. Fix by connecting the unwired elements to wires. The condition includes both the elements and the pins that remain unwired, which may simplify finding the problem for complicated wiring diagrams."))
9,823
Common Lisp
.lisp
232
38.284483
92
0.726016
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
51ab2982c3616ce516fad1a99246db07d0031d2c0dbb5c1741edb0730eae67c1
26,574
[ -1 ]
26,575
microinstruction.lisp
simoninireland_cl-vhdsl/src/hw/microinstruction.lisp
;; Micro-instructions ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Micro-instrutions ---------- (defclass microinstruction () ((system :documentation "The system this metainstruction controls." :initarg :system) (value :documentation "The value of the micro-instruction, as a bit field." :initform 0 :accessor microinstruction-bitfield) (mi-bus :documentation "The control bus on whch micro-instructions are issued." :initarg :bus :reader microinstruction-bus)) (:documentation "Base class for micro-instructions. This class isn't used directly. It serves as the base class for micro-instructions created for specific systems, usually using ther `defmicroinstructions' macro.")) (defgeneric run-microinstruction (mi) (:documentation "Run the micro-instruction MI against its system. This places the value of the micro-instruction onto the bus.")) (defmethod run-microinstruction ((mi microinstruction)) (pins-from-value (microinstruction-bus mi) (microinstruction-bitfield mi))) ;; ---------- The sub-classes constructed for specific systems ---------- (defun component-slot (slot-def) "Test whether SLOT-DEF is a slot holding a component. Component slots have a :type attribute that holds a class that is a sub-type of `component'. Returns the type of the component, or nil." (if-let ((type (slot-definition-type slot-def))) (if (subtypep type 'component) ;; return the class associated with the type (find-class type)))) (defun mi-slot-name-for-slot (pin-slot component-slot-def) "Compute the slot name used for a micro-instruction for PIN-SLOT on CL. The name is constructed for PIN-SLOT on the component held within COMPONENT-SLOT-DEF. The slot name is interned into the same package as COMPONENT-SLOT-DEFs name to ensure it's accessed from the same scope." (let* ((component-symbol (slot-definition-name component-slot-def)) ;; create the name for the new slot (component-name (symbol-name component-symbol)) (pin-slot-name (symbol-name pin-slot)) (mi-slot-name (str:concat component-name "/" pin-slot-name)) ;; create the new slot's name as a symbol interned into the correct package (component-package (symbol-package component-symbol)) (mi-slot (intern mi-slot-name component-package))) mi-slot)) (defun mi-pin-slots (cl) "Return the slot definitions for the micro-instruction pin interface of CL." (let ((slot-defs (class-slots cl)) nano-slots) (dolist (slot-def slot-defs) ;; construct a new slot per pin interface slot in an appropriate role (when-let* ((type (component-slot slot-def))) (let ((pin-slots (pin-slots-for-roles type (list :control)))) (dolist (pin-slot pin-slots) (let ((mi-slot-name (mi-slot-name-for-slot pin-slot slot-def))) (setf nano-slots (cons mi-slot-name nano-slots))))))) ;; return the constructed slots nano-slots)) ;; ---------- Macro interface ---------- (defun declare-mi-pin-slot (mi-pin-slot-name) "Return the code to declare the MI-PIN-SLOT-NAME in the micro-instruction." ;; we need to intern the symbol name into th keywords package ;; for use an the initial argument (let ((mi-pin-slot-keyword (intern (symbol-name mi-pin-slot-name) "KEYWORD"))) `(,mi-pin-slot-name :initarg ,mi-pin-slot-keyword))) (defun declare-mi-slot-initarg (mi mi-slot-name) "Return the code to install the value of MI-SLOT-NAME. The value is assumed to be passed using the key MI-SLOT-NAME and is assigned to the object MI, which should be a symbol." `(setf (slot-value ,mi ',mi-slot-name) ,mi-slot-name)) (defun declare-mi-class (cl mi-pin-slot-names) "Return the code declaring the micro-instruction class named CL. MI-PIN-SLOT-NAMES provides the slots to include." (let ((mi-pin-slot-decls (mapcar #'declare-mi-pin-slot mi-pin-slot-names))) `(defclass ,cl (microinstruction) (,@mi-pin-slot-decls) (:documentation "Micro-instructions controlling a system.")))) (defun declare-mi-initialize-instance (cl mi-pin-slot-names) "Return the code defining `initialize-instance' for the micro-instruction CL." (with-gensyms (mi initargs) (let ((mi-pin-slot-initargs (mapcar #'(lambda (mi-slot-name) (declare-mi-slot-initarg mi mi-slot-name)) mi-pin-slot-names))) `(defmethod initialize-instance :after ((,mi ,cl) &rest ,initargs &key ,@mi-pin-slot-names &allow-other-keys) (declare (ignore ,initargs)) ,@mi-pin-slot-initargs)))) (defmacro defmicroinstruction (cl (system) &body body) "Define the class CL of micro-instructions for controlling SYSTEM." (declare (ignore body)) (let* ((mi-pin-slot-names (mi-pin-slots (find-class system))) (mi-class (declare-mi-class cl mi-pin-slot-names)) (mi-initialize-instance (declare-mi-initialize-instance cl mi-pin-slot-names))) `(progn ;; define the micro-instruction class ,mi-class ;; define the initialiser for instances ,mi-initialize-instance )))
5,782
Common Lisp
.lisp
123
43.373984
80
0.723616
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
b9fc3dae3ca24a7f7043e0a8c445c5f03d4ee8c7615432d66e9583aa66f739c2
26,575
[ -1 ]
26,576
register.lisp
simoninireland_cl-vhdsl/src/hw/register.lisp
;; Software-emulated registers ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Simple registers ---------- (defclass register (component enabled clocked readwrite) ((width :documentation "The width of the register." :initarg :width :initform 8 :reader width) (value :documentation "The register's current value." :initarg :value :initform 0 :accessor register-value) (data-bus :documentation "The data bus the register is connected to." :initarg :bus :pins width :role :io :reader data-bus)) (:metaclass metacomponent) (:documentation "A register. Registers must be connected to a bus and three wires. The data bus must have at least as many wires as the register. The three other wires are for clock, register enable, and write enable. When write is enabled then at the next rising clock edge then the value of the register will be written from the bus. When write is disabled, read is enabled and the value of the register will be made available on the bus. Write-enable should be see from the perspective of a client outside the register.")) (defmethod on-pin-triggered ((r register) p (v (eql 1))) (declare (ignore p)) ;; we only have one trigger pin (when (write-enabled-p r) (register-value-from-bus r (data-bus r)))) (defmethod on-pin-changed ((r register)) (if (write-enabled-p r) ;; set all data bus pins to :reading (setf (pin-states (data-bus r)) :reading) ;; put the value of the register onto the data bus pins (register-value-to-bus r (data-bus r)))) (defmethod on-enable ((r register)) ;; set the data bus pins to reading (setf (pin-states (data-bus r)) :reading)) (defmethod on-disable ((r register)) ;; tri-state the data bus (setf (pin-states (data-bus r)) :tristate)) (defun register-value-to-bus (r b) "Move the value of R to the pins of bus B." (setf (pins-value b) (register-value r))) (defun register-value-from-bus (r b) "Make the value on the pins of bus B the value of R. This implies that the pins are all :reading." (setf (slot-value r 'value) (pins-value b))) ;; ---------- ALU registers ---------- (defclass latch (register) ((latched-bus :documentation "The bus showing the latched value." :initarg :latched-bus :pins width :role :io :reader latched-bus)) (:metaclass metacomponent) (:documentation "A latch. A latch is a register that also provides a way of \"peeking\" at its value in a way that's always visible regardless of whether the latch is enabled or not. The `data-bus' connector is used to read and write the latch just like a register; the `latched-bus' connector makes the latched value available. A typical use for latches is attaching a register to an ALU, where the value is made available constantly for arithmetic but whose update and access via the data bus are controlled.")) ;; This logic is in the triggering even because that's the only time the ;; value of the register should change. (defmethod on-pin-triggered :after ((l latch) p (v (eql 1))) (declare (ignore p)) ;; we only have one trigger pin ;; put the value on the latched bus too (if (write-enabled-p l) (register-value-to-bus l (latched-bus l))))
4,004
Common Lisp
.lisp
95
39.242105
75
0.722165
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f106e92c851c0f618930647588337f175a41aa8dd623458a59c5607119001e50
26,576
[ -1 ]
26,577
component.lisp
simoninireland_cl-vhdsl/src/hw/component.lisp
;; Base class for fully-software-emulated hardware components ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Components ---------- (defclass component () ((name :documentation "The readable name of the component." :initarg :name :reader name)) (:metaclass metacomponent) (:documentation "A component in an architecture. Components encapsulate functions and offer a pin-based interface.")) ;; We add an :after method for `initialize-instance' to create the pins ;; for all slots in the pin interface for which we know their width. ;; We then wire-up these components and slots by calling ;; `connect-component' and finally call `component-pins-changed' to ;; let the component set up its internal state to be consistent with ;; its initial pin values. ;; ;; If sub-classes add additional :after methods specialised against ;; themselves, these will see a component that's fully wired-up ;; according to any embeded wiring diagram. ;; ;; The :after method should probably be decomposed to let the ;; individual elements be called/overridden programmatically (defun component-width-of-slot (c slot-def) "Return the width of SLOT-DEF on C." (let ((w (slot-value slot-def 'pins))) (if (and (symbolp w) (not (eql w t))) ;; t = undefined ;; width derived from the value of another slot (slot-value c w) ;; width as given w))) (defmethod initialize-instance :after ((c component) &rest initargs) (declare (ignore initargs)) ;; create the slots and connectors for the pin interface (let* ((slot-defs (class-slots (class-of c))) (pin-slot-defs (remove-if-not #'slot-def-in-pin-interface-p slot-defs))) (dolist (slot-def pin-slot-defs) (let* ((slot (slot-definition-name slot-def)) ;; number of wires in the slot (width (component-width-of-slot c slot-def)) ;; role the slot fulfills ;; (set by `compute-effective-slot-definition' if omitted) (role (slot-value slot-def 'role)) ;; wires the slot's pins should be connected to (bus (if (slot-exists-and-bound-p c slot) (slot-value c slot)))) ;; sanity check any wiring (when bus ;; we accept single wires and single pins (unless (typep bus 'bus) (let ((wire-or-pin bus)) (etypecase wire-or-pin (wire (setq bus (make-instance 'bus :width 1)) (setf (elt (wires bus) 0) wire-or-pin)) (pin (setq bus (make-instance 'bus :width 1)) (setf (elt (wires bus) 0) (wire wire-or-pin)))))) ;; check widths match (let ((bus-width (width bus))) (cond ((eql width t) ;; no width, set it to the number of ;; wires on the bus we've been given (setq width bus-width)) ;; wrong number of wires, signal an error ((not (equal bus-width width)) (error 'mismatched-wires :component c :slot slot :expected width :received bus-width))))) ;; create the connector (setf (slot-value c slot) (if (not (equal width t)) (let ((conn (make-instance 'connector :width width :component c :role role))) ;; if we've been given a bus, connect it (when bus (connect-pins conn bus)) conn)))))) ;; wire-up the slots we created using the wiring diagram (connect-component c) ;; TODO make sure all sub-component slots that have objects have ;; all their slots wired ;; make sure we're in a state consistent with our initial pins (on-pin-changed c)) ;; ---------- Pin interface ---------- (defmethod pin-interface ((c component)) (pin-interface (class-of c))) (defun pin-interface-p (c slot) "Test whether SLOT is in the pin interface of C. Returns nil if SLOT either isn't a slot in C's pin interface, or isn't a slot of C at all." (not (null (member slot (pin-interface c))))) (defun pin-role-for-slot (c slot) "Return the role assigned to the pins of SLOT in class CL. SLOT must be in C's pin interface." (let ((slot-def (find-pin-slot-def (class-of c) slot :fatal t))) (slot-value slot-def 'role))) (defun pin-slots-for-roles (c roles) "Extract all the slots in the pin interface of C having roles in ROLES. C may be a comppnent or a component class." (remove-if-not #'(lambda (slot) (member (pin-role-for-slot c slot) roles)) (pin-interface c))) ;; This includes only the pin on the component, not on its sub-components (defmethod pins ((c component)) (let ((pin-slots (pin-interface c))) (mapappend #'(lambda (slot) (pins (slot-value c slot))) pin-slots))) ;; ---------- Pin roles ---------- (defgeneric configure-pin-for-role (pin role) (:documentation "Set up PIN suitable for ROLE. Methods can specialise this function to configure pins appropriatly for new roles. The standard roles are: - `:io' for I/O pins that can be read from and written to - `:reading' for pins that can only be read from - `:control' for control pins permanently in `:reading' mode - `:status' for pins reporting component status - `:trigger' for pins that respond to a leading or trailing edge, typically clock pins")) (defmethod configure-pin-for-role (pin (role (eql :io))) (setf (state pin) :tristate)) (defmethod configure-pin-for-role (pin (role (eql :reading))) (setf (state pin) :reading)) (defmethod configure-pin-for-role (pin (role (eql :control))) (setf (state pin) :reading)) (defmethod configure-pin-for-role (pin (role (eql :status))) (setf (state pin) 0)) (defmethod configure-pin-for-role (pin (role (eql :trigger))) (setf (state pin) :trigger)) ;; ---------- Behavioural interface ---------- (defgeneric on-pin-changed (c) (:method-combination guarded) (:documentation "Callback called when the values asserted on pins of component C change. This happens for changes on `:reading' and `:control' pins only. Changes to tristated pins are ignored; changes to `:trigger' pins cause a `pin-triggered' callback. The methods on this function are guarded, meaning that methods may implement the `:if' qualifier to conditionally prevent execution of the method if the guard evaluates to false.") ;; default callback is empty (:method ((c component)))) (defgeneric on-pin-triggered (c p v) (:method-combination guarded) (:documentation "Callback called when trigger pin P on component C transitions to V. This method can be specialised using `eql' to only be fired on (for example) rising transitions to 1. The methods on this function are guarded, meaning that methods may implement the `:if' qualifier to conditionally prevent execution of the method if the guard evaluates to false.") ;; default callback is empty (:method ((c component) p v))) ;; ---------- Sub-components ---------- (defmethod subcomponent-interface ((c component)) (subcomponent-interface (class-of c))) (defun subcomponent-p (c slot) "Test whether SLOT holds a sub-component of C." (not (null (member slot (subcomponent-interface c))))) (defun subcomponent-type (cl slot) "Return the type of the sub-components expected in SLOT of component class CL." (let ((slot-def (find slot (class-slots cl) :key #'slot-definition-name))) (slot-definition-type slot-def))) (defmethod components ((c component)) (mapcar #'(lambda (slot) (slot-value c slot)) (subcomponent-interface c))) ;; ---------- Integral wiring diagrams ---------- (defun ensure-wire-description-endpoint (cl endpoint) "Parse ENDPOINT against class CL. Check the endpoint is valid, meaning that it is a symbol naming a pin slot on CL or a pair of symbols naming a sub-component slot on CL and a pin slot on that sub-component." (or (cond ((symbolp endpoint) ;; slot on this component (pin-interface-p cl endpoint)) ((consp endpoint) ;; slot on a sub-component (let* ((cslot (car endpoint)) (slot-type (subcomponent-type cl cslot))) (if slot-type (let ((slot (safe-cadr endpoint))) (ensure-wire-description-endpoint (find-class slot-type) slot)))))) ;; if we fall through, the endpoint was invalid (error 'invalid-endpoint :component cl :endpoint endpoint))) (defun ensure-wire-description (cl wiredesc) "Parse WIREDESC against class CL and check validity." (every #'(lambda (endpoint) (ensure-wire-description-endpoint cl endpoint)) wiredesc)) (defun ensure-wiring-diagram (cl wires) "Parse the WIRES give for class CL." (if (every #'(lambda (wiredesc) (ensure-wire-description cl wiredesc)) wires) wires)) (defun endpoint-connector (c endpoint) "Return the connector for ENDPOINT on C." (if (symbolp endpoint) (slot-value c endpoint) (slot-value (slot-value c (car endpoint)) (safe-cadr endpoint)))) ;; TODO This will fall foul of pin slots with widths of T, which can ;; be connected top any "appropriate" bus. (defun connect-wire (c w) "Connect all the slots in W within C." (let (b) (dolist (endpoint w) (let ((conn (endpoint-connector c endpoint))) ;; make sure we have a bus to connect to (if (null b) (setq b (make-instance 'bus :width (width conn)))) ;; connect the wires (connect-pins conn b))))) (defgeneric connect-component (c) (:documentation "Internally wire C according to its wiring diagram. This function is called automatically by `make-instance' when a component is instanciated, and wires-up any class-wide wiring diagram. It can be specialised to add more behaviours.")) ;; TODO we should sanity-check the wiring disagram at compile time, from ;; within metacomponent. (defmethod connect-component ((c component)) (let* ((cl (class-of c)) (diagram (wiring-diagram cl)) (wires (ensure-wiring-diagram cl diagram))) (dolist (wire wires) (connect-wire c wire))))
10,485
Common Lisp
.lisp
248
38.71371
90
0.705569
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0b0c000d61a5c9f77bab2688b767d47ff02b438024a8d1ef35b6a18146daebbd
26,577
[ -1 ]
26,578
arch.lisp
simoninireland_cl-vhdsl/src/hw/arch.lisp
;; Underlying services for fully-software-emulated hardware components ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Generic functions ---------- (defgeneric name (e) (:documentation "Return the user-readable name of element E.")) (defgeneric pins (e) (:documentation "Return a list of all the pins on element E.")) (defgeneric state (e) (:documentation "Return the state of element E.")) (defgeneric wires (e) (:documentation "Return all the wires connected to element E.")) (defgeneric components (e) (:documentation "Return all the components connected to element E. If E is a component itself, this will include all sub-components. ")) (defgeneric width (e) (:documentation "Return the width in bits of element E.")) (defgeneric floating-p (e) (:documentation "Test whether element E has any floating values. Floating values are usually (although not necessarily) an error.")) (defgeneric fully-wired-p (e) (:method-combination and) (:documentation "Test whether element E is fully wired. Dangling wires are usually (although not necessarily) an error. Use `ensure-fully-wired' to test a set of elements at once and signal an error if there are dangling wires. Additional methods added to this function must use the \"and\" qualifier, and are treated as a conjunction,") ;; the default checks that all pins are wired (:method and (e) (null (remove-if #'pin-wired-p (pins e))))) ;; ---------- Wires ---------- (defclass wire () ((state :documentation "The state of the wire." :initform :floating :initarg :state :reader state) (pins :documentation "List of pins attached to the wire." :initform '() :accessor pins) (assertions-table :documentation "A mapping from asserted value to the pins asserting it." :initform (make-hash-table) :reader wire-pin-assertions)) (:documentation "A wire. Wires connect several components together. Each pin connected to a wire can have one of several states: - 0 or 1, the logical values - :floating, where no clear value is asserted Components assert the states of pins, and all the pins on a wire integrate to deterine the wire's state.")) (defmethod wires ((w wire)) (list w)) (defmethod width ((w wire)) 1) (defun logic-value-p (v) "Test whether V is a logic value. V can take a logic value (0 or 1) or some other value indicating a non-asserting (floating) state. Use `wire-floating-p' to check for floating wires." (or (equal v 0) (equal v 1))) (defun other-logic-value (v) "Return the other logic value to V. 0 and 1 exchange values; other (non-logical) values are left unchanged." (cond ((symbolp v) v) ((= v 0) 1) ((= v 1) 0) (t (error "Strange value ~a assigned to wire" v)))) (defmethod floating-p ((w wire)) (eql (state w) :floating)) (defun wire-known-pin-p (w p) "Test that P is a pin attached to W." (member p (pins w))) (defun wire-pins-asserting (w v) "Return the list of pins of W asserting V." (gethash v (wire-pin-assertions w))) (defun wire-components-with-pins-asserting (w v) "Return a list of all components of pins of W asserting V." ;; filter-out any nulls from pins without an associated component ;; (usually global pins like clocks) (remove-if #'null (mapcar #'component (wire-pins-asserting w v)))) (defun wire-pin-asserting-p (w p v) "Test whether P on W is asserting V. This checks for the inclusion of P in the `wire-pins-asserting' list for V." (member p (wire-pins-asserting w v))) (defun wire-any-pin-asserting-p (w v) "Test if there is any pin or W asserting V." (> (length (wire-pins-asserting w v)) 0)) (defun wire-remove-pin-asserting (w p v) "Remove P from the pins of W asserting V." (if-let ((asserting (wire-pins-asserting w v))) (setf (gethash v (slot-value w 'assertions-table)) (delete p asserting)))) (defun wire-add-pin-asserting (w p v) "Add P to the pins of W asserting V." (if-let ((asserting (wire-pins-asserting w v))) ;; value exists, add to the list (setf (gethash v (slot-value w 'assertions-table)) (cons p asserting)) ;; new value, create a new list (setf (gethash v (slot-value w 'assertions-table)) (list p)))) (defun wire-determine-state (w) "Determine the electrical state 0f W. The wire is in states 0 or 1 if only that logic value is being asserted by any pin, and :floating otherwise. Pins that are :reading, :trigger, or :tristate have no effect." (cond ((and (wire-any-pin-asserting-p w 0) (not (wire-any-pin-asserting-p w 1))) 0) ((and (wire-any-pin-asserting-p w 1) (not (wire-any-pin-asserting-p w 0))) 1) (t :floating))) (defun wire-update-state-and-trigger (w) "Update the state of W and notify any pins. The components of :reading pins are notified by calling `component-pin-changed' once per component. The components of :trigger pins are notifed by calling `component-pin-triggered' once per pin: if a single component happened to have two or ore :tigger pins attached to the same wire, it would get multiple notifications, one for each pin. (This situation is assumed to be unusual.)" (let* ((wire-ov (slot-value w 'state)) (wire-nv (wire-determine-state w))) (when (not (equal wire-ov wire-nv)) ;; store the new state (setf (slot-value w 'state) wire-nv) ;; propagate changes ;; TBC: should we also propagate floating values? (when (logic-value-p wire-nv) ;; for :reading pins, call their components' change notification (dolist (c (wire-components-with-pins-asserting w :reading)) (on-pin-changed c)) ;; for :trigger pins, call the pin's change notification (dolist (p (wire-pins-asserting w :trigger)) (on-pin-triggered (component p) p wire-nv)))))) (defun wire-add-pin (w p) "Add pin P to wire W." (let ((v (slot-value p 'state))) ;; check we don't already know this pin (when (wire-known-pin-p w p) (error "Pin ~s is already attached to wire ~s" p w)) ;; record the pin (setf (pins w) (cons p (pins w))) ;; place the pin into the correct bucket (wire-add-pin-asserting w p v) ;; set the wire's state based on this new pin (wire-update-state-and-trigger w))) (defmethod (setf wire-state) (nv (w wire) p ov) (when (not (equal ov nv)) ;; state is changing, remove pin from old bucket and place ;; into new bucket (wire-remove-pin-asserting w p ov) (wire-add-pin-asserting w p nv) ;; set the wire's state based on this new pin (wire-update-state-and-trigger w))) ;; ---------- Buses ---------- (defclass bus () ((width :documentation "The width of the bus." :initarg :width :initform 8 :reader width) (wires :documentation "The bus' wires, as a sequence." :reader wires)) (:documentation "A bus consisting of several wires.")) (defmethod initialize-instance :after ((b bus) &rest initargs) (declare (ignore initargs)) ;; create the wires (let* ((w (width b)) (wires (make-array (list w)))) (dolist (i (iota w)) (setf (elt wires i) (make-instance 'wire))) (setf (slot-value b 'wires) wires))) (defmethod floating-p ((b bus)) (some #'floating-p (wires b))) ;; ---------- Pins ---------- (defclass pin () ((component :documentation "The component the pin is attached to." :initform nil :initarg :component :accessor component) (wire :documentation "The wire the pin connects to." :initarg :wire :initform nil :accessor wire) (state :documentation "The state being asseted by the component onto the wire." :initform :tristate :initarg :state)) (:documentation "A pin connects a component to a wire. Pins can be in one of several states, including: - 1, asserting a logical 1 - 0, asserting a logical 0 - :reading, reading the state of the wire - :tristate, effectively disconnected from the wire - :trigger, like read but waiting for an edge The main difference between :reading and :trigger is how changes to the underlying wire state are notified to the attached components. For a :reading pin, a change causes a call to `component-pin-changed' on the pin's component. For :trigger pins, a change causes a call to `component-pin-triggered', which also specifies the pin that caused the notification.")) ;; TODO This should be a type assertion (defun ensure-pin-state (p state) "Ensure it makes sense to use STATE for P." (unless (member state '(0 1 :reading :tristate :trigger)) (error 'illegal-pin-state :pin p :state state))) (defmethod initialize-instance :after ((p pin) &rest initargs) (declare (ignore initargs)) ;; connect to the underlying wire if there is one (when (pin-wired-p p) (wire-add-pin (wire p) p))) (defmethod pins ((p pin)) (list p)) (defmethod wires ((p pin)) (list (wire p))) (defmethod (setf wire) (wire (p pin)) (setf (slot-value p 'wire) wire) (wire-add-pin wire p)) (defun pin-tristated-p (p) "Test if P is tristated." (equal (slot-value p 'state) :tristate)) (defun pin-wired-p (p) "Test whether P is attached to a wire or not." (not (null (wire p)))) (defun pin-reading-p (p) "Test if P is reading." (equal (slot-value p 'state) :reading)) (defun pin-asserted-p (p) "Test if P has a value asserted on it." (let ((v (slot-value p 'state))) (or (equal v 0) (equal v 1)))) (defmethod floating-p ((p pin)) (or (pin-tristated-p p) (and (pin-reading-p p) (floating-p (wire p))))) (defmethod state ((p pin)) (cond ((pin-asserted-p p) (slot-value p 'state)) ((pin-tristated-p p) (error 'reading-non-reading-pin :pin p)) ((floating-p p) (error 'reading-floating-value :pin p)) ((pin-reading-p p) (state (wire p))) ;; shouldn't get here, it's a weird state (t (error 'reading-non-reading-pin :pin p)))) (defmethod (setf state) (nv (p pin)) (let ((ov (slot-value p 'state))) ;; only update when the state changes (when (not (equal ov nv)) ;; make sure the pin state makes sense (ensure-pin-state p nv) (setf (slot-value p 'state) nv) (when (pin-wired-p p) (setf (wire-state (wire p) p ov) nv))))) ;; ---------- Connectors ---------- (defclass connector () ((width :documentation "The width of the connector." :initarg :width :reader width) (pins :documentation "The pins of the connector." :reader pins-sequence) (component :documentation "The component this connector's pins are connected to." :initarg :component :initform nil :reader component) (role :documentation "The role of the pins in this connector." :initarg :role :initform :io :reader role)) (:documentation "A sequence of pins. A connector connects a sequence of wires to a component.")) (defmethod initialize-instance :after ((conn connector) &rest initargs) (declare (ignore initargs)) ;; create the pins, without wires (let* ((c (component conn)) (w (width conn)) (role (role conn)) (pins (make-array (list w)))) (dolist (i (iota w)) (let ((pin (make-instance 'pin))) (configure-pin-for-role pin role) (setf (elt pins i) pin) (setf (component pin) c))) (setf (slot-value conn 'pins) pins))) (defmethod components ((c connector)) (list (component c))) (defun connector-pins-floating (conn) "Return a list of floating pins in CONN." (remove-if-not #'floating-p (coerce (pins conn) 'list))) (defmethod floating-p ((conn connector)) (> (length (connector-pins-floating conn)) 0)) (defmethod pins ((conn connector)) (coerce (pins-sequence conn) 'list)) (defun pin-states (conn) "Return a sequence of state values for the pins of CONN." (map 'vector #'state (pins conn))) (defmethod (setf pin-states) (nv (conn connector)) (map nil (lambda (p) (setf (state p) nv)) (pins conn))) (defun pins-value (conn) "Move the values of the pins on CONN into an integer. The first pin in the pins of CONN is moved to the least-significant bit of the value, and so on." (let* ((ps (pins conn)) (v 0) (n (1- (length ps)))) (dolist (i (iota (length ps))) (setf v (+ (ash v 1) (state (elt ps (- n i)))))) v)) (defmethod (setf pins-value) (v (conn connector)) (let ((ps (pins conn)) (nv v)) (dolist (i (iota (length ps))) (setf (state (elt ps i)) (logand nv 1)) (setf nv (ash nv -1)))))
13,165
Common Lisp
.lisp
356
33.58427
76
0.690456
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ead2b97827d50fda67e2257dbe36ab9ed3ef6eabde2d4c342c3a3d70a8207ed8
26,578
[ -1 ]
26,579
mop.lisp
simoninireland_cl-vhdsl/src/hw/mop.lisp
;; Metaclass for defining pin-oriented interfaces ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- The metaclass of components ---------- ;; Create a hidden base metaclass wose "slots" become options ;; available for slots in the final class (def-extra-options-metaclass premetacomponent () ((pins :type integer) (role :type symbol))) (defclass metacomponent (premetacomponent) ((pin-interface-slots :documentation "The slots forming the component's pin interface.") (subcomponent-slots :documentation "The slots containing sub-components.") (wiring :documentation "The wiring diagram." :initarg :wiring :initform nil :reader wiring-diagram)) (:documentation "The metaclass of components. The metaclass introduces two new slot arguments, `:pins' and `:role', to mark slots as part of the pin interface. These markers are then picked up when an object of the class is instanciated. `:pins' defines the number of pins in the slot. It should be one of: - an integer - a symbol identifying another slot on the same object that contains the width - T, to denote a slot with undetermined width If the width is set to the value of a nother slot, this value is treated as a constant and assigned to :pins for later queries. `:role' defines the intended use of the pins in the slot, and can'tbe any role supported by `configure-pin-for-role' If there are any `:initform' or :`initargs' for pin interface slots, they should contain the wire or wires that the slot's pins should be connected to. If wires are provided and the `:pins' value is set to T, the number of wires will be taken as the width of the slot. Classes with this metaclass can include an argument `:wiring' that specifies a wiring diagram for instances of the class. They will also support the `pin-interface' function that extracts the slots in their pin interface as defined by the slot options, and the `subcomponents-interface' function that extracts the slots that have types that aresub-types of `component'.")) ;; TODO There's more work to do here in deciding how slots can be ;; re-defined or combined. (defmethod compute-effective-slot-definition ((cl metacomponent) slot slot-defs) (let ((slot-def (call-next-method))) (when (and (slot-def-in-pin-interface-p slot-def) (not (slot-exists-and-bound-p slot-def 'role))) ;; fill in default :role if it is missing (setf (slot-value slot-def 'role) :io)) ;; return the slot definition slot-def)) (defmethod validate-superclass ((cl standard-class) (super metacomponent)) t) (defun find-pin-slot-def (cl slot &key fatal) "Return the slot definition for SLOT in CL. If FATAL is set to T an error is raised if SLOT does not exist or isn't part of the pin interface." (flet ((pin-slot-named (slot-def) (and (slot-def-in-pin-interface-p slot-def) (equal (slot-definition-name slot-def) slot)))) (if-let ((slot-defs (remove-if-not #'pin-slot-named (class-slots cl)))) (car slot-defs) ;; no pin slot of that name, either ignored or fatal (if fatal (error "No slot named ~a in pin interface of ~a" slot cl))))) (defun slot-def-in-pin-interface-p (slot-def) "Test whether SLOT-DEF defines a slot composed of pins. This tests for the existence of the :pins slot option in the slot definition." (slot-exists-and-bound-p slot-def 'pins)) (defun slot-def-in-subcomponents-p (slot-def) "Test whether SLOT-DEF defines a sub-component. Sub-components are simply slots that gave a type that is a sub-class of `component'." (subtypep (slot-definition-type slot-def) (find-class 'component))) (defgeneric pin-interface (c) (:documentation "Return the list of slots in the pin interface of C,") (:method ((cl metacomponent)) (slot-value cl 'pin-interface-slots))) (defgeneric subcomponent-interface (c) (:documentation "Return the list of slots of C holding sub-components.") (:method ((cl metacomponent)) (slot-value cl 'subcomponent-slots))) (defmethod finalize-inheritance :after ((class metacomponent)) (let* ((slot-defs (class-slots class)) (pin-slot-defs (remove-if-not #'slot-def-in-pin-interface-p slot-defs)) (subcomponent-slot-defs (remove-if-not #'slot-def-in-subcomponents-p slot-defs))) ;; populate the class' pin interface slots (setf (slot-value class 'pin-interface-slots) (mapcar #'slot-definition-name pin-slot-defs)) ;; populate the class' subcomponent slots (setf (slot-value class 'subcomponent-slots) (mapcar #'slot-definition-name subcomponent-slot-defs)))) ;; ---------- Enabler helper ---------- (defun call-methods (methods) "Return `call-method' forms for all METHODS." (mapcar #'(lambda (m) `(call-method ,m)) methods)) (define-method-combination guarded (&optional (order :most-specific-first)) ((arounds (:around)) (ifs (:if)) (befores (:before)) (primaries () :order order :required t) (afters (:after))) "A method combination that adds `:if' methods to guard a generic function. When present, `:if' methods are run first to test whether the other methods in the method stack are run. In other words they behave a little like `:around' methods, with the difference that `:if' methods always run first wherever they appear in the effective method stack. All `:if' methods must return non-nil for the \"functional\" parts of the method to be executed. Schematically the method ordering is: (if (and ifs) (arounds (befores) (primaries) (afters))) The order of execution for `:if' methods is undefined. However, they can have side-effects as long as these can happen in any order. One use case is for a guard to prevent a call to the target method but redirect the call to another, which is fine as long as there's no other guard that might inhibit it." (let* ((before-form (call-methods befores)) (after-form (call-methods afters)) (primary-form `(call-method ,(car primaries) ,(cdr primaries))) (core-form (if (or befores afters (cdr primaries)) `(prog1 (progn ,@before-form ,primary-form) ,@after-form) ;; optimisation for no :before or :after methods and ;; only one primary method `(call-method ,(car primaries)))) (around-form (if arounds `(call-method ,(car arounds) (,@(cdr arounds) (make-method ,core-form))) ;; optimisation for no :around methods core-form))) (if ifs `(if (and ,@(call-methods ifs)) ,around-form) ;; optimisation for no :if methods around-form)))
7,319
Common Lisp
.lisp
170
39.823529
83
0.728131
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6f6a8c1a0ea8bd4deaa09e3af8c329f16789767864c32defd1608807f7a22f5d
26,579
[ -1 ]
26,580
wiring.lisp
simoninireland_cl-vhdsl/src/hw/wiring.lisp
;; Wiring-up the pin interfaces of components ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Slot access ---------- (defun ensure-subcomponent (c slot) "Return the sub-component in SLOT of C. SLOT is checked to make sure it is a component." (let ((c1 (slot-value c slot))) (if (typep c1 'component) c1 (error 'non-component-type :type (class-of c1))))) (defun ensure-pin-slot (c slot) "Return the connector of SLOT on C. SLOT is checked to ensure it's in the pin interface of C." (if (pin-interface-p c slot) (slot-value c slot) (error 'non-pin-interface-slot :component c :slot slot))) (defun slot-connector (c s) "Return the connector for S on C. S should be a symbol or a two-element list identifying either a pin-slot of C or a pin-slot of a sub-component of C held in one of its slots." ;; extract the right slot, either directly or on the sub-component (when (consp s) (setq c (ensure-subcomponent c (car s))) (setq s (safe-cadr s))) ;; return the connector (ensure-pin-slot c s)) (defun ensure-compatible-widths (conn b) "Ensure connector CONN can be connected to bus B. At the moment this means their widths mst be equal: it might be acceptable to relax this as long as the us is \"wide enough\" for the connector" (if (not (equal (width conn) (width b))) (error 'incompatible-pin-widths :connector conn :bus b))) ;; ---------- Wiring state tests ---------- (defun ensure-fully-wired (&rest args) "Ensure that all elements of ARGS are fully wired. The elements of ARGS will typically be components, but can also be pins, connectors, or anything accepted by `fully-wired-p'. Components are only fully wired if their sub-compnents (if any) are. If the elements are not fully wired, a `not-fully-wired' error is signalled containing all the pins that fail the test." (flet ((all-components (c) "Include a component and its subcomponents." (if (typep c 'component) (cons c (components c)) c))) (let ((not-fully-wired (remove-if #'fully-wired-p (mapappend #'all-components args)))) (unless (null not-fully-wired) (let ((unwired-pins (remove-if #'pin-wired-p (mapappend #'pins not-fully-wired)))) (error 'not-fully-wired :elements not-fully-wired :pins unwired-pins)))))) ;; ---------- Wiring interface ---------- (defun connect-pins (conn b) "Connect the pins of connector CONN to the wires of bus B." ;; widths have to match (ensure-compatible-widths conn b) ;; wire-up the pins (let ((ps (pins conn)) (ws (wires b))) (dolist (i (iota (width conn))) (setf (wire (elt ps i)) (elt ws i))))) (defun connect-slots (c1 s1 c2 s2) "Connect slot S1 on component C1 to slot S2 on component C2." (let* ((conn1 (slot-connector c1 s1)) (conn2 (slot-connector c2 s2)) (w1 (width conn1)) (w2 (width conn2))) (let ((b (make-instance 'bus :width w1))) (connect-pins conn1 b) (connect-pins conn2 b))))
3,738
Common Lisp
.lisp
90
38.322222
90
0.696049
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
71626430379f834520e9c8286503937897ba49b8944a468b5da1de67536f2868
26,580
[ -1 ]
26,581
mixins.lisp
simoninireland_cl-vhdsl/src/hw/mixins.lisp
;; Mixins for common component features ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/hw) ;; ---------- Enable- and disable-able components ---------- (defclass enabled () ((enable :documentation "The component-enable pin." :initarg :enable :pins 1 :role :control) (enabled :documentation "Flag recording the component's enablement." :initform nil :accessor enabled)) (:metaclass metacomponent) (:documentation "A mixin for a component that can be enabled and disabled. Enable-able components only respond to changes in their pin interface when they are enabled. The states of their pins are left unchanged.")) (defmethod enabled-p ((c enabled)) (let ((en (elt (pins (slot-value c 'enable)) 0))) (and (pin-wired-p en) (not (floating-p en)) (equal (state en) 1)))) ;; Guards to prevent callbacks on disabled components (defmethod on-pin-changed :if ((c enabled)) (let ((en (enabled-p c)) (pre (enabled c))) ;; re-direct the callback if the enabled status has changed (cond ((and en (not pre)) ;; component has become enabled (on-enable c)) ((and (not en) pre) ;; component has become disabled (on-disable c))) (setf (enabled c) en) ;; return whether we're now enabled en)) (defmethod on-pin-triggered :if ((c enabled) p v) (enabled-p c)) ;; Callbacks for enablement and disablement ;; TODO Should we tristate :io and :reading pins, or indeed all pins except ;; enable, when the component is disabled? Or leave that to sub-classes? (defgeneric on-enable (c) (:documentation "Callback called when a component is enabled.") ;; default callback is empty (:method ((c enabled)))) ;; TODO Should we have an :after method here that re-calls `on-pin-changed' ;; so that the pins are updated to reflect the component's state? (defgeneric on-disable (c) (:documentation "Callback called when a component is disabled.") ;; defalt callback is empty (:method ((c enabled)))) ;; ---------- Clocked components ---------- (defclass clocked () ((clock :documentation "The component's clock pin." :initarg :clock :pins 1 :role :trigger :reader clock)) (:metaclass metacomponent) (:documentation "A mixin for a component that has a clock line. Clocked components do most of their active work when the clock transitions, although they can change state at other times too.")) ;; ---------- Read/write components ---------- (defclass readwrite () ((write-enable :documentation "The component's write-enable pin." :initarg :write-enable :pins 1 :role :control :reader write-enable)) (:metaclass metacomponent) (:documentation "A mixin for a component that has a write-enable line.. This provides a common control line for determining whether a component reads data from a bus (when write-enable is high) or makes data available on the bus. 'Write' should be seen from the perspective of ourside the component. This only works for components with a single decision on read or write. More complicated components might need several such control lines.")) (defmethod write-enabled-p ((c readwrite)) (equal (state (elt (pins (slot-value c 'write-enable)) 0)) 1)) (defmethod read-enabled-p ((c readwrite)) (not (write-enabled-p c)))
4,029
Common Lisp
.lisp
100
37.36
76
0.720924
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
775291dd74c33db1048a9b4e637d91e35324e6d93042d79e08e45bb9319eb2be
26,581
[ -1 ]
26,582
syntax.lisp
simoninireland_cl-vhdsl/src/rtl/syntax.lisp
;; Tester functions for RTLisp ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/rtl) ;; Throughout this file "form" means "abstract syntax tree as returned by ;; ast:parse from parsing a Lisp s-expression". ;; ---------- Operators ---------- (defvar *arithmetic-operators* '(+ - * / mod ash) "Arithmetic operators.") (defvar *bitwise-operators* '(logand logior lognot logxor) "Bitwise arithmetic operators.") (defvar *logical-operators* '(not = /=) "Logical operators.") ;; ...plus and and or, which are implemented as macros expanding to ;; let or if forms (defun operator-p (form) "Test that FORM is a valid operator form." (and (typep form 'ast::function-application) (let ((op (slot-value (slot-value form 'ast::operator) 'ast::symbol))) (or (member op *arithmetic-operators*) (member op *bitwise-operators*) (member op *logical-operators*))))) ;; ---------- Constants ---------- (defun constant-p (form) "Test whether FORM evaluates to a constant that can be compiled away." (typep form 'ast::constant-form)) ;; ---------- Assignments and local variables ---------- (defun let-p (form) "Test that FORM is a valid let block." (and (or (typep form 'ast::let-form) (typep form 'ast::let*-form)) (let ((body (slot-value form 'ast::iprogn-forms))) (every #'expression-p body)))) ;; ---------- Conditionals ---------- (defun if-p (form) "Test that FORM is a conditional." (or (typep form 'ast::if-form) (typep form 'ast::cond-form))) ;; ---------- Assignments ---------- (defun setf-p (form) "Test that FORM is a setf." (typep form 'ast::setf-form)) ;; ---------- Expressions ---------- (defun expression-p (form) "Test that FORM is a valid expression form." (funcall (any-of-p constant-p let-p operator-p if-p setf-p) form)) ;; ---------- Fragments ---------- (defun fragment-p (form) "Test that FORM is a valid RTLisp fragment." ;; only expressions at the moment (funcall (any-of-p expression-p) form)) (defun closed-fragment-p (form vars) "Test that FORM is a fragment with any free variables mentioned in VARS. VARS being empty implies that FORM is a closed-form fragment." (subsetp (ast:free-variables form) vars))
2,966
Common Lisp
.lisp
71
39.126761
77
0.684137
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2e827ab1b3a0b4b73d5673d937ced45147f3f1f418d7e4d509c5840fa90eab77
26,582
[ -1 ]
26,583
package.lisp
simoninireland_cl-vhdsl/src/rtl/package.lisp
;; Package for RTLisp, a synthesisable fragment of Lisp ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :common-lisp-user) (defpackage cl-vhdsl/rtl (:use :cl :alexandria :serapeum :cl-vhdsl) (:local-nicknames (:def :cl-vhdsl/def) (:ast :clast)) (:export ;; validation #:validate ;; conditions #:not-synthesisable #:unknown-variable ))
1,090
Common Lisp
.lisp
30
34.2
75
0.735795
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
effd97e6553cd8afd02dba691b9a0da669dbb57be28f4af24be7540a7007480c
26,583
[ -1 ]
26,584
parser.lisp
simoninireland_cl-vhdsl/src/rtl/parser.lisp
;; Tree traversal and parsing for RTLisp ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/rtl) (defun validate (form &optional vars) "Validate that FORM is a valid fragment in an environment containing VARS. FORM must be a valid synthesisable Lisp fragment. Any variables appearing free in FORM must be mentioned in VARS. If VARS ar omitted then FORM must be a closed form. Failure to validate signals either `not-synthesisable' or `unknown-variable' as appropriate." (let ((f (ast:parse form))) ;; syntax (unless (fragment-p f) (error 'not-synthesisable :fragment f)) ;; closure (unless (closed-fragment-p f vars) (let ((vars (set-difference (ast:free-variables f) vars))) (error 'unknown-variable :variables vars)))))
1,490
Common Lisp
.lisp
34
41.647059
76
0.748792
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e8ec0fdce0713d6f376d5b0ae7cf474dab70b7c8b15f98c9d5784e65cc85e6a3
26,584
[ -1 ]
26,585
conditions.lisp
simoninireland_cl-vhdsl/src/rtl/conditions.lisp
;; Conditions for synthesis ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/rtl) ;; ---------- Synthesis ---------- (define-condition not-synthesisable () ((fragment :documentation "The code that could not be synthesised." :initarg :fragment :reader fragment)) (:report (lambda (c str) (format str "Could not synthesise code:~%~a" (fragment c)))) (:documentation "Condition signalled when code can't be synthesised. This usually indicates that the Lisp fragment provided is un-parsable because it contains non-synthesisable syntax, or because of a problem with the synthesiser's code generator.")) (define-condition unknown-variable () ((var :documentation "The variable(s)." :initarg :variable :initarg :variables :reader variables)) (:report (lambda (c str) (format str "Unknown variable(s) ~a" (variables c)))) (:documentation "Condition signalled when one or more undeclared variables are encountered. This is caused either by an undeclared variable or by use of a variable that should be declared in the architectural environment, such as a register."))
1,864
Common Lisp
.lisp
44
39.681818
93
0.739514
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
38049f475b78027a0d3f123f0c00abcd510b877c8574958c9b87cf35bc1b2a59
26,585
[ -1 ]
26,586
package.lisp
simoninireland_cl-vhdsl/systems/6502/package.lisp
;; Package definition for the 6502 emulator ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :common-lisp-user) (defpackage cl-vhdsl/6502 (:use :cl :cl-ppcre :cl-interpol :cl-bitfields :alexandria :cl-vhdsl/def) (:local-nicknames (:emu :cl-vhdsl/emu)) (:export ;; addressing modes ;; (all but the classes can be hidden eventually) #:immediate #:immediate-value #:absolute #:absolute-address #:absolute-indexed #:absolute-indexed-index ;; instructions (both classes and functions) #:LDA #:LDX #:LDY #:STA #:DEX #:BNZ #:BRK ;; assembler #:*assembler-instructions* #:*assembler-addressing-modes* #:assembler-parse-number #:assembler-parse-instruction #:assembler-parse-line #:assembler-parse-sexp ;; macro interface ))
1,523
Common Lisp
.lisp
48
28.916667
75
0.723622
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
dc6a6e23ca6db5eb7130844eced5cadb883245ce97be275979e18541f5332795
26,586
[ -1 ]
26,587
addressing.lisp
simoninireland_cl-vhdsl/systems/6502/addressing.lisp
;; 6502 addressing modes ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502) ;; ---------- Helper functions ---------- ;; The 6502 assemblers typically allow decimal,hex, octal, and binary ;; numbers, selected by suffix. I've seen a couple that allow explicit ;; negative number literals too. (defvar *assembler-digits* "0123456789ABCDEF" "Digits for bases up to 16.") (defun assembler-parse-digit (c radix) "Parse C as a digit in base RADIX." (let ((d (position c *assembler-digits*))) (if (or (null d) (>= d radix)) (error "Not a digit in base ~a: ~a" radix c) d))) (defun assembler-parse-number (s) "Parse S as a number. The suffixes H, O, and B can be used to indicate hex, octal, and binary as needed. Decimal is assumed as the default." (let* ((len (length s)) (first (elt s 0)) (last (elt s (1- len))) (radix 10) (i 0) (m 1) (n 0)) ;; check for negative numbers (switch (first :test #'char=) (#\- (setq i 1) (setq m (- 1))) (#\+ (setq i 1))) ;; test for trailing radix (switch (last :test #'char=) (#\H (setq radix 16) (setq len (1- len))) (#\O (setq radix 8) (setq len (1- len))) (#\B (setq radix 2) (setq len (1- len)))) ;; parse digits against the radix (dolist (j (iota (- len i) :start i)) (setq n (+ (* n radix) (assembler-parse-digit (elt s j) radix)))) (* n m))) ;; ---------- Immediate ---------- (defclass immediate (addressing-mode) ((value :documentation "The value, as an unsigned 8-bit byte." :type word-8 :initarg :value :reader immediate-value)) (:documentation "Immediate addressing, with an inline 8-bit value.")) (defun immediate (&rest args) (apply #'make-instance (cons 'immediate args))) (defmethod addressing-mode-data ((mode immediate) arch) (immediate-value mode)) (defmethod addressing-mode-regexp ((cls (eql 'immediate))) "#((?:[0-9]+)|(?:[0-9a-fA-F]+H))") (defmethod addressing-mode-parse ((mode immediate) ss) (setf (slot-value mode 'value) (assembler-parse-number (car ss)))) (defmethod addressing-mode-argument ((cls (eql 'immediate)) s) (assembler-parse-number s)) (defmethod addressing-mode-bytes ((mode immediate)) (list (immediate-value mode))) (defmethod addressing-mode-behaviour ((mode immediate) c) (immediate-value mode)) ;; ---------- Absolute ---------- (defclass absolute (addressing-mode) ((address :documentation "The address, a 16-bit word." :type word-16 :initarg :address :reader absolute-address)) (:documentation "Absolute addressing, with an inline 16-bit address.")) (defun absolute (&rest args) (apply #'make-instance (cons 'absolute args))) (defmethod addressing-mode-regexp ((cls (eql 'absolute))) "((?:[0-9]+)|(?:[0-9a-fA-F]+H))") (defmethod addressing-mode-parse ((mode absolute) ss) (setf (slot-value mode 'address) (assembler-parse-number (car ss)))) (defun little-endian-word-16 (w) "Return a list of bytes in the 16-bit word, little-endian." (let ((l (logand w #16rFF)) (h (logand (ash w -8) #16rFF ))) (list l h))) (defmethod addressing-mode-bytes ((mode absolute)) (little-endian-word-16 (absolute-address mode))) (defmethod addressing-mode-behaviour ((mode absolute) c) (absolute-address mode)) ;; ---------- Zero-page ---------- (defclass zero-page (addressing-mode) ((address :documentation "The offset into page zero, an 8-bit word." :type word-8 :initarg :address :reader zero-page-address)) (:documentation "Absolute addressing, with an inline 8-bit page zero address.")) (defun zero-page (&rest args) (apply #'make-instance (cons 'zero-page args))) (defmethod addressing-mode-regexp ((cls (eql 'zero-page))) "((?:[0-9]+)|(?:[0-9a-fA-F]+H))") (defmethod addressing-mode-parse ((mode zero-page) ss) (setf (slot-value mode 'address) (assembler-parse-number (car ss)))) (defmethod addressing-mode-bytes ((mode zero-page)) (little-endian-word-16 (zero-page-address mode))) (defmethod addressing-mode-behaviour ((mode zero-page) c) (zero-page-address mode) c) ;; ---------- Absolute indexed ---------- (defclass absolute-indexed (absolute) ((index :documentation "The index register to add to the address." :type index-register :initarg :indexed-by :reader absolute-indexed-index)) (:documentation "An absolute address plus the contents of an index register. The address is an absolute address wihtin the entire address space of the processor.")) (defun absolute-indexed (&rest args) (apply #'make-instance (cons 'absolute-indexed args))) (defmethod addressing-mode-regexp ((cls (eql 'absolute-indexed))) "((?:[0-9]+)|(?:[0-9a-fA-F]+H)),\\s*([XY])") (defmethod addressing-mode-parse ((mode absolute-indexed) ss) (setf (slot-value mode 'address) (assembler-parse-number (car ss))) (setf (slot-value mode 'index) (cadr ss))) (defmethod addressing-mode-bytes ((mode absolute-indexed)) (little-endian-word-16 (absolute-address mode))) (defmethod addressing-mode-behaviour ((mode absolute-indexed) c) (+ (absolute-address mode) (emu:core-register-value (absolute-indexed-index mode) c))) ;; ---------- Relative ---------- (defclass relative (addressing-mode) ((offset :documentation "The offset from the program counter.." :type index-register :initarg :offset :reader relative-offset)) (:documentation "Relative addressing, with an inline 8-bit offset. The offset is relative to the current program counter, and may be positive or negative.")) (defun relative (&rest args) (apply #'make-instance (cons 'relative args))) (defmethod addressing-mode-regexp ((cls (eql 'relative))) "((?:[0-9]+)|(?:[0-9a-fA-F]+H))") (defmethod addressing-mode-parse ((mode relative) ss) (setf (slot-value mode 'offset) (assembler-parse-number (car ss)))) (defmethod addressing-mode-bytes ((mode relative)) (little-endian-word-8 (relative-offset mode))) (defmethod addressing-mode-behaviour ((mode relative) c) (relative-offset mode)) ;; ---------- Indexed indirect ---------- (defclass indexed-indirect (zero-page) ((index :documentation "The index register to add to the address." :type index-register :initarg :indexed-by :reader indexed-indirect-index)) (:documentation "An offset into page zero plus the contents of an index register. The offset is used to generate an address in page zero, to which the contents of the index register are added.")) (defmethod addressing-mode-bytes ((mode indexed-indirect)) (little-endian-word-16 (indexed-indirect-index mode))) ;; ---------- Indirect indexed ---------- (defclass indirect-indexed (zero-page) ((index :documentation "The index register to add to the address." :type index-register :initarg :indexed-by :reader indirect-indexed-index)) (:documentation "An offset into page zero plus the contents of an index register. The offset is used to generate an offset into page zero which is retrieved as an absolute address, and then the contents of the index register are added to it.")) (defmethod addressing-mode-bytes ((mode indirect-indexed)) (little-endian-word-16 (indirect-indexed-index mode))) ;; ---------- Addressing mode encoding/decoding ---------- ;; 6502 instructions encode their addressing mode using a small ;; bit pattern within the opcode. (defgeneric addressing-mode-encode (mode) (:documentation "Return the code used for MODE in opcodes.")) (defmethod addressing-mode-encode ((mode absolute)) #2r011) (defmethod addressing-mode-encode ((mode immediate)) #2r010) (defmethod addressing-mode-encode ((mode absolute-indexed)) (if (equal (absolute-indexed-index mode) 'X) #2r111 #2r110)) ;; ---------- Assembler ---------- (defun parse-instruction-arguments (args) "Convert ARGS into an addressing mode object." (cond ((atom args) (make-instance 'immediate :value args)) ((equal (length args) 1) (make-instance 'absolute) :address (car args)) ((equal (length args) 2) (make-instance 'absolute-indexed :address (car args) :index (cadr args))) (t (signal 'unrecognised-addressing-mode :args args))))
8,939
Common Lisp
.lisp
219
37.543379
83
0.69335
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3842bd97b84ea02773dd313c8b8f6758e85aed31050cc69355ca31f1217df2ef
26,587
[ -1 ]
26,588
instructions.lisp
simoninireland_cl-vhdsl/systems/6502/instructions.lisp
;; 6502 instructions ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502) ;; ---------- Loads ---------- (defclass LDA (instruction) () (:documentation "LoaD Accumulator.")) (defun LDA (&rest args) (let ((ins (apply #'make-instance (cons 'LDA args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((cls (eql 'LDA))) "LDA") (defmethod instruction-addressing-modes ((cls (eql 'LDA))) '(immediate absolute absolute-indexed)) (defmethod instruction-opcode ((ins LDA)) (let* ((mode (instruction-addressing-mode ins)) (b (addressing-mode-encode mode)) opcode) (setf-bitfields opcode (1 0 1 b b b 0 1)) opcode)) (defmethod instruction-behaviour ((ins LDA) c) (setf (emu:core-register-value 'A c) (instruction-argument ins c)) (setf (emu:core-flag-value 'Z c) (= (emu:core-register-value 'A c) 0))) (defclass LDX (instruction) () (:documentation "LoaD index register X.")) (defun LDX (&rest args) (let ((ins (apply #'make-instance (cons 'LDX args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((ins (eql 'LDX))) "LDX") (defmethod instruction-addressing-modes ((ins (eql 'LDX))) '(immediate absolute)) (defmethod instruction-opcode ((ins LDX)) (let* ((mode (instruction-addressing-mode ins)) (b (addressing-mode-encode mode)) opcode) (setf-bitfields opcode (1 0 1 b b b 1 0)) opcode)) (defmethod instruction-behaviour ((ins LDX) c) (setf (emu:core-register-value 'X c) (instruction-argument ins c)) (setf (emu:core-flag-value 'Z c) (= (emu:core-register-value 'X c) 0))) (defclass LDY (instruction) () (:documentation "LoaD index register X.")) (defun LDY (&rest args) (let ((ins (apply #'make-instance (cons 'LDY args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((ins (eql 'LDY))) "LDY") (defmethod instruction-addressing-modes ((ins (eql 'LDY))) '(immediate absolute)) (defmethod instruction-opcode ((ins LDY)) (let* ((mode (instruction-addressing-mode ins)) (b (addressing-mode-encode mode)) opcode) (setf-bitfields opcode (1 0 1 b b b 0 0)) opcode)) (defmethod instruction-behaviour ((ins LDY) c) (setf (emu:core-register-value 'Y c) (instruction-argument ins c)) (setf (emu:core-flag-value 'Z c) (= (emu:core-register-value 'Y c) 0))) ;; ---------- Saves ---------- (defclass STA (instruction) () (:documentation "STore Accumulator.")) (defun STA (&rest args) (let ((ins (apply #'make-instance (cons 'STA args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((ins (eql 'STA))) "STA") (defmethod instruction-addressing-modes ((ins (eql 'STA))) '(immediate absolute absolute-indexed)) (defmethod instruction-opcode ((ins STA)) (let* ((mode (instruction-addressing-mode ins)) (b (addressing-mode-encode mode)) opcode) (setf-bitfields opcode (1 0 0 b b b 0 1)) opcode)) (defmethod instruction-behaviour ((ins STA) c) (setf (emu:core-memory-location (instruction-argument ins c) c) (emu:core-register-value 'A c))) ;; ---------- Increment and decrement---------- (defclass DEX (instruction) () (:documentation "DEcrement index register X.")) (defun DEX (&rest args) (let ((ins (apply #'make-instance (cons 'DEX args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((ins (eql 'DEX))) "DEX") (defmethod instruction-addressing-modes ((ins (eql 'DEX))) '(implicit)) (defmethod instruction-opcode ((ins DEX)) #2r11001010) (defmethod instruction-behaviour ((ins DEX) c) (decf (emu:core-register-value 'X c)) (setf (emu:core-flag-value 'Z c) (= (emu:core-register-value 'X c) 0))) ;; ---------- Branches ---------- (defclass BNZ (instruction) () (:documentation "Branch if Not Zero")) (defun BNZ (&rest args) (let ((ins (apply #'make-instance (cons 'BNZ args)))) (instruction-check ins) ins)) (defmethod instruction-mnemonic ((ins (eql 'BNZ))) "BNZ") (defmethod instruction-addressing-modes ((ins (eql 'BNZ))) '(relative)) (defmethod instruction-behaviour ((ins BNZ) c) (if (= (emu:core-flag-value 'Z c) 0) (setf (emu:core-register-value 'PC c) (+ (emu:core-register-value 'PC c) (instruction-argument ins c))))) ;; ---------- Miscellaneous ---------- ;; At the moment this isn't the actual BRK instruction, which ;; jumps to an interrupt vector: this version stops execution. (defclass BRK (instruction) () (:documentation "BReaK execution.")) (defmethod instruction-mnemonic ((ins (eql 'BRK))) "BRK") (defmethod instruction-addressing-modes ((ins (eql 'BRK))) '(implicit)) (defmethod instruction-opcode ((ins BRK)) 0) (defmethod instruction-behaviour ((ins BRK) c) (emu:core-end-program c))
5,439
Common Lisp
.lisp
140
36.171429
98
0.690657
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ef86814d1420f5e3f401e33ab1c890a918df6aca3a6a2f2ca5dc5bd33e2b3fdd
26,588
[ -1 ]
26,589
assembler.lisp
simoninireland_cl-vhdsl/systems/6502/assembler.lisp
;; 6502 assembler ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502) (named-readtables:in-readtable :interpol-syntax) ;; ---------- The regular expressions ---------- (defparameter *assembler-comment* ";(\\s+.*)?" "A regular expression matching a comment. Comments consist of a semi-colon and then the rest of the line.") (defparameter *assembler-label* "([A-Za-z0-9_$-])+:?" "A regular expression matching a label. A label is a simple string.") (defparameter *assembler-directive* "\\.[A-Z]+" "A reglar expression matching an assembler directive. Directives start with a dot.") (defparameter *assembler-opcode* "([A-Z]{3})" "A regular expression to match opcodes. An opcode consists of three upper-case letters. This is only true for the 6502, not for other processors.") (defparameter *assembler-immediate* "#([0-9]+)" "Regular expression to match immediate values. The 6502 convention is for immediate values to consist of a hash followed by a number.") ;; ---------- Assembler state ---------- (defvar *assembler-instructions* nil "The list of instruction classes used by the assembler.") (defvar *assembler-directives* nil "The list of directives used by the assembler.") (defvar *assembler-symbol-table* (make-hash-table) "An hash table of symbols. A symbol is mapped to one of: - A pair (:integer . val) representing an integer constant - A pair (:offset . off) representing a relative offset from PC - A pair (:address . addr) representing an absolute address ") (defvar *assembler-pc* 0 "The assembler's program counter.") ;; ---------- Pseudo-functions and directives ---------- (defclass directive (abstract-instruction) () (:documentation "Assembler directives.")) (defgeneric assembler-directive-action (dir) (:documentation "The effect of DIR on the assembler's state.")) (defclass equ (directive) ((value :documentation "The value." :type integer :initarg :value :reader assembler-equ-value)) (:documentation "A .EQU directive that defines a value.")) (defmethod instruction-mnemonic ((dir (eql 'equ))) ".EQU") ;; ---------- Parsing functions ---------- (defun assembler-uncomment (s) "Remove any comments from S. This also removes trailing whitespace." (regex-replace "\\s+$" (regex-replace *assembler-comment* s "") "")) (defun assembler-parse-instruction (fields) "Parse FIELDS as an instruction line." (if-let ((inscls (assembler-get-mnemonic (car fields) *assembler-instructions*))) (let ((modes (instruction-addressing-modes inscls))) (if-let ((addrcls (assembler-get-addressing-mode (cadr fields) modes))) ;; we have an addressing mode, construct the instruction (let* ((modecls (car addrcls)) (mode (if modecls (make-instance modecls :parse (cadr addrcls)) nil)) (ins (make-instance inscls :addressing-mode mode))) ins) ;; no addressing mode, fail (error "Instruction ~a needs an argument" (instruction-mnemonic inscls)))))) (defun assembler-parse-line (s) "Assemble the line of machine code in S. This returns an assembled instruction or nil, and may change the state of the assembler." (let* ((uncommented (assembler-uncomment s)) (fields (split "\\s+" uncommented))) (if (> (length fields) 0) (if (string= (car fields) "") ;; no label, decode instruction (assembler-parse-instruction (cdr fields)) ;; a labelled entry, define the label and then parse the rest (let ((label (car fields))) (assembler-parse-labelled-instruction fields)))))) ;; ---------- Assembler s-expression format ---------- (defun assembler-parse-sexp (x) "Parse X as an s-expression defining an assembler (pseudo-)instruction." (let ((opcode (car x))) ;; look-up the instruction (if-let ((inscls (assembler-get-mnemonic x *assembler-instructions*))) ;; we have an instruction (let ((mi (cons inscls (cdr x)))) (apply #'make-instance mi)) ;; not a recognised instruction (error (make-instance 'unrecognised-mnemonic :mnemonic opcode)))))
4,805
Common Lisp
.lisp
116
38.37931
84
0.71253
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c8cfde362c57772da6550bacb9eaeb6b6c8a9b7f2bff734ca3b442cabad71fb7
26,589
[ -1 ]
26,590
emu.lisp
simoninireland_cl-vhdsl/systems/6502/emu.lisp
;; 6502 emulation in software ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502)
816
Common Lisp
.lisp
19
41.894737
75
0.757538
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0f767129ed447566bb77203519cc4dd485cfb5bcb3d853c4a3bdfd9c1e467839
26,590
[ -1 ]
26,591
arch.lisp
simoninireland_cl-vhdsl/systems/6502/arch.lisp
;; 6502 architecture definition ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502) (defparameter *6502-system* (make-instance 'architecture) "6502 system.") (defparameter *MOS6502* (make-instance 'core) "6502 core.") (dolist (r (list (make-instance 'data-register :name 'A :width 8 :documentation "The accumulator.") (make-instance 'index-register :name 'X :width 8 :documentation "Index register X.") (make-instance 'index-register :name 'Y :width 8 :documentation "Index register Y.") (make-instance 'program-counter :name 'PC :width 16 :documentation "Program counter.") (make-instance 'index-register :name 'SP :width 8 :documentation "Stack pointer (offset).") (make-instance 'special-register :name 'P :width 8 :documentation "Flags register."))) (setf (gethash (register-name r) (core-registers *MOS6502*)) r)) (dolist (f (list (make-instance 'flag :name 'C :register 'P :bit 0 :documentation "Carry flag.") (make-instance 'flag :name 'Z :register 'P :bit 1 :documentation "Zero flag."))) (setf (gethash (flag-name f) (core-flags *MOS6502*)) f)) (setf (architecture-components *6502-system*) (list :core *MOS6502* :memory (make-instance 'memory :size (* 8 KB)) :address-bus (make-instance 'bus :connections '(:core :memory)) :data-bus (make-instance 'bus :connections '(:core :memory))))
2,199
Common Lisp
.lisp
49
40.408163
75
0.690187
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
5505011e9b4563534af769e4d4e32d9dd3263d2b536f9bbf3e984f8781653e7a
26,591
[ -1 ]
26,592
package.lisp
simoninireland_cl-vhdsl/systems/6502/test/package.lisp
;; Test package for the 6502 emulator ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (defpackage cl-vhdsl/6502/test (:use :cl :cl-ppcre :cl-vhdsl :cl-vhdsl/6502) (:import-from :fiveam #:is #:test #:def-suite)) (in-package :cl-vhdsl/6502/test) (def-suite cl-vhdsl/6502)
987
Common Lisp
.lisp
24
39.791667
75
0.746875
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
21f4e527f821541569dc61173b0b766d4d2ba941ed13c9e43ba6181b075765d2
26,592
[ -1 ]
26,593
test-emu.lisp
simoninireland_cl-vhdsl/systems/6502/test/test-emu.lisp
;; Tests of 6502 software emulation ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/6502) (let* ((mem (make-instance 'emu:cached-memory :size (* 8 KB))) (core (emu:make-core *MOS6502*))) (emu:memory-initialise mem) (let ((p (list (make-instance 'LDA :addressing-mode (immediate :value 25)) (make-instance 'STA :addressing-mode (absolute :address #16r200)) (make-instance 'BRK :addressing-mode (implicit))))) (emu:load-program p mem) (emu:run-program core mem) (emu:memory-location mem #16r200) ) ) (defun create-instruction (mnemonic mode mem pc) "doc" (let ((ins (funcall #'make-instance mnemonic :addressing-mode mode))) (load-instruction ins mem pc))) (defmacro defprogram (var (mem &key (initial #16r300)) &body body) "Assemble a program to a list of instructions." `(macrolet ((LDA (mode) `(setq pc (create-instruction 'LDA ,mode mem pc))) (STA (mode) `(setq pc (create-instruction 'STA ,mode mem pc))) (DEX (mode) `(setq pc (create-instruction 'DEX ,mode mem pc))) (INX (mode) `(setq pc (create-instruction 'INX ,mode mem pc))) (TAX (mode) `(setq pc (create-instruction 'TAX ,mode mem pc))) (BEQ (mode) `(setq pc (create-instruction 'BEQ ,mode mem pc))) (BNZ (mode) `(setq pc (create-instruction 'BNZ ,mode mem pc))) (BRK (mode) `(setq pc (create-instruction 'BRK ,mode mem pc))) (immediate (&rest args) `(apply #'make-instance (list 'immediate ,@args))) (absolute (&rest args) `(apply #'make-instance (list 'absolute ,@args))) (absolute-indexed (&rest args) `(apply #'make-instance (list 'absolute-indexed ,@args))) (relative (&rest args) `(apply #'make-instance (list 'relative ,@args))) (.LABEL (label) `(setf (gethash ',label symbols) pc)) (.TO-LABEL (label) `(if-let ((addr (gethash ',label symbols))) (- addr pc) (print "Forward reference")))) (let ((mem ,mem) (pc ,initial) (symbols (make-hash-table))) ,@body mem))) (let ((mem (make-instance 'cached-memory :size (* 8 KB)))) (memory-initialise mem) (defprogram test (mem) (LDA (immediate :value 100)))) (defprogram copy-block ((make-instance 'cached-memory :size (* 8 KB)) :initial #16r400) (let ((SOURCE #16r200) (DEST #16r300) (LEN #16r2ff)) (.LABEL START) (LDA (absolute :address LEN)) (BEQ (relative :offset (.TO-LABEL END))) ;;(TAX) ;;(INX) (.LABEL COPY) (LDA (absolute-indexed :address SOURCE :index 'X)) (STA (absolute-indexed :address DEST :index 'X)) ;;(DEX) (BNZ (relative :offset (.TO-LABEL COPY))) (.LABEL END) ;;(BRK) ) )
3,413
Common Lisp
.lisp
93
32.666667
87
0.658699
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f4315e98f76e7ca582efdec15a79c8a208ba7b9001b31a535f1bfeb4bfbcb587
26,593
[ -1 ]
26,594
test-assembler.lisp
simoninireland_cl-vhdsl/systems/6502/test/test-assembler.lisp
;; Test the 6502 assemler ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/systems/6502/test) (in-suite cl-vhdsl/systems/6502) (test test-labels "Test we can recognise labels." (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL16")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "16LABEL")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL_16")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL-16")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "-LABEL")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "_LABEL")) (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL$")) ;; accept trailing colons (is (scan cl-vhdsl/systems/6502::*assembler-label* "LABEL:"))) (test test-opcodes "Test we can recognise assembler opcodes." (is (scan cl-vhdsl/systems/6502::*assembler-opcode* "LDA")) (is (null (scan cl-vhdsl/systems/6502::*assembler-opcode* "LD")))) (test test-uncomment "Test we can remove comments." (dolist (s '(("; one line" "") (" ; one line" "") (" ; one line " "") (" LDA #12 ; one line" " LDA #12") (" LDA #12 ; one line " " LDA #12"))) (is (equal (cl-vhdsl/systems/6502::assembler-uncomment (car s)) (cadr s)))))
2,048
Common Lisp
.lisp
44
43.818182
80
0.690381
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3649ee3dbe55c024564f34c6e6e803847f7b40d8cae61d62c170c380e2c2e414
26,594
[ -1 ]
26,595
package.lisp
simoninireland_cl-vhdsl/systems/sap-1/package.lisp
;; Package definition for the SAP-1 emulator ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :common-lisp-user) (defpackage cl-vhdsl/SAP-1 (:use :cl :cl-ppcre :cl-interpol :cl-bitfields :alexandria :cl-vhdsl/def) (:local-nicknames (:emu :cl-vhdsl/emu)) (:export ;; reference implkementation #:run-reference ;; core and architecture #:*SAP-1-architecture* #:*SAP-1-core* ;; instruction set an addressing modes #:absolute #:LDA #:ADD #:SUB #:OUT #:HLT))
1,220
Common Lisp
.lisp
35
32.514286
75
0.727119
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
23bad738135387abd6d53c74f90e55a04694438beaf624d6cd2c1b3e735ff0cd
26,595
[ -1 ]
26,596
explicit.lisp
simoninireland_cl-vhdsl/systems/sap-1/explicit.lisp
;; A minimal, explicitly-coded reference SAP-1 ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/SAP-1) (defun run-reference (mem) "Run a SAP-1 program from MEM. This is a hand-cded reference implementation ofthe SAP-1 processor, It takes a memory space of 16 bytes in MEM, starting execution from address 0, and returns the contents of the OUT register." (block RUN (let ((PC 0) (A 0) (OUT 0)) (labels ((lda (addr) (setf A (aref mem addr))) (add (addr) (setf A (+ A (aref mem addr)))) (sub (addr) (setf A (- A (aref mem addr)))) (out () (setf OUT A)) (hlt () (return-from RUN OUT)) (execute () "Run the machine's execution loop." (let* ((IR (aref mem PC)) (INS (ash IR -4)) (W (logand IR #2r1111))) ;; increment the program counter (incf PC) ;;decode the instruction (eswitch (INS) (#2r0000 (lda W)) (#2r0001 (add W)) (#2r0010 (sub W)) (#2r1110 (out)) (#2r1111 (hlt))) ;; continue execution (execute)))) ;; run the machine (execute)))))
1,836
Common Lisp
.lisp
56
28.767857
75
0.660623
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
223131daf9f7792d89ca0d4c1abe418d7959c0b82a4164ce8b1a8c432e7189d7
26,596
[ -1 ]
26,597
sap-1.lisp
simoninireland_cl-vhdsl/systems/sap-1/sap-1.lisp
;; SAP-1 architecture ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. ;; The SAP-1 ("Simple as Possible - 1") processor is described in: ;; ;; Albert Paul Malvino and Jerald Brown. Digital Computer Electronics. ;; McGraw-Hill. ISBN 0-02-800594-5. 1999. ;; ;; notably in Part 2, p.140. (in-package :cl-vhdsl/SAP-1) ;; ---------- Architecture ---------- (defparameter *SAP-1-system* (make-instance 'architecture) "SAP-1 architecture.") (defparameter *SAP-1-core* (make-instance 'core) "SAP-1 core.") (dolist (r (list (make-instance 'data-register :name 'A :width 8 :documentation "Accumulator.") (make-instance 'data-register :name 'OUT :width 8 :documentation "Output register.") (make-instance 'program-counter :name 'PC :width 4 :documentation "Program counter."))) (setf (gethash (register-name r) (core-registers *SAP-1-core*)) r)) ;; ---------- Addressing modes ---------- (defclass absolute (addressing-mode) ((addr :documentation "The address, a 4-bit word." :initarg :address :reader absolute-address)) (:documentation "An absolute address, stored inline.")) (defun absolute (&rest args) (apply #'make-instance (cons 'absolute args))) (defmethod addressing-mode-behaviour ((mode absolute) c) (absolute-address mode)) (defmethod addressing-mode-bytes ((mode absolute)) '()) ;; ---------- Instruction set ---------- ;; LDA (defclass LDA (instruction) () (:documentation "LoaD Accumulator.")) (defmethod instruction-addressing-mode ((ins (eql 'LDA))) '(absolute)) (defmethod instruction-opcode ((ins LDA)) (let* ((a (absolute-address (instruction-addressing-mode ins))) opcode) (setf-bitfields opcode (0 0 0 0 a a a a)) opcode)) (defmethod instruction-behaviour ((ins LDA) c) (setf (emu:core-register-value 'A c) (emu:core-memory-location (instruction-argument ins c) c))) ;; ADD (defclass ADD (instruction) () (:documentation "ADD value ad address to the accumulator.")) (defmethod instruction-addressing-mode ((ins (eql 'ADD))) '(absolute)) (defmethod instruction-opcode ((ins ADD)) (let* ((a (absolute-address (instruction-addressing-mode ins))) opcode) (setf-bitfields opcode (0 0 0 1 a a a a)) opcode)) (defmethod instruction-behaviour ((ins ADD) c) (setf (emu:core-register-value 'A c) (+ (emu:core-register-value 'A c) (emu:core-memory-location (instruction-argument ins c) c)))) ;; SUB (defclass SUB (instruction) () (:documentation "SUBtract value at address from the accumulator.")) (defmethod instruction-addressing-mode ((ins (eql 'SUB))) '(absolute)) (defmethod instruction-opcode ((ins SUB)) (let* ((a (absolute-address (instruction-addressing-mode ins))) opcode) (setf-bitfields opcode (0 0 1 0 a a a a)) opcode)) (defmethod instruction-behaviour ((ins SUB) c) (setf (emu:core-register-value 'A c) (- (emu:core-register-value 'A c) (emu:core-memory-location (instruction-argument ins c) c)))) ;; OUT (defclass OUT (instruction) () (:documentation "Copy the accumulator to the OUTput register.")) (defmethod instruction-addressing-mode ((ins (eql 'OUT))) '(implicit)) (defmethod instruction-opcode ((ins OUT)) (let (opcode) (setf-bitfields opcode (1 1 1 0 0 0 0 0)) opcode)) (defmethod instruction-behaviour ((ins OUT) c) (setf (emu:core-register-value 'OUT c) (emu:core-register-value 'A c))) ;; HLT (defclass HLT (instruction) () (:documentation "HaLT execution.")) (defmethod instruction-opcode ((ins HLT)) (let (opcode) (setf-bitfields opcode (1 1 1 1 0 0 0 0)) opcode)) (defmethod instruction-addressing-modes ((ins (eql 'HLT))) '(implicit)) (defmethod instruction-behaviour ((ins HLT) c) (emu:core-end-program c))
4,481
Common Lisp
.lisp
120
34.391667
75
0.704419
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e168e15057fa2995fba26fd1c641e82090fb16cd6ba8a3cccf3afd38219fbff4
26,597
[ -1 ]
26,598
package.lisp
simoninireland_cl-vhdsl/systems/sap-1/test/package.lisp
;; Test package for the SAP-1 emulator ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :common-lisp-user) (defpackage cl-vhdsl/SAP-1/test (:use :cl :cl-ppcre :cl-vhdsl :cl-vhdsl/SAP-1) (:local-nicknames (:def :cl-vhdsl/def) (:emu :cl-vhdsl/emu)) (:import-from :fiveam #:is #:test #:def-suite)) (in-package :cl-vhdsl/SAP-1/test) (def-suite cl-vhdsl/SAP-1)
1,092
Common Lisp
.lisp
26
40.384615
75
0.734463
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d1ee8794b398e483950faf0ba05f6be0815d2ad69cd585a6817ce6dc5ca2d99e
26,598
[ -1 ]
26,599
test-emu.lisp
simoninireland_cl-vhdsl/systems/sap-1/test/test-emu.lisp
;; Tests of SAP-1 software emulation ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/SAP-1/test) (test test-10.2 "Test the basics (example 10-2)." (let* ((mem (make-instance 'emu:cached-memory :size 16)) (core (emu:make-core *SAP-1-core*))) (emu:memory-initialise mem) (let ((p (list (make-instance 'LDA :addressing-mode (absolute :address #16rF)) (make-instance 'ADD :addressing-mode (absolute :address #16rE)) (make-instance 'OUT :addressing-mode (def:implicit)) (make-instance 'HLT :addressing-mode (def:implicit))))) (emu:load-program p mem :initial #16r0) (setf (emu:memory-location mem #16rF) 1) (setf (emu:memory-location mem #16rE) 2) (emu:run-program core mem :initial #16r0) (is (equal (emu:core-register-value 'OUT core) 3))))) (test test-10-4 "Test the basics (example 10-4)." (let* ((mem (make-instance 'emu:cached-memory :size 16)) (core (emu:make-core *SAP-1-core*))) (emu:memory-initialise mem) (let ((p (list (make-instance 'LDA :addressing-mode (absolute :address #16r9)) (make-instance 'ADD :addressing-mode (absolute :address #16rA)) (make-instance 'ADD :addressing-mode (absolute :address #16rB)) (make-instance 'SUB :addressing-mode (absolute :address #16rC)) (make-instance 'OUT :addressing-mode (def:implicit)) (make-instance 'HLT :addressing-mode (def:implicit))))) (emu:load-program p mem :initial #16r0) (setf (emu:memory-location mem #16r9) #16r10) (setf (emu:memory-location mem #16rA) #16r14) (setf (emu:memory-location mem #16rB) #16r18) (setf (emu:memory-location mem #16rC) #16r20) (emu:run-program core mem :initial #16r0) ;; check result (is (equal (emu:core-register-value 'OUT core) (- (+ #16r10 #16r14 #16r18) #16r20))) ;; check opcode compilation (is (equal (emu:core-memory-location #16r0 core) #16r09)) (is (equal (emu:core-memory-location #16r1 core) #16r1A)) (is (equal (emu:core-memory-location #16r2 core) #16r1B)) (is (equal (emu:core-memory-location #16r3 core) #16r2C)) (is (equal (emu:core-memory-location #16r4 core) #16rE0)) (is (equal (emu:core-memory-location #16r5 core) #16rF0)))))
2,967
Common Lisp
.lisp
59
45.915254
90
0.686918
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7d67b7d088aa93a6c7eec01d5b77b0d655d4770baf1aea58a8567a2f41cfd414
26,599
[ -1 ]
26,600
test-explicit.lisp
simoninireland_cl-vhdsl/systems/sap-1/test/test-explicit.lisp
;; Tests of SAP-1 reference implementation ;; ;; Copyright (C) 2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-vhdsl/SAP-1/test) (test test-immediate-exit "Test we can immediately exit." (let ((mem (make-array (list 16) :element-type '(integer 0 255) :initial-element 0))) (setf (aref mem 0) #2r11110000) ;; hlt (is (equal (run-reference mem) 0)))) (test test-load "Test a load." (let ((mem (make-array (list 16) :element-type '(integer 0 255) :initial-element 0))) ;; (lda 8) (out) (hlt) (setf (aref mem 0) #2r00001000) ;; lda 8 (setf (aref mem 1) #2r11100000) ;; out (setf (aref mem 2) #2r11110000) ;; hlt ;; data (setf (aref mem 8) #2r11111110) ;; 254 (is (equal (run-reference mem) 254)))) (test test-load-no-output "Test a load that doesn't change the output register." (let ((mem (make-array (list 16) :element-type '(integer 0 255) :initial-element 0))) (setf (aref mem 0) #2r00001000) ;; lda 8 (setf (aref mem 1) #2r11110000) ;; hlt ;; data (setf (aref mem 8) #2r11111110) ;; 254 (is (equal (run-reference mem) 0)))) (test test-load-add-sub "Test we can add and subtract." (let ((mem (make-array (list 16) :element-type '(integer 0 255) :initial-element 0))) (setf (aref mem 0) #2r00001000) ;; lda 8 (setf (aref mem 1) #2r00011001) ;; add 9 (setf (aref mem 2) #2r00101010) ;; sub 10 (setf (aref mem 3) #2r11100000) ;; out (setf (aref mem 4) #2r11110000) ;; hlt ;; data (setf (aref mem 8) #2r00001100) ;; 12 (setf (aref mem 9) #2r00000010) ;; 2 (setf (aref mem 10) #2r00000011) ;; 3 (is (equal (run-reference mem) 11))))
2,452
Common Lisp
.lisp
63
35.253968
75
0.648125
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
59bfa3736fb962ada9c6634b98206b753dd118742c6ed28692cab4b56c7d9899
26,600
[ -1 ]
26,601
cl-vhdsl.asd
simoninireland_cl-vhdsl/cl-vhdsl.asd
;; System definitions ;; ;; Copyright (C) 2023--2024 Simon Dobson ;; ;; This file is part of cl-vhdsl, a Common Lisp DSL for hardware design ;; ;; cl-vhdsl is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-vhdsl is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. ;; ---------- cl-vhdsl ---------- (asdf:defsystem "cl-vhdsl" :description "An experiment in building a hardware and processor description DSL." :author "Simon Dobson <[email protected]" :version (:read-file-form "version.sexp") :license "GPL3" :depends-on ("alexandria" "cl-bitfields" "cl-ppcre" "cl-interpol" "str" "closer-mop" "slot-extra-options" "clast") :pathname "src/" :serial t :components ((:file "package") (:file "utils") (:module "def" :components ((:file "package") (:file "types") (:file "constants") (:file "conditions") (:file "arch") (:file "register") (:file "addressing") (:file "instruction"))) (:module "emu" :components ((:file "package") (:file "arch") (:file "cached-memory") (:file "emu") (:file "conditions"))) (:module "hw" :components ((:file "package") (:file "arch") (:file "mop") (:file "component") (:file "mixins") (:file "wiring") (:file "register") (:file "alu") (:file "ram") (:file "ring-counter") (:file "microinstruction") (:file "control") (:file "debugging") (:file "conditions"))) (:module "rtl" :components ((:file "package") (:file "syntax") (:file "parser") (:file "conditions")))) :in-order-to ((test-op (test-op "cl-vhdsl/test")))) (asdf:defsystem "cl-vhdsl/test" :description "Global tests of VHDSL." :depends-on ("alexandria" "cl-vhdsl" "cl-vhdsl/6502" "fiveam") :pathname "test/" :serial t :components ((:file "package") (:file "test-utils") (:file "test-debugging") (:file "test-mop") ;;(:file "test-assembler") (:file "test-wires") (:file "test-wiring") (:file "test-registers") (:file "test-alu") (:file "test-datapath") (:file "test-ring-counters") ;;(:file "test-microinstructions") (:file "test-rtl") ) :perform (test-op (o c) (uiop:symbol-call :fiveam '#:run-all-tests))) ;; ---------- 6502 emulator ---------- (asdf:defsystem "cl-vhdsl/6502" :description "A 6502 emulator in software" :author "Simon Dobson <[email protected]" :license "GPL3" :depends-on ("alexandria" "cl-ppcre" "cl-vhdsl") :pathname "systems/6502/" :serial t :components ((:file "package") (:file "arch") (:file "addressing") (:file "instructions") (:file "assembler") (:file "emu")) :in-order-to ((test-op (test-op "cl-vhdsl/6502/test")))) (asdf:defsystem "cl-vhdsl/6502/test" :description "Tests of VHDSL 6502 emulator." :depends-on ("cl-vhdsl/6502" "cl-ppcre" "fiveam") :pathname "systems/6502/test/" :serial t :components ((:file "package") (:file "test-assembler")) :perform (test-op (o c) (uiop:symbol-call :fiveam '#:run-all-tests))) ;; ---------- SAP-1 emulator ---------- (asdf:defsystem "cl-vhdsl/SAP-1" :description "A SAP-1 emulator in software" :author "Simon Dobson <[email protected]" :license "GPL3" :depends-on ("alexandria" "cl-ppcre" "cl-vhdsl") :pathname "systems/sap-1/" :serial t :components ((:file "package") (:file "sap-1") (:file "explicit")) :in-order-to ((test-op (test-op "cl-vhdsl/SAP-1/test")))) (asdf:defsystem "cl-vhdsl/SAP-1/test" :description "Tests of VHDSL SAP-1 emulator." :depends-on ("cl-vhdsl/SAP-1" "cl-ppcre" "fiveam") :pathname "systems/sap-1/test/" :serial t :components ((:file "package") (:file "test-explicit")) :perform (test-op (o c) (uiop:symbol-call :fiveam '#:run-all-tests)))
4,531
Common Lisp
.asd
131
29.251908
84
0.611491
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e56da1d5b619cee111bb27e9af77c5461083dbd5800f00565ad7c98cfcbaffc5
26,601
[ -1 ]
26,603
.readthedocs.yaml
simoninireland_cl-vhdsl/.readthedocs.yaml
version: 2 build: os: ubuntu-22.04 tools: python: "3.11" apt_packages: - libcurl4-openssl-dev jobs: post_system_dependencies: - git clone -b release https://github.com/roswell/roswell.git - (cd roswell && sh bootstrap && ./configure --prefix=$HOME/.local && make && make install) python: install: - requirements: requirements.txt sphinx: configuration: doc/conf.py
401
Common Lisp
.l
16
21.875
96
0.701571
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
001fcb1ed97f8201c525e9ca6d2047146f2fb78c2e7afff68f9faeef25ffd7b2
26,603
[ -1 ]
26,604
Makefile
simoninireland_cl-vhdsl/Makefile
# Makefile for cl-vhdsl # # Copyright (C) 2024 Simon Dobson # # This file is part of cl-vhdsl, a Common Lisp DSL for hardware design # # cl-vhdsl is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # cl-vhdsl is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with cl-vhdsl. If not, see <http://www.gnu.org/licenses/gpl.html>. # The version we're building VERSION = $(shell cat version.sexp) # ----- Sources ----- SOURCES_ASDF = cl-vhdsl.asd SOURCES = $(shell find src -name '*.lisp' -print) SOURCES_DOC = $(shell ls doc/*.rst) SOURCES_DOC_CONF = doc/conf.py # ----- Tools ----- # Base commands LISP = sbcl PYTHON = python3 PIP = pip VIRTUALENV = $(PYTHON) -m venv ACTIVATE = . $(VENV)/bin/activate CHDIR = cd # Files that are locally changed vs the remote repo # (See https://unix.stackexchange.com/questions/155046/determine-if-git-working-directory-is-clean-from-a-script) GIT_DIRTY = $(shell $(GIT) status --untracked-files=no --porcelain) # The git branch we're currently working on GIT_BRANCH = $(shell $(GIT) rev-parse --abbrev-ref HEAD 2>/dev/null) # Root directory ROOT = $(shell pwd) # Requirements for the documentation venv VENV = venv3 REQUIREMENTS = requirements.txt # Constructed commands RUN_SPHINX_HTML = PYTHONPATH=$(ROOT) make html # ----- Top-level targets ----- # Default prints a help message help: @make usage # Build the API documentation using Sphinx .PHONY: doc doc: env $(SOURCES_ASDF) $(SOURCES_DOC) $(SOURCES_DOC_CONF) $(ACTIVATE) && $(CHDIR) doc && $(RUN_SPHINX_HTML) # Build a documentation Python venv .PHONY: env env: $(VENV) $(VENV): $(VIRTUALENV) $(VENV) $(ACTIVATE) && $(PIP) install -U pip wheel && $(PIP) install -r requirements.txt # Make a new release release: $(SOURCES_GENERATED) master-only commit upload # Check we're on the master branch before uploading master-only: if [ "$(GIT_BRANCH)" != "master" ]; then echo "Can only release from master branch"; exit 1; fi # Update the remote repos on release # (This will trigger .github/workflows/release.yaml to create a GitHib release, and # .github/workflows/ci.yaml to run the full integration test suite) commit: check-local-repo-clean $(GIT) push origin master $(GIT) tag -a v$(VERSION) -m "Version $(VERSION)" $(GIT) push origin v$(VERSION) .SILENT: check-local-repo-clean check-local-repo-clean: if [ "$(GIT_DIRTY)" ]; then echo "Uncommitted files: $(GIT_DIRTY)"; exit 1; fi # Clean up the distribution build clean: $(RM) $(SOURCES_GENERATED) $(SOURCES_DIST_DIR) $(PACKAGENAME).egg-info dist $(SOURCES_DOC_BUILD_DIR) $(SOURCES_DOC_ZIP) # Clean up everything, including the computational environment (which is expensive to rebuild) reallyclean: clean $(RM) $(VENV) # ----- Generated files ----- # Manifest for the package MANIFEST: Makefile echo $(SOURCES_EXTRA) $(SOURCES_GENERATED) $(SOURCES_CODE_INIT) $(SOURCES_CODE) | $(TR) ' ' '\n' >$@ # The setup.py script setup.py: $(SOURCES_SETUP_IN) $(REQUIREMENTS) Makefile $(CAT) $(SOURCES_SETUP_IN) | $(SED) -e 's|VERSION|$(VERSION)|g' -e 's|REQUIREMENTS|$(PY_REQUIREMENTS)|g' >$@ # The source distribution tarball $(DIST_SDIST): $(SOURCES_GENERATED) $(SOURCES_CODE_INIT) $(SOURCES_CODE) Makefile $(ACTIVATE) && $(RUN_SETUP) sdist # The binary (wheel) distribution $(DIST_WHEEL): $(SOURCES_GENERATED) $(SOURCES_CODE_INIT) $(SOURCES_CODE) Makefile $(ACTIVATE) && $(RUN_SETUP) bdist_wheel # The tags file TAGS: $(ETAGS) -o TAGS $(SOURCES_CODE) # ----- Usage ----- define HELP_MESSAGE Available targets: make env create a documentation virtual environment make doc build the API documentation using Sphinx make release make a release make clean clean-up the build make reallyclean clean up the virtualenv as well endef export HELP_MESSAGE usage: @echo "$$HELP_MESSAGE"
4,248
Common Lisp
.l
108
37.675926
120
0.728425
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9bf82887f6f4bc9339141bd299fc3ca21e6a200ff8fe7ee06c7af81eef63bf77
26,604
[ -1 ]
26,652
Makefile
simoninireland_cl-vhdsl/doc/Makefile
# Minimal makefile for Sphinx documentation # # You can set these variables from the command line, and also # from the environment for the first two. SPHINXOPTS ?= SPHINXBUILD ?= sphinx-build SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
634
Common Lisp
.l
16
38.25
72
0.70684
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4acd02b509ce1d4bc4dcf29ef8b8db9541cf72e3ae10772909d83c1a07b5c15f
26,652
[ -1 ]
26,653
install.rst
simoninireland_cl-vhdsl/doc/install.rst
Installation ============ In a nutshell ------------- **Lisps**: Steel Bank Common Lisp v.24.0 or later **Operating systems**: Linux, OS X **License**: `GNU General Public License v3 or later (GPLv3) <http://www.gnu.org/licenses/gpl.html>`_ **Repository**: https://github.com/simoninireland/cl-vhdsl **Maintainer**: `Simon Dobson <mailto:[email protected]>`_ Installation with ASDF ---------------------- At the moment `CL-VHDSL` requires manual installation. Clone the repository into a directory that ASDF will find. There are several other Lisp libraries on which `CL-VHDSL` depends. These can be loaded from the repo directory using the `Makefile`: .. code-block:: shell make depends Then start your Lisp and run: .. code-block:: lisp (asdf:load-system "cl-vhdsl")
797
Common Lisp
.l
20
37.8
101
0.71916
simoninireland/cl-vhdsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2f0dcb78dc7a2d213373c1c528898c376b50fb877d393b97926c340fafc6597f
26,653
[ -1 ]
26,683
tasker.lisp
dpflug_cl-tasker/tasker.lisp
(defpackage #:cl-tasker (:use #:cl #:xml-emitter) (:import-from #:xml-emitter) (:export :flash :tasker-data)) (in-package :cl-tasker) (defun get-java-time () (+ (mod (get-internal-real-time) 1000) ; Close enough. (* 1000 (- (get-universal-time) 2208988800)))) ;;; Make hash tables easier to create. (set-macro-character #\{ (lambda (str char) (declare (ignore char)) ; Ignore me some warnings (let ((*readtable* (copy-readtable *readtable* nil)) (keep-going t)) (set-macro-character #\} (lambda (stream char) (declare (ignore char) (ignore stream)) (setf keep-going nil))) (let ((pairs (loop for key = (read str nil nil t) while keep-going for value = (read str nil nil t) collect (list key value))) (retn (gensym))) `(let ((,retn (make-hash-table :test #'equal))) ,@(mapcar (lambda (pair) `(setf (gethash ,(car pair) ,retn) ,(cadr pair))) pairs) ,retn))))) (defparameter *action-codes* {'FLASH 548 ;;---- Unimplemented below this line ---- 'NONE -1 ;; Is this a noop? 'FIRST-PLUGIN-CODE 1000 ; higher are all plugins ;Deprecated ;; Not sure what to do with these. I can't really test them? 'TEST-OLD 115 'TAKE-PHOTO-OLD 10 'TAKE-PHOTO-SERIES-OLD 11 'TAKE-PHOTO-CHRON-OLD 12 'LIST-VARIABLES 594 'TEST-FILE-OLD 411 'SET-SPEECH-PARAMS 876 'NOTIFY 500 'NOTIFY-LED-RED 510 'NOTIFY-LED-GREEN 520 'PERMANENT-NOTIFY 777 'NOTIFY-VIBRATE 530 'NOTIFY-SOUND 540 'POPUP-IMAGE-TASK-NAMES 557 'POPUP-TASK-ICONS 560 'POPUP-TASK-NAMES 565 'KEYGUARD-PATTERN 151 ; Active 'ANCHOR 300 'SET-SMS-APP 252 'SAY-AFTER 696 'SHUT-UP 697 'TORCH 511 'DPAD 701 'TYPE 702 'BUTTON 703 'NOTIFY-PLAIN 523 'NOTIFY-LED 525 'NOTIFY-VIBRATE-2 536 'NOTIFY-SOUND-2 538 'CANCEL-NOTIFY 779 'POPUP 550 'HTML-POPUP 941 'MENU 551 'POPUP-TASK-BUTTONS 552 'SET-ALARM 566 'START-TIMER 543 'CALENDAR-INSERT 567 'REBOOT 59 'VIBRATE 61 'MIDI-PLAY 156 'VIBRATE-PATTERN 62 'STATUS-BAR 512 'CLOSE-SYSTEM-DIALOGS 513 'MICROPHONE-MUTE 301 'VOLUME-ALARM 303 'VOLUME-RINGER 304 'VOLUME-NOTIFICATION 305 'VOLUME-CALL 306 'VOLUME-MUSIC 307 'VOLUME-SYSTEM 308 'VOLUME-DTMF 309 'VOLUME-BT-VOICE 311 'SILENT-MODE 310 'SOUND-EFFECTS-ENABLED 136 'HAPTIC-FEEDBACK 177 'SPEAKERPHONE-STATUS 254 'RINGER-VIBRATE 256 'NOTIFICATION-VIBRATE 258 'NOTIFICATION-PULSE 259 'DIALOG-SETTINGS 200 'DIALOG-ACCESSIBILITY-SETTINGS 236 'DIALOG-PRIVACY-SETTINGS 238 'DIALOG-AIRPLANE-MODE-SETTINGS 201 'DIALOG-ADD-ACCOUNT-SETTINGS 199 'DIALOG-APN-SETTINGS 202 'DIALOG-BATTERY-INFO-SETTINGS 251 'DIALOG-DATE-SETTINGS 203 'DIALOG-DEVICE-INFO-SETTINGS 198 'DIALOG-INTERNAL-STORAGE-SETTINGS 204 'DIALOG-DEVELOPMENT-SETTINGS 205 'DIALOG-WIFI-SETTINGS 206 'DIALOG-LOCATION-SOURCE-SETTINGS 208 'DIALOG-INPUT-METHOD-SETTINGS 210 'DIALOG-SYNC-SETTINGS 211 'DIALOG-NFC-SETTINGS 956 'DIALOG-NFC-SHARING-SETTINGS 957 'DIALOG-NFC-PAYMENT-SETTINGS 958 'DIALOG-DREAM-SETTINGS 959 'DIALOG-WIFI-IP-SETTINGS 212 'DIALOG-WIRELESS-SETTINGS 214 'DIALOG-APPLICATION-SETTINGS 216 'DIALOG-BLUETOOTH-SETTINGS 218 'DIALOG-ROAMING-SETTINGS 220 'DIALOG-DISPLAY-SETTINGS 222 'DIALOG-LOCALE-SETTINGS 224 'DIALOG-MANAGE-APPLICATION-SETTINGS 226 'DIALOG-MEMORY-CARD-SETTINGS 227 'DIALOG-NETWORK-OPERATOR-SETTINGS 228 'DIALOG-POWER-USAGE-SETTINGS 257 'DIALOG-QUICK-LAUNCH-SETTINGS 229 'DIALOG-SECURITY-SETTINGS 230 'DIALOG-SEARCH-SETTINGS 231 'DIALOG-SOUND-SETTINGS 232 'DIALOG-USER-DICTIONARY-SETTINGS 234 'INPUT-METHOD-SELECT 804 'POKE-DISPLAY 806 'SCREEN-BRIGHTNESS-AUTO 808 'SCREEN-BRIGHTNESS 810 'SCREEN-OFF-TIMEOUT 812 'ACCELEROMETER-ROTATION 822 'STAY-ON-WHILE-PLUGGED-IN 820 'KEYGUARD-ENABLED 150 'LOCK 15 'SYSTEM-LOCK 16 'SHOW-SOFT-KEYBOARD 987 'CAR-MODE 988 'NIGHT-MODE 989 'SET-LIGHT 999 'READ-BINARY 776 'WRITE-BINARY 775 'READ-LINE 415 'READ-PARA 416 'READ-FILE 417 'MOVE-FILE 400 'COPY-FILE 404 'COPY-DIR 405 'DELETE-FILE 406 'DELETE-DIR 408 'MAKE-DIR 409 'WRITE-TO-FILE 410 'LIST-FILES 412 'ZIP-FILE 420 'UNZIP-FILE 422 'VIEW-FILE 102 'BROWSE-FILES 900 'GET-FIX 902 'STOP-FIX 901 'GET-VOICE 903 'VOICE-COMMAND 904 'LOAD-IMAGE 188 'SAVE-IMAGE 187 'RESIZE-IMAGE 193 'ROTATE-IMAGE 191 'FLIP-IMAGE 190 'FILTER-IMAGE 185 'CROP-IMAGE 189 'TAKE-PHOTO-TWO 101 'ENCRYPT-FILE 434 'DECRYPT-FILE 435 'ENTER-PASSPHRASE 436 'CLEAR-PASSPHRASE 437 'SET-PASSPHRASE 423 'ENCRYPT-DIR 428 'DECRYPT-DIR 429 'KILL-APP 18 'LOAD-APP 20 'LOAD-LAST-APP 22 'SETCPU 915 'GO-HOME 25 'WAIT 30 'WAIT-UNTIL 35 'IF 37 'ENDIF 38 'ELSE 43 'FOR 39 'ENDFOR 40 'SEARCH 100 'RUN-SCRIPT 112 'JAVASCRIPTLET 129 'JAVASCRIPT 131 'RUN-SHELL 123 'REMOUNT 124 'RETURN 126 'TEST-NET 341 'TEST-FILE 342 'TEST-MEDIA 343 'TEST-APP 344 'TEST-VARIABLE 345 'TEST-PHONE 346 'TEST-TASKER 347 'TEST-DISPLAY 348 'TEST-SYSTEM 349 'TEST-SCENE 194 'SCENE-ELEMENT-TEST 195 'SAY 559 'SAY-TO-FILE 699 'SEND-INTENT 877 'VIEW-URL 104 'SET-CLIPBOARD 105 'SET-WALLPAPER 109 'HTTP-GET 118 'HTTP-POST 116 'OPEN-MAP 119 'ANDROID-MEDIA-CONTROL 443 'GRAB-MEDIA-BUTTON 490 'PLAY-RINGTONE 192 'BEEP 171 'MORSE 172 'MUSIC-PLAY 445 'MUSIC-PLAY-DIR 447 'MUSIC-STOP 449 'MUSIC-FORWARD 451 'MUSIC-BACK 453 'SCAN-CARD 459 'RINGTONE 457 'SOUND-RECORD 455 'SOUND-RECORD-STOP 657 'AUTO-SYNC 331 'AIRPLANE-MODE 333 'GPS-STATUS 332 'BLUETOOTH-STATUS 294 'BLUETOOTH-NAME 295 'BLUETOOTH-SCO 296 'BLOCK-CALLS 95 'DIVERT-CALLS 97 'REVERT-CALLS 99 'CONTACTS 909 'CALL-LOG 910 'EMAIL-COMPOSE 125 'SMS-COMPOSE 250 'MMS-COMPOSE 111 'TETHER-WIFI 113 'TETHER-USB 114 'TAKE-CALL 731 'RADIO-STATUS 732 'END-CALL 733 'SILENCE-RINGER 734 'MOBILE-NETWORK-MODE 735 'MAKE-PHONECALL 90 'MOBILE-DATA-STATUS 450 'MOBILE-DATA-STATUS-DIRECT 433 'SEND-TEXT-SMS 41 'SEND-DATA-SMS 42 'AIRPLANE-RADIOS 323 'WIFI-STATUS 425 'WIFI-NET-CONTROL 426 'WIFI-SLEEP-POLICY 427 'WIMAX-STATUS 439 'SET-TIMEZONE 440 'CHANGE-ICON-SET 140 'CHANGE-WIDGET-TEXT 155 'CHANGE-WIDGET-ICON 152 'TOGGLE-PROFILE 159 'QUERY-ACTION 134 'RUN-TASK 130 'GOTO 135 'STOP 137 'DISABLE-TASKER 139 'TASKER-LOGGING 283 'SET-TASKER-ICON 138 'SET-TASKER-PREF 133 'CREATE-SCENE 46 'SHOW-SCENE 47 'HIDE-SCENE 48 'DESTROY-SCENE 49 'SCENE-ELEMENT-VALUE 50 'SCENE-ELEMENT-FOCUS 68 'SCENE-ELEMENT-TEXT 51 'SCENE-ELEMENT-TEXT-COLOUR 54 'SCENE-ELEMENT-TEXT-SIZE 71 'SCENE-ELEMENT-BACKGROUND-COLOUR 55 'SCENE-ELEMENT-BORDER 56 'SCENE-ELEMENT-POSITION 57 'SCENE-ELEMENT-SIZE 58 'SCENE-ELEMENT-ADD-GEOMARKER 60 'SCENE-ELEMENT-DELETE-GEOMARKER 63 'SCENE-ELEMENT-WEB-CONTROL 53 'SCENE-ELEMENT-MAP-CONTROL 64 'SCENE-ELEMENT-VISIBILITY 65 'SCENE-ELEMENT-CREATE 69 'SCENE-ELEMENT-DESTROY 73 'SCENE-ELEMENT-IMAGE 66 'SCENE-ELEMENT-DEPTH 67 'ARRAY-PUSH 355 'ARRAY-PROCESS 369 'ARRAY-POP 356 'ARRAY-CLEAR 357 'SET-VARIABLE 547 'SET-VARIABLE-RANDOM 545 'INC-VARIABLE 888 'DEC-VARIABLE 890 'CLEAR-VARIABLE 549 'SPLIT-VARIABLE 590 'JOIN-VARIABLE 592 'QUERY-VARIABLE 595 'CONVERT-VARIABLE 596 'SECTION-VARIABLE 597 'SEARCH-REPLACE-VARIABLE 598 'ASTRID 371 'BEYONDPOD 555 'DAILYROADS 568 'DUETODAY 599 'ANDROID-NOTIFIER 558 'NEWSROB 556 'OFFICETALK 643 'JUICE-DEFENDER-DATA 456 'JUICE-DEFENDER-STATUS 395 'SLEEPBOT 442 'SMSBACKUP 553 'TESLALED 444 'WIDGETLOCKER 458 'GENTLEALARM 911 'ZOOM-ELEMENT-STATE 793 'ZOOM-ELEMENT-POSITION 794 'ZOOM-ELEMENT-SIZE 795 'ZOOM-ELEMENT-VISIBILITY 721 'ZOOM-ELEMENT-ALPHA 760 'ZOOM-ELEMENT-IMAGE 761 'ZOOM-ELEMENT-COLOUR 762 'ZOOM-ELEMENT-TEXT 740 'ZOOM-ELEMENT-TEXT-SIZE 741 'ZOOM-ELEMENT-TEXT-COLOUR 742}) (defparameter *ifops* {'- 0 '~ 1 '!~ 2 '< 3 '> 4 '= 5 '!= 6 'even 7 'odd 8 'set 9 '!set 10 '~R 11 '!~R 12}) (defmacro action (action-code action-id ifclause label &rest arglist) "" (let ((c action-code) (id action-id) (ifop (car ifclause)) (lhs (cadr ifclause)) (rhs (caddr ifclause)) (args arglist)) `(with-tag ("Action" '(("sr" ,(format nil "act~A" id)) ("ve" 3))) (simple-tag "code" ,c) ,(let ((op (gethash ifop *ifops*))) (cond (op `(emit-simple-tags :lhs ,lhs :op ,(gethash ifop *ifops*) :rhs ,rhs)) ((and ifop (not op)) (warn "Your if clause countained a wrong operation. Try prepending it with :.")))) ,(if label `(simple-tag "label" ,label)) (loop for arg in ',args for i from 0 to ,(1- (length args)) do (cond ((stringp arg) (simple-tag "Str" arg `(("sr" ,(format nil "arg~A" i)) ("ve" 3)))) ((or (typep arg 'boolean) (integerp arg)) (simple-tag "Int" "" `(("sr" ,(format nil "arg~A" i)) ("val" ,(cond ((integerp arg) arg) (arg 1) (t 0)))))) (t (princ (format nil "Don't know how to handle variable ~A of type ~a" arg (type-of arg))))))))) (defmacro flash (str &key ((:if ifclause) nil) (id 0) (label nil) (long nil)) `(action (gethash :flash *action-codes*) ,id ,ifclause ,label ,str ,long)) (defmacro defaction (name &optional args kwargs) `(defmacro ,name (,@args &key ((:if ifclause) nil) (id 0) (label nil) ,@kwargs) `(action (gethash ',',name *action-codes*) ,id ,ifclause ,label ,,@args ,,@(loop for kwarg in kwargs collect (first kwarg))))) (defaction shut-up) (defaction javascriptlet (code) ((libraries "") (autoexit t) (timeout 45))) (defmacro tasker-data (&body body) `(with-tag ("TaskerData" '(("sr" "") ("dvi" 1) ("tv" "1.6u2"))) ,@(loop for (f . args) in body for i from 0 to (1- (length body)) collect `(,f ,@args :id ,i))))
10,005
Common Lisp
.lisp
413
20.656174
102
0.688035
dpflug/cl-tasker
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
5da731364b739ada84a5f2720946aef822fb4dcda07c90033e8d2888df9a60c0
26,683
[ -1 ]
26,684
cl-tasker.asd
dpflug_cl-tasker/cl-tasker.asd
(asdf:defsystem #:cl-tasker :name "cl-tasker" :author "David Pflug <[email protected]>" :maintainer "David Pflug <[email protected]" :description "Generator of Tasker XML files" :long-description "This is a package to help you create XML files that Tasker will import, so you can create projects, profiles, and tasks without fiddling with buttons and typing on a small touch screen." :depends-on (#:xml-emitter) :components ((:file "tasker")))
458
Common Lisp
.asd
8
54.5
207
0.751111
dpflug/cl-tasker
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
05cbbd9b0a24a3f5d1b39712e8c9b7e61f23c445243eb6e16f1e354cbc5f1b54
26,684
[ -1 ]
26,702
package.lisp
simoninireland_cl-bitfields/test/package.lisp
;; package.lisp: Test package ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (defpackage cl-bitfields/test (:use :cl :cl-bitfields :fiveam) (:import-from :fiveam #:is #:test)) (in-package :cl-bitfields/test) (def-suite cl-bitfields)
965
Common Lisp
.lisp
23
40.652174
79
0.756124
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
356c6dd7256fbd5a100840eda654c40146f5c83233912fcdfd93952877a63af2
26,702
[ -1 ]
26,703
test-bitfields.lisp
simoninireland_cl-bitfields/test/test-bitfields.lisp
;; test-bitfields.lisp: Test bitfield extraction and binding ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-bitfields/test) (in-suite cl-bitfields) ;; ---------- Extracting symbols from bitfield patterns ---------- (test test-symbols "Test we can extract symbols from a pattern." ;; null patterns (is (null (cl-bitfields::extract-symbols '()))) (is (null (cl-bitfields::extract-symbols '(0)))) (is (null (cl-bitfields::extract-symbols '(1)))) (is (null (cl-bitfields::extract-symbols '(-)))) (is (null (cl-bitfields::extract-symbols '(0 1)))) (is (null (cl-bitfields::extract-symbols '(0 - 1)))) ;; single symbols (including weird ones) (is (equal (cl-bitfields::extract-symbols '(x)) '(x))) (is (equal (cl-bitfields::extract-symbols '(x 0)) '(x))) (is (equal (cl-bitfields::extract-symbols '(*)) '(*))) ;; multiple symbols (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(x y)) '(x y)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(0 x y)) '(x y)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(x 0 y)) '(x y)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(x y -)) '(x y)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(x x y y y)) '(x y)))) ;; symbols with width specifiers (is (null (set-exclusive-or (cl-bitfields::extract-symbols '((x 3) 0)) '(x)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(z (x 3) y)) '(x y z)))) (is (null (set-exclusive-or (cl-bitfields::extract-symbols '(z (x 3) x)) '(x z))))) (test test-bad-symbols "Test that meaningless elements in a bitfield pattern throw an error." ;; string, not symbol (signals error (cl-bitfields::extract-symbols '(x y "hello"))) ;; non-bit value (signals error (cl-bitfields::extract-symbols '(2 - -))) ;; non-symbol leading a width specifier (signals error (cl-bitfields::extract-symbols '((2 1))))) ;; ---------- Extracting bits ---------- (test test-bit "Test we can extract single bits." (is (equal (cl-bitfields::extract-bits 0 1 0) 0)) (is (equal (cl-bitfields::extract-bits 0 1 1) 1)) (is (equal (cl-bitfields::extract-bits 1 1 1) 0)) (is (equal (cl-bitfields::extract-bits 3 1 #2r1000) 1)) (is (equal (cl-bitfields::extract-bits 5 1 #2r1000) 0))) (test test-bits "Test we can extract multiple bits." (is (equal (cl-bitfields::extract-bits 0 1 0) 0)) (is (equal (cl-bitfields::extract-bits 0 1 1) 1)) (is (equal (cl-bitfields::extract-bits 1 1 1) 0)) (is (equal (cl-bitfields::extract-bits 4 3 #2r11100) #2r111)) (is (equal (cl-bitfields::extract-bits 2 2 #2r11100) #2r10))) ;; ---------- Pattern compression ---------- (test test-pattern-compression "Test the pattern compression logic." ;; no action (is (equal (cl-bitfields::compress-pattern '(x y z)) '(x y z))) (is (equal (cl-bitfields::compress-pattern '(x y x)) '(x y x))) (is (equal (cl-bitfields::compress-pattern '(x 1 - x)) '(x 1 - x))) (is (equal (cl-bitfields::compress-pattern '((x 4) y x)) '((x 4) y x))) (is (equal (cl-bitfields::compress-pattern '((x 4) y (x 3))) '((x 4) y (x 3)))) ;; sequences (is (equal (cl-bitfields::compress-pattern '(x x x)) '((x 3)))) (is (equal (cl-bitfields::compress-pattern '(x x y)) '((x 2) y))) (is (equal (cl-bitfields::compress-pattern '((x 2) (x 3) y)) '((x 5) y))) (is (equal (cl-bitfields::compress-pattern '((x 2) x x)) '((x 4)))) (is (equal (cl-bitfields::compress-pattern '(y - (x 2) (x 3) y)) '(y - (x 5) y))) ;; sequences with unknown (run-time) widths (is (equal (cl-bitfields::compress-pattern '((x n) x y)) '((x (1+ n)) y))) (is (equal (cl-bitfields::compress-pattern '(x (x n) y)) '((x (1+ n)) y))) (is (equal (cl-bitfields::compress-pattern '(x (y n) z)) '(x (y n) z))) (is (equal (cl-bitfields::compress-pattern '((x n) x (x n) y)) '((x (+ n (1+ n))) y))) (is (equal (cl-bitfields::compress-pattern '((x n) (x m) y)) '((x (+ n m)) y)))) ;; ---------- with-bitfields ---------- (test test-destructuring-constants "Test constant matches, no binding." ;; successes (is (with-bitfields (0) #2r100 T)) (is (with-bitfields (1 0 0) #2r100 T)) ;; failures (body isn't evaluated) (is (not (with-bitfields (1 0 1) #2r100 T)))) (test test-destructuring-ignore "Test we ignore bits when needed." (is (with-bitfields (1 - 0) #2r100 T)) (is (with-bitfields (1 - 0) #2r110 T))) (test test-destructuring-bind-single "Test we bind single-bit variables correctly." ;; single-character symbols (is (equal (with-bitfields (x 0 0) #2r100 x) 1)) ;; long symbols (is (equal (with-bitfields (xyz 0 0) #2r100 xyz) 1))) (test test-destructuring-bind-multi "Test we bind multiple-bit variables correctly." (is (equal (with-bitfields (x x 0) #2r100 x) #2r10)) (is (equal (with-bitfields (x x x) #2r100 x) #2r100)) ;; occurrances don't have to be contiguous (is (equal (with-bitfields (x x 0 x) #2r1101 x) #2r111))) (test test-destructuring-bind-several "Test the binding of several variables." (is (equal (with-bitfields (x y 0) #2r100 (list x y)) (list 1 0))) (is (equal (with-bitfields (x x y 0) #2r1100 (list x y)) (list #2r11 0))) (is (equal (with-bitfields (x x y y) #2r1101 (list x y)) (list #2r11 1))) ;; intermingle with constants and wildcard bits (is (equal (with-bitfields (x x - - y y 1 0) #2r11011010 (list x y)) (list #2r11 #2r10))) ;; occurrances can be interleaved (strange but legal) (is (equal (with-bitfields (x y x y) #2r1101 (list x y)) (list #2r10 #2r11)))) (test test-destructuring-bind-width "Test we can bind bitfields using a width specifier." ;; simple match (is (equal (with-bitfields ((x 3)) #2r1010 x) #2r10)) ;; match with other elements (is (equal (with-bitfields ((x 3) 0) #2r1010 x) #2r101)) (is (equal (with-bitfields (y (x 3) z) #2r11010 (list x y z)) (list #2r101 1 0))) (is (equal (with-bitfields (0 (x 3) z) #2r11010 (list x z)) nil)) ;; match several uses of the same symbol (is (equal (with-bitfields (x (x 3) y) #2r11010 (list x y)) (list #2r1101 0))) (is (equal (with-bitfields ((x 2) (x 3) y) #2r110101 (list x y)) (list #2r11010 1))) (is (equal (with-bitfields ((x 2) y (x 3)) #2r110101 (list x y)) (list #2r11101 0))) ;; match a zero-width field (is (equal (with-bitfields ((x 0) y (x 3)) #2r110101 (list x y)) (list #2r101 0))) (is (equal (with-bitfields ((x 0) y (x 0)) #2r110101 (list x y)) (list 0 1)))) (test destructuring-bind-variable-width "Test that we can include expressions as field widths." ;; the simplest case (let ((w 3)) (is (equal (with-bitfields ((x w)) #2r1110 x) #2r110)) ;; more complicated cases (is (equal (with-bitfields (y (x w) z) #2r11101 (list x y z)) (list #2r110 1 1))) (is (equal (with-bitfields (y (x w) (x w) z) #2r11101011 (list x y z)) (list #2r110101 1 1))) (is (equal (with-bitfields (y (x w) 0 (x w) z) #2r111001011 (list x y z)) (list #2r110101 1 1))) (is (equal (with-bitfields (y (x w) 1 (x w) z) #2r111001011 (list x y z)) nil)) ;; computed field widths (is (equal (with-bitfields (y (x (+ w 1)) (x w) z) #2r111101011 (list x y z)) (list #2r1110101 1 1))) ;; side-effects in calculations (do once, in order) (let ((v 1)) (is (equal (with-bitfields ((x v) (y (setq v (1+ v))) (z (setq v (1+ v)))) #2r110111 (list x y z)) (list #2r1 #2r10 #2r111)))) (let ((v 1)) (is (equal (with-bitfields ((x v) (y (setq v (1+ v))) (y (setq v (1+ v)))) #2r110111 (list x y)) (list #2r1 #2r10111)))) ;; zero-width fields (let ((v 0)) (is (equal (with-bitfields ((x v) y (x 3)) #2r110101 (list x y)) (list #2r101 0)))) (let ((v 0)) (is (equal (with-bitfields ((x v) y) #2r110101 (list x y)) (list 0 1)))) ;; fields with nothing to match (let ((v 0)) (is (equal (with-bitfields ((x v) (y v)) #2r110101 (list x y)) (list 0 0)))))) ;; ---------- make-bitfields ---------- (test test-make-single "Test we can make simple bitfields." ;; constants (is (equal (make-bitfields (1)) 1)) (is (equal (make-bitfields (0)) 0)) ;; no don't care bits (signals error (make-bitfields (- 1))) ;; single variable (is (equal (let ((x #2r101)) (make-bitfields (x x x))) #2r101)) ;; split single variable (is (equal (let ((x #2r1001)) (make-bitfields (x x x 0 x))) #2r10001))) (test test-make-width "Test width specifiers." (is (equal (let ((x #2r1001)) (make-bitfields ((x 3)))) #2r001)) (is (equal (let ((x #2r1001)) (make-bitfields ((x 3) 1))) #2r0011)) (is (equal (let ((x #2r1001)) (make-bitfields ((x 3) 1 x))) #2r10011))) (test test-make-variable-width "Test we can make bitfields with variable widths." (is (equal (let ((x #2r10110) (w 3)) (make-bitfields ((x w) 1 x x))) #2r101110)) (is (equal (let ((x #2r10110) (y #2r10) (w 3) (v 2)) (make-bitfields ((x w) 1 (y v)))) #2r110110)) ;; zero-width fields (is (equal (let ((x #2r10110) (w 0)) (make-bitfields ((x w) 1 x x))) #2r110)) ;; side effects (is (equal (let ((x #2r10110) (y #2r10) (w 0)) (make-bitfields ((x (setq w (+ w 2))) 1 (y (setq w (1+ w)))))) #2r101010))) (test test-information-lost "Test that we signal a loss of information." ;; basic condition signalling (signals information-lost (let ((x #2r111)) (make-bitfields ((x 2))))) ;; check the right variales are included in the condition (handler-bind ((information-lost (lambda (c) (is (equal (information-lost-from c) '(x)))))) (let ((x #2r111)) (make-bitfields ((x 2))))) (handler-bind ((information-lost (lambda (c) (is (equal (information-lost-from c) '(y)))))) (let ((x #2r111) (y #2r11)) (make-bitfields ((x 3) y)))) (handler-bind ((information-lost (lambda (c) (is (equal (information-lost-from c) '(x y)))))) (let ((x #2r111) (y #2r11)) (make-bitfields ((x 2) y))))) ;; ---------- with-bitfields-f ---------- (test test-with-bitfields-f-simple "Test we can reconstruct simple patterns" ;; single variable (is (equal (let ((v #2r10110)) (with-bitfields-f (x x x 1 0) v (setq x #2r100)) v) #2r10010)) ;; result of the construct itself (is (equal (let ((v #2r10110)) (list (with-bitfields-f (x x x 1 0) v (setq x #2r100)) v)) (list #2r100 #2r10010))) ;; test with-bitfields didn't generate these side effects (is (equal (let ((v #2r10110)) (with-bitfields (x x x 1 0) v (setq x #2r100)) v) #2r10110)) ;; fail to deconstruct (is (equal (let ((v #2r10111)) (list (with-bitfields-f (x x x 1 0) v (setq x #2r100)) v)) (list nil #2r10111)))) (test test-with-bitfields-f-multi "Test multiple variables." (is (equal (let ((v #2r10111)) (list (with-bitfields-f (x x x y y) v (setq x #2r100) (setq y #2r00)) v)) (list #2r0 #2r10000))) (is (equal (let ((v #2r10111)) (list (with-bitfields-f (x x x 1 y y) v (setq x #2r100) (setq y #2r00)) v)) (list #2r0 #2r100100))) (is (equal (let ((v #2r1011101)) (with-bitfields-f (x x x 1 1 y y) v (setf x #2r000) (setf y #2r00)) v) #2r0001100)) (is (equal (let ((v #2r10111)) (list (with-bitfields-f (x x x y 1 y) v (setq x #2r100) (setq y #2r00)) v)) (list #2r0 #2r100010)))) (test test-with-bitfields-f-width "Test updates with width specifiers with side effects." (is (equal (let ((v #2r10111) (w 2)) (list (with-bitfields-f ((x (setq w (1+ w))) 1 (y (setq y (1- w)))) v (setq x #2r100) (setq y #2r00)) v)) (list #2r0 #2r100100)))) ;; ---------- setf-bitfields ---------- (test test-setf-bitfields "Test we can set bitfields to different places." ;; to variables (is (equal (let ((v 0) (x #2r111) (y #2r10)) (setf-bitfields v (x x x y y)) v) #2r11110)) ;; to the insides of lists (is (equal (let* ((l '(1 2 3)) (x #2r111) (y #2r10)) (setf-bitfields (elt l 1) (x x x y y)) l) (list 1 #2r11110 3))) ;; to the slots of objects ;; (also checks the general case of symbol-macrolet, since that's ;; the mechanism for slots and accessors: should we do them explicitly anyway?) (progn (defclass slotter () ((a :initform 0 :accessor slot-a))) (is (equal (let ((o (make-instance 'slotter)) (x #2r111) (y #2r10)) (setf-bitfields (slot-a o) (x x x y y)) (slot-a o)) #2r11110)) (is (equal (let ((o (make-instance 'slotter)) (x #2r111) (y #2r10)) (with-slots (a) o (setf-bitfields a (x x x y y)) (slot-a o))) ; check the slot, not the abbreviation #2r11110)) (is (equal (let ((o (make-instance 'slotter)) (x #2r111) (y #2r10)) (with-accessors ((acc slot-a)) o (setf-bitfields acc (x x x y y)) (slot-a o))) ; check the slot, not the abbreviation #2r11110))) ;; doesn't accept don't-care bits (signals error (let ((v 0) (x #2r111)) (setf-bitfields v (x x - x)))))
14,661
Common Lisp
.lisp
438
28.335616
86
0.582125
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d7d1b6ecef091992e2fa2b57e1b0359c065ab471138c2e550654b0abd0416352
26,703
[ -1 ]
26,704
package.lisp
simoninireland_cl-bitfields/src/package.lisp
;; cl-bitfields.lisp: Package definition for cl-bitfields ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (defpackage cl-bitfields (:use :cl) (:export #:with-bitfields #:with-bitfields-f #:setf-bitfields #:make-bitfields #:information-lost #:information-lost-from #:information-lost-warning)) (in-package :cl-bitfields)
1,074
Common Lisp
.lisp
28
36.285714
79
0.75
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
92297ee225c5675046f2c3e4e40865a7f025375eea79747689411376d48b7dc3
26,704
[ -1 ]
26,705
conditions.lisp
simoninireland_cl-bitfields/src/conditions.lisp
;; conditions.lisp: Conditions signalled by bitfield operations ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-bitfields) ;; ---------- Information lost condition ---------- (define-condition information-lost () ((var :initarg :variables :reader information-lost-from)) (:documentation "Signalled when information in a variable is not written out in a bitfield pattern.")) (defun informtion-lost-warning (c) "Display a warning about loss of information." (format t "Information lost in bitfield from variables ~A" (informtion-lost-from c)))
1,296
Common Lisp
.lisp
27
46.481481
104
0.75712
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
500f9de2f0393e69a3849a1a43755b8a29c2a92a477a86e5ef3631c20f92cf40
26,705
[ -1 ]
26,706
bitfields.lisp
simoninireland_cl-bitfields/src/bitfields.lisp
;; bitfields.lisp -- Bitfield manipulation ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (in-package :cl-bitfields) ;; ---------- Helper functions ---------- (defun extract-bits (b w n) "Extract W bits starting at B from N, where the least-significant bit is numbered 0" (logand (ash n (- (- (1+ b) w))) (- (ash 1 w) 1))) ;; ---------- Code generators ---------- ;; TODO Widths less than zero, or non-integer, are always errors. (defun extract-symbols (l) "Extract a list of symbols appearing in L. This identifies variables (symbols) to be matched against bits. Elements 0, 1, and - are ignored. A list should contain a symbol name and a bit width. Any other elements cause an error." (if (null l) '() (let ((syms (extract-symbols (cdr l))) (s (car l))) (cond ((member s '(0 1 -)) syms) ((symbolp s) (if (member s syms) syms (cons s syms))) ((listp s) (let ((q (car s))) (cond ((not (symbolp q)) (error "(~S ...) cannot appear in a bitmap pattern" q)) ((member q syms) syms) (t (cons q syms))))) (t (error "~S cannot appear in a bitmap pattern" s)))))) (defun bits-in-pattern (pat) "Count the number of bits PAT is trying to match. If the number of bits can be computed at compile-time (i.e., all the widths specifiers are constants), return the total number of bits as a number. Otherwise, return an expression that computes the number at run-time. PAT is assumed to be side-effect-free, which means it should first be passed through `relabel-pattern-width-specifiers` to factor-out calculated widths into new variable bindings." (labels ((count-bits (pat) (let ((p (car pat))) (cond ((null p) (list 0 '())) ;; width specifier ((listp p) (let ((w (cadr p)) (rest (count-bits (cdr pat)))) (if (numberp w) (list (+ (car rest) w) (cadr rest)) ; add to known width (list (car rest) (cons w (cadr rest)))))) ; add to sequence calculation ;; single-bit match (t (let ((rest (count-bits (cdr pat)))) (list (1+ (car rest)) (cadr rest)))))))) (let ((bits (count-bits pat))) (if (null (cadr bits)) ;; no expressions, return the number of bits (car bits) ;; we have expressions, return the number-of-bits calculation (if (equal (car bits) 0) (if (equal (length (cadr bits)) 1) (cadr bits) ; a single calculation, return directly `(+ ,@(cadr bits))) ; a sequence, add them together `(+ ,(car bits) ,@(cadr bits))))))) ; generally, add the known and sequence (defun compress-pattern (pat) "Compress PAT for more efficient compilation. This combines adjacent instances of the same variable into a width specifier, which extracts several bits in one go and so involves less bit-twiddling. PAT is assumed to be side-effect-free, which means it should first be passed through `relabel-pattern-width-specifiers` to factor-out calculated widths into new variable bindings." (if (null pat) '() (let* ((p (car pat)) (r (compress-pattern (cdr pat))) (q (car r))) (cond ((member p '(0 1 -)) ;; literal bits left unchanged (cons p r)) ((listp p) (cond ((equal (cadr p) 0) ;; (x 0) -> deleted r) ((listp q) (if (equal (car p) (car q)) ;; (x 3) (x 4) -> (x 7) (if (and (numberp (cadr p)) (numberp (cadr q))) ;; both widths known, compute total now (cons (list (car p) (+ (cadr p) (cadr q))) (cdr r)) ;; both sizes not known, add computation (cons (list (car p) `(+ ,(cadr p) ,(cadr q))) (cdr r))) ;; (x 3) (y 4) -> unchanged (cons p r))) ((symbolp q) (if (equal (car p) q) ;; (x 3) x -> (x 4) (if (numberp (cadr p)) ;; width is known, increment it (cons (list (car p) (1+ (cadr p))) (cdr r)) ;; width is not known, add computation (cons (list (car p) `(1+ ,(cadr p))) (cdr r))) ;; (x 3) y -> unchanged (cons p r))) (t (cons p r)))) ((symbolp p) (cond ((listp q) (if (equal p (car q)) ;; x (x 4) -> (x 5) (if (numberp (cadr q)) ;; width is known, increment it (cons (list (car q) (1+ (cadr q))) (cdr r)) ;; width is not known, add computation (cons (list (car q) `(1+ ,(cadr q))) (cdr r))) ;; x (y 4) -> unchanged (cons p r))) ((symbolp q) (if (equal p q) ;; x x -> (x 2) (cons (list p 2) (cdr r)) ;; x y -> unchanged (cons p r))) (t (cons p r)))) (t (cons p r)))))) (defun relabel-pattern-width-specifiers (pat) "Rewrite all variable width specifiers in PAT. A constant width specifier is left unchanged. A computed one is re-written to a new variable, and a list of definitions is returned along with the new pattern. This is used to prevent repeated computation of width expressions that might have side-effects. Width specifiers consisting of a single variable reference are not re-written, since such references can't generate side-effects." (if (null pat) '(() ()) (let ((p (car pat)) (rest (relabel-pattern-width-specifiers (cdr pat)))) (cond ((listp p) (if (not (numberp (cadr p))) ;; a computed width (if (symbolp (cadr p)) ;; a variable reference that can't cause a side effects (list (cons p (car rest)) (cadr rest)) ;; not a variable reference, re-write to a new variable (let ((nv (gensym))) (list (cons (list (car p) nv) ; re-written width (car rest)) (cons (list nv (cadr p)) ; new variable with width calculaton (cadr rest))))) ;; a fixed width, return unchanged (list (cons p (car rest)) (cadr rest)))) (t (list (cons p (car rest)) (cadr rest))))))) (defun generate-with-bitfields-destructure (pattern var escape) "Generate the code to destructure PATTERN from VAR. This function is the main code generator for `with-bitfields' that constructs the list of tests and assignments implied by the pattern. A list of assignments is returned, with any errors in pattern-matching at run-time resulting in a nil return from the block designated by ESCAPE. PATTERN should be side-effect-free, implying it has been passed through `relabel-pattern-width-specifiers' to convert any forms into variables. Any failures will generate a return to the block designanted ESCAPE." (labels ((match-bit (pat bits known computed) (if (null pat) '() (let ((p (car pat))) (if (listp p) ;; width specifier (let ((n (car p)) (w (cadr p))) (let ((exs (generate-extract bits w known computed))) (cons `(setf ,n (+ ,(car exs) (ash ,n ,w))) (match-bit (cdr pat) bits (cadr exs) (caddr exs))))) ;; single-bit match (let ((exs (generate-extract bits 1 known computed))) (case p ;; a 0 or 1 matches that bit, or escapes the binding ((0 1) (cons `(if (not (equal ,(car exs) ,p)) (return-from ,escape nil)) (match-bit (cdr pat) bits (cadr exs) (caddr exs)))) ;; a - matches any bit (- (match-bit (cdr pat) bits (cadr exs) (caddr exs))) ;; a symbol binds the bit in that variable (otherwise (cons `(setf ,p (+ ,(car exs) (ash ,p 1))) (match-bit (cdr pat) bits (cadr exs) (caddr exs)))))))))) ;; generate the code for the bit offset, collapsing ny zeros ;; or empty lists (generate-offset (bits known computed) (if (null computed) (if (equal known 0) bits `(- ,bits ,known)) (if (equal known 0) `(- ,bits ,@computed) `(- ,bits ,known ,@computed)))) ;; generate the call to `extract-bits' (generate-extract (bits wanted known computed) (if (numberp bits) ;; known width, implies no computation and all numbers (list `(extract-bits ,(- bits known) ,wanted ,var) (+ known wanted) computed) ;; unknown width (let ((offset (generate-offset bits known computed))) (if (numberp wanted) ;; known number of bits (list `(extract-bits ,offset ,wanted ,var) (+ known wanted) computed) ;; unknown number of bits (list `(extract-bits ,offset ,wanted ,var) known (append computed (list wanted)))))))) (let* ((bits (bits-in-pattern pattern))) (if (numberp bits) ;; number of bits is known at compile-time, use constants (match-bit pattern (1- bits) 0 nil) ;; number of bits must be computed (let ((nob (gensym))) `((let ((,nob (1- ,(if (equal (length bits) 1) (car bits) bits)))) ,@(match-bit pattern nob 0 nil)))))))) (defun extract-relabelling (l) "Generate relabellings for the variables in L. The patterns are the same as for `make-bitfields', with the difference that - (don't-care) bits aren't allowed. The relabellings are returned as a list of elements of the form (v nv) where nv is a new variable taking the value of variable v. The list acts as an alist to look-up the new names of variables; when the pairs are reversed, it is suitable for creating the corresponding let-bindings." (if (null l) '() (let ((syms (extract-relabelling (cdr l))) (s (car l))) (cond ((member s '(1 0)) ;; explicit bits don't generate bindings syms) ((equal s '-) ;; "don't care" bits not allowed (error "- cannot appear in a make-bitfields pattern")) ((symbolp s) ;; variable references (if (assoc s syms) syms (let ((x (gensym))) (cons (list s x) syms)))) ((listp s) ;; width specifiers (if (assoc (car s) syms) syms (let ((x (gensym))) (cons (list (car s) x) syms)))) (t (error "~S cannot appear in bitfield pattern" s)))))) (defun generate-make-bitfields-restructure (pattern var) "Generate the code required to reconstruct PATTERN. This is the main code generator for `make-bitfields'. VARS is an alist mapping program variables to new variables, allowing the variables to be changed as the bitfield value is built. VAR is the working variable for the bitfield being built. PATTERN should be side-effect-free, implying it has been passed through `relabel-pattern-width-specifiers' to convert any forms into variables." (labels ((make-bit (pat consumed vars) (if (null pat) '() (let* ((p (car pat)) (exs (make-bit (cdr pat) consumed vars))) (if (listp p) ;; width specifier (let* ((n (car p)) (nv (lookup-new-variable n vars)) (w (cadr p)) ;; optimise the cases where the widths are known (mask (if (numberp w) (1- (ash 1 w)) `(1- (ash 1 ,w)))) (shift (if (numberp w) (- w) `(- ,w)))) (append exs (list `(setf ,var (logior ,var (ash (logand ,nv ,mask) ,consumed))) `(setf ,nv (ash ,nv ,shift)) `(incf ,consumed ,w)))) ;; single-bit match (case p ;; 0 simply shifts the number of known bits (0 (append exs (list `(incf ,consumed)))) ;; one (1 (append exs (list `(setq ,var (logior ,var (ash 1 ,consumed))) `(incf ,consumed)))) ;; symbol has bit extracted (otherwise (let ((nv (cadr (assoc p vars)))) (append exs (list `(setq ,var (logior ,var (ash (logand ,nv 1) ,consumed))) `(setq ,nv (ash ,nv -1)) `(incf ,consumed)))))))))) ;; look-up the new corresponding to the old one (lookup-new-variable (n vars) (cadr (assoc n vars))) ;; generate code to check for information loss (generate-information-check (vars) (let* ((losing (gensym)) (checks (mapcar (lambda (v) `(if (not (equal ,(cadr v) 0)) (setf ,losing (append ,losing (list ',(car v)))))) vars))) `(let ((,losing '())) ,@checks (if (not (null ,losing)) (signal 'information-lost :variables ,losing)))))) (let* ((variables (extract-relabelling pattern)) (let-bindings (mapcar (lambda (p) (list (cadr p) (car p))) variables)) (consumed (gensym))) `(let (,@let-bindings (,consumed 0)) ,@(make-bit pattern consumed variables) ,(generate-information-check variables))))) ;; ---------- with-bitfields ---------- (defmacro with-bitfields (pattern n &rest body) "Bind variables in PATTERN to the bits of N within BODY. PATTERN is interpreted as a bitfield pattern with each element corrsponding to a bit. The last element of the list corresponds to the rightmpost (least significant) bit of N. Each element of PATTERN is one of 0, 1, -, a list, or a symbol. 0 and 1 must match with 0 or 1 in the corrsponding bit of N. - matches either 0 or 1 (the bit is ignored). A symbol will be declared in a let binding and have the corresponding bit bound to it. If the same symbol appears several times in PATTERN then it receives all the bits in the obvious order. The bits taken into a variable don't have to be consecutive. A list element should take the form (x w) where x is a symbol and w is a number. This creates a symbol with the name x that consumes w bits from the pattern. As with symbols binding single bits, the same symbol can appear in several width specifiers, or alone to bind a single bit. The width specifier can be a constant, a variable reference, or an arbitrary form that returns a number. Forms are evaluated in order and only once, so side-effects occur as expected. For example, the pattern '(x x x 0), when matched against the number 10 (#2r1010), will bind x to 5 (#2r101), the bits in the corresponding positions. The same pattern matched against 11 (#2r1011) will fail because the rightmost bits of the number and the pattern don't match. In an environment with `w = 3' and `v = 2' the following patterns are all the same: - (x x x 0) - ((x 3) 0) - ((x w) 0)) - ((x v) x 0) - ((x (+1 v)) 0) WITH-BITFIELDS returns the value of executing BODY in an environment extended by the extracted variables (if any), or nil if PATTERN doesn't match N." (let* ((syms (extract-symbols pattern)) (let-bindings (mapcar #'(lambda (s) (list s 0)) syms)) (relabels (relabel-pattern-width-specifiers pattern)) (cpattern (compress-pattern (car relabels))) (escape (gensym)) (var (gensym)) (decls-and-tests (generate-with-bitfields-destructure cpattern var escape)) (matcher `(let (,@let-bindings (,var ,n)) ,@decls-and-tests ,@body)) (widths (if (null (cadr relabels)) matcher `(let ,(cadr relabels) ,matcher)))) `(block ,escape ,widths))) ;; ---------- make-bitfields ---------- (defmacro make-bitfields (pattern) "Construct a value according to the bitfield PATTERN. The variables references in PATTERN should all be in scope. Literal 1 and 0 symbols are mapped to those bits. Variables may appear several times, and their bits are extrated and placed into the value in the expected order. Width specifiers appear as pairs (x w) where x is a variable name and w a width in bits, which may be a constant, a variable, or a form. For example, if x = 10 (#2r1010), the pattern '(x x x 0) creates the value 4 (#2r100)." (let* ((relabels (relabel-pattern-width-specifiers pattern)) (cpattern (compress-pattern (car relabels))) (result (gensym)) (decls-and-shifts (generate-make-bitfields-restructure cpattern result)) (matcher `(let ((,result 0)) ,decls-and-shifts ,result)) (widths (if (null (cadr relabels)) matcher `(let ,(cadr relabels) ,matcher)))) widths)) ;; ---------- setf-bitfields ---------- (defmacro setf-bitfields (v pattern) "Set the place identified by V to the bitfields constructed from PATTERN. This is shorthand for '(setf V (make-bitfields pattern))'." `(setf ,v (make-bitfields ,pattern))) ;; ---------- with-bitfields-f ---------- (defmacro with-bitfields-f (pattern n &rest body) "Destructure N according to pattern, then re-create it from values changed by BODY. N must designate a place suitable to be assigned to by `setf'. The value of N is first destructured using PATTERN (as used in `with-bindings', creating variables that are in scope for the forms in BODY. Oce all the BODY forms have been executed, N is re-created using PATTERN in the manner of `make-bitfields'. If N cannot be destructured according to PATTERN, `with-bitfields-f' returns nil. Otherwise it returns the value of the last BODY form." (let* ((syms (extract-symbols pattern)) (let-bindings (mapcar #'(lambda (s) (list s 0)) syms)) (relabels (relabel-pattern-width-specifiers pattern)) (cpattern (compress-pattern (car relabels))) (escape (gensym)) (var (gensym)) (decls-and-tests (generate-with-bitfields-destructure cpattern var escape)) (result (gensym)) (update (gensym)) (decls-and-shifts (generate-make-bitfields-restructure cpattern update)) (matcher `(let (,@let-bindings (,var ,n)) ,@decls-and-tests (let ((,result (progn ,@body)) (,update 0)) ,decls-and-shifts (setf ,n ,update) ,result))) (widths (if (null (cadr relabels)) matcher `(let ,(cadr relabels) ,matcher)))) `(block ,escape ,widths)))
18,384
Common Lisp
.lisp
483
32.660455
86
0.631972
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ad46b09d31f07ca99f8032f43fcd24e13bf00221799946ea3c3b87b4478e794d
26,706
[ -1 ]
26,707
cl-bitfields.asd
simoninireland_cl-bitfields/cl-bitfields.asd
;; cl-bitfields.asd: ASDF system definition for cl-bitfields ;; ;; Copyright (C) 2023 Simon Dobson ;; ;; This file is part of cl-bitfields, Common Lisp DSL macros for bitfields ;; ;; cl-bitfields is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; cl-bitfields is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with cl-bitfields. If not, see <http://www.gnu.org/licenses/gpl.html>. (defsystem "cl-bitfields" :description "Macros for manipulating bitfields in Common Lisp" :author "Simon Dobson <[email protected]" :version (:read-file-form "version.sexp") :license "GPL3" :depends-on ("alexandria") :pathname "src/" :serial t :components ((:file "package") (:file "conditions") (:file "bitfields")) :in-order-to ((test-op (test-op "cl-bitfields/test")))) (defsystem "cl-bitfields/test" :depends-on ("cl-bitfields" "fiveam") :pathname "test/" :components ((:file "package") (:file "test-bitfields")) :perform (test-op (o c) (uiop:symbol-call :fiveam '#:run-all-tests)))
1,479
Common Lisp
.asd
36
38.638889
79
0.724497
simoninireland/cl-bitfields
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9d428cd073a43c33a9a9ee11139319c88c86e51fbe4d0a0fde1a183b3295ba58
26,707
[ -1 ]
26,729
split-shot.lisp
smithzvk_Split-Shot/split-shot.lisp
(in-package :split-shot) (defvar *width* 800) (defvar *arena-height* 500) (defvar *height* 600) (defvar *keys* '(:1 :q :2 :w :3 :e :4 :r :5 :t :6 :y :7 :u :8 :i :9 :o :0)) (defgame split-shot () () (:viewport-width *width*) (:viewport-height *height*) (:viewport-title "SplitShot")) (defvar *black* (vec4 0 0 0 1)) (defvar *white* (vec4 1 1 1 1)) (defvar *red* (vec4 1 0 0 1)) (defvar *green* (vec4 0 1 0 1)) (defvar *origin* (vec2 0 0)) (defvar *cannon-pos* (vec2 (floor *width* 2) 0)) (defvar *cannon-rotation* 0.0) (defvar *cannon-turn-right* nil) (defvar *cannon-turn-left* nil) (defvar *shot-pos* *cannon-pos*) (defvar *initial-vel* 50) (defvar *shot-vel* (vec2 0 30)) (defvar *shot-fired* nil) (defvar *paused* nil "Indicates when we are in a paused state. In the paused state you can rewind the game state.") (defvar *history* nil "This holds the history of the game state for the given level. This allows for rewinding the game state.") (defvar *future* nil "This holds the saved future of the game state for the given level. This allows for moving forward in the game state history.") (defvar *shot-state* (make-array 19 :initial-element 100) "This holds the global state of all of your shots.") (defvar *key-pressed* (make-array 19 :initial-element nil) "Holds the current pressed state of the shot controlling keys.") (defparameter *fast-forward* 1.0) (defstruct shot pos vel ilo ihi) (defun shot-mass (shot) (iter (for i :from (shot-ilo shot) :to (shot-ihi shot)) (summing (aref *shot-state* i)))) (defun find-shot (index) (let ((shot (iter (for shot :in *shots*) (finding shot :such-that (<= (shot-ilo shot) index (shot-ihi shot)))))) (if shot (values shot (< (shot-ilo shot) index (shot-ihi shot))) nil))) (defvar *shots* () "A list of current shots.") (defstruct target pos) (defvar *live-targets* () "A list of targets that need to be hit to win the level.") (defvar *hit-targets* () "A list of targets that have already been hit.") (defun dot-product (va vb) (rtg-math.vector2:dot (bodge-math::value-of va) (bodge-math::value-of vb))) (defun distance-squared (va vb) (rtg-math.vector2:distance-squared (bodge-math::value-of va) (bodge-math::value-of vb))) (defun length-squared (v) (rtg-math.vector2:length (bodge-math::value-of v))) (defun perp-vec (vec) "Create a perpendicular vector by rotating 90 degrees clockwise." (vec2 (y vec) (- (x vec)))) (defun line-collision (pos line margin) "Test if point, POS, is within collision distance, MARGIN, of LINE specified as a list containing a starting point, a unit direction vector, and a length. This is a polling collision detector, so MARGIN should be chosen such that it is larger you ever expect to step in a given frame time step. If there is an collision, return the perpendicular distance to the line. Positive is to the right of the line as you stand at its starting point and look down its direction. Note that this isn't a sphero-cylinder style collision test. Ends of lines are not rounded and the margin doesn't apply to distances past the end of the line." (destructuring-bind (start direction length) line (let* ((diff (gamekit:subt pos start)) (a (dot-product diff direction))) (when (<= 0 a length) (let* ((perp (perp-vec direction)) (p (dot-product diff perp))) (when (<= (- margin) p margin) p)))))) (defun target-collision (pos target rad) (< (distance-squared pos target) (* rad rad))) (defparameter *boundary* (list (list (vec2 0 0) (vec2 0 +1) *arena-height*) (list (vec2 0 *arena-height*) (vec2 +1 0) *width*) (list (vec2 *width* *arena-height*) (vec2 0 -1) *arena-height*) (list (vec2 *width* 0) (vec2 -1 0) *width*))) (defparameter *levels* (list (list :cannon (list (vec2 (/ *width* 2) 0) (- (/ pi 2)) (/ pi 2)) :targets (list (vec2 (/ *width* 2) *arena-height*)) :walls ()) (list :cannon (list (vec2 (/ *width* 2) 0) (- (/ pi 2)) (/ pi 2)) :targets (list (vec2 (/ *width* 2) *arena-height*)) :walls (list (list (vec2 (* 0.75 *width*) (/ *arena-height* 2)) (vec2 -1 0) (* 0.5 *width*)))) (list :cannon (list (vec2 (/ *width* 2) 0) (- (/ pi 2)) (/ pi 2)) :targets (list (vec2 (* 0.75 *width*) *arena-height*) (vec2 (* 0.25 *width*) *arena-height*)) :walls ()) (list :cannon (list (vec2 (/ *width* 2) 0) (- (/ pi 2)) (/ pi 2)) :targets (list (vec2 (* 0.75 *width*) 0) (vec2 (* 0.25 *width*) 0)) :walls ()))) (defvar *level* nil "The current level") (defvar *level-number* 0 "The current level number") (defun real-time-seconds () "Return seconds since certain point of time." (float (/ (get-internal-real-time) internal-time-units-per-second) 0d0)) (defvar *last-time* (real-time-seconds) "Denotes timestamp of the last model frame.") (defmethod act ((app split-shot)) (let* ((new-time (real-time-seconds)) (dt (* (- new-time *last-time*) *fast-forward*)) (removal-list ())) (cond (*paused* (when (and *cannon-turn-left* *history*) (let ((state (pop *history*))) (push state *future*) (destructuring-bind (shots shot-state) state (setf *shots* shots) (setf *shot-state* shot-state)))) (when (and *cannon-turn-right* *future*) (let ((state (pop *future*))) (push state *history*) (destructuring-bind (shots shot-state) state (setf *shots* shots) (setf *shot-state* shot-state))))) (t ;; First save the current state and clear the future (when *shots* (push (list (mapcar #'copy-shot *shots*) (copy-seq *shot-state*)) *history*) (setf *future* nil)) (when *cannon-turn-left* (incf *cannon-rotation* 0.1)) (when *cannon-turn-right* (decf *cannon-rotation* 0.1)) ;; Steering of shots (iter (for key :in-vector *key-pressed* :with-index i) (when key (multiple-value-bind (shot interior) (find-shot i) (when (and shot (not interior)) (let ((perp (normalize (perp-vec (shot-vel shot))))) (cond ((= i (shot-ilo shot)) (setf (shot-vel shot) (add (mult (/ (* 18000 dt) (shot-mass shot)) perp) (shot-vel shot))) (setf (aref *shot-state* (shot-ilo shot)) (max 0 (- (aref *shot-state* (shot-ilo shot)) (* 30 dt))))) ((= i (shot-ihi shot)) (setf (shot-vel shot) (add (mult (/ (* -18000 dt) (shot-mass shot)) perp) (shot-vel shot))) (setf (aref *shot-state* (shot-ihi shot)) (max 0 (- (aref *shot-state* (shot-ihi shot)) (* 30 dt))))))) (when (= 0 (aref *shot-state* (shot-ilo shot))) (incf (shot-ilo shot))) (when (= 0 (aref *shot-state* (shot-ihi shot))) (decf (shot-ihi shot))) (when (< (shot-ihi shot) (shot-ilo shot)) (push shot removal-list)))))) ;; Handle shot motion (iter (for shot :in *shots*) ;; Integrate motion (setf (shot-pos shot) (add (shot-pos shot) (mult dt (shot-vel shot)))) ;; Detect collisions (when (or ;; Detect out of bounds (iter (for wall :in *boundary*) (for collision := (line-collision (shot-pos shot) wall 500)) (finding wall :such-that (and collision (< collision 0)))) ;; Detect collisions with walls (iter (for wall :in (getf *level* :walls)) (for collision := (line-collision (shot-pos shot) wall 5)) (finding wall :such-that collision))) (push shot removal-list))) (iter (for shot :in removal-list) (setf *shots* (remove shot *shots*)) (iter (for i :from (shot-ilo shot) :below (length *shot-state*)) (if (= 0 (aref *shot-state* i)) (finish) (setf (aref *shot-state* i) 0))) (let ((hit-targets ())) (iter (for target :in *live-targets*) (when (target-collision (shot-pos shot) target 10) (push target hit-targets))) (iter (for target :in hit-targets) (push target *hit-targets*) (setf *live-targets* (remove target *live-targets*))))) (unless (iter (for val :in-vector *shot-state*) (thereis (> val 0))) (cond (*live-targets* (format t "~%Try again!") (init-level (nth (mod *level-number* (length *levels*)) *levels*))) (t (format t "~%Level Complete!") (incf *level-number*) (init-level (nth (mod *level-number* (length *levels*)) *levels*))))))) (setf *last-time* new-time))) (defmacro add-bindings ((keys state &body body) &rest more-bindings) "Setup bindings without as much boiler plate." (let ((lambda-sym (gensym "ADD-BINDINGS-"))) `(progn (let ((,lambda-sym (lambda (key) (declare (ignorable key)) ,@body))) ,@(iter (for k :in (ensure-list keys)) (collect `(bind-button ,k ,state (lambda () (funcall ,lambda-sym ,k)))))) ,@(if more-bindings `((add-bindings ,@more-bindings)) nil)))) (defun key-index (key) (position key *keys*)) (defun handle-split (shot i) (let ((pos (position shot *shots* :test 'eq)) (perp (normalize (perp-vec (shot-vel shot)))) (left-shot (make-shot :pos (shot-pos shot) :ilo (shot-ilo shot) :ihi (- i 1))) (right-shot (make-shot :pos (shot-pos shot) :ilo (+ i 1) :ihi (shot-ihi shot)))) ;; First split the shot (setf (aref *shot-state* i) 0) ;; Update the velocity given the new shots (setf (shot-vel left-shot) (add (mult (/ -6000 (shot-mass left-shot)) perp) (shot-vel shot))) (setf (shot-vel right-shot) (add (mult (/ 6000 (shot-mass right-shot)) perp) (shot-vel shot))) (setf *shots* (concatenate 'list (subseq *shots* 0 pos) (list left-shot right-shot) (subseq *shots* (+ pos 1)))))) (defun init-level (level) (unless level (stop)) (setf *level* level) (setf *key-pressed* (make-array (length *keys*) :initial-element nil)) (setf *shot-state* (make-array (length *keys*) :initial-element 100)) (setf *shots* nil) (setf *shot-fired* nil) (setf *paused* nil) (setf *history* nil) (setf *future* nil) (setf *live-targets* (getf *level* :targets)) (setf *hit-targets* ()) (destructuring-bind (pos min max) (getf *level* :cannon) (setf *cannon-pos* pos) (setf *cannon-rotation* 0.0) (setf *cannon-turn-right* nil) (setf *cannon-turn-left* nil))) (defmethod post-initialize ((this split-shot)) ;; Initialize world state (setf *last-time* (real-time-seconds)) (setf *level-number* 0) (init-level (nth (mod *level-number* (length *levels*)) *levels*)) ;; Setup bindings (add-bindings (:escape :pressed (stop)) ((:1 :q :2 :w :3 :e :4 :r :5 :t :6 :y :7 :u :8 :i :9 :o :0) :pressed (multiple-value-bind (shot interior) (find-shot (key-index key)) (if (and shot interior) ;; If the key is in the interior of a shot, then perform a split (handle-split shot (key-index key)) (setf (aref *key-pressed* (key-index key)) t)))) ((:1 :q :2 :w :3 :e :4 :r :5 :t :6 :y :7 :u :8 :i :9 :o :0) :released (setf (aref *key-pressed* (key-index key)) nil)) (:left :pressed (setf *cannon-turn-left* t)) (:left :released (setf *cannon-turn-left* nil)) (:right :pressed (setf *cannon-turn-right* t)) (:right :released (setf *cannon-turn-right* nil)) (:up :pressed (setf *fast-forward* (* *fast-forward* 2))) (:up :released (setf *fast-forward* (/ *fast-forward* 2))) (:down :pressed (setf *fast-forward* (/ *fast-forward* 2))) (:down :released (setf *fast-forward* (* *fast-forward* 2))) (:space :pressed (cond ((not *shot-fired*) (setf *shot-fired* t *shots* (list (make-shot :pos *cannon-pos* :vel (vec2 (* *initial-vel* (- (sin *cannon-rotation*))) (* *initial-vel* (cos *cannon-rotation*))) :ilo 0 :ihi (- (length *shot-state*) 1))))) (t (setf *paused* (not *paused*))))))) (defun draw-wall (direction length) (draw-line *origin* (mult length direction) *white* :thickness 5.0)) (defun draw-target (color) (draw-circle *origin* 15 :fill-paint color)) (defun draw-shot () (let ((w 10) (h 5)) (draw-rect (vec2 (/ w -2) (/ h -2)) w h :fill-paint *white* :rounding 5.0))) (defun draw-cannon () (with-pushed-canvas () (let ((w 7) (h 30)) (draw-circle *origin* 15 :fill-paint *white*) (rotate-canvas 0) (draw-rect (vec2 (/ w -2) 0) w h :fill-paint *white*)))) (defmethod draw ((this split-shot)) ;; Clear screen (draw-rect *origin* *width* *height* :fill-paint *black*) ;; Draw arena (iter (for shot :in *shots*) (with-pushed-canvas () (translate-canvas (x (shot-pos shot)) (y (shot-pos shot))) (rotate-canvas (atan (y (shot-vel shot)) (x (shot-vel shot)))) (draw-shot))) (with-pushed-canvas () (translate-canvas (x *cannon-pos*) (y *cannon-pos*)) (rotate-canvas *cannon-rotation*) (draw-cannon)) (iter (for target :in *live-targets*) (with-pushed-canvas () (translate-canvas (x target) (y target)) (draw-target *red*))) (iter (for target :in *hit-targets*) (with-pushed-canvas () (translate-canvas (x target) (y target)) (draw-target *green*))) (iter (for (start direction length) :in (append *boundary* (getf *level* :walls))) (with-pushed-canvas () (translate-canvas (x start) (y start)) (draw-wall direction length))) ;; Draw interface (draw-rect (vec2 0 *arena-height*) *width* (- *height* *arena-height*) :fill-paint *black*) (let ((box-width (/ *width* (length *keys*)))) (iter (for key :in *keys*) (for idx :from 0) (with-pushed-canvas () (translate-canvas (+ 2 (* idx box-width)) *arena-height*) (draw-rect *origin* (- box-width 4) (aref *shot-state* idx) :fill-paint *black* :stroke-paint *white*) (unless *shots* (draw-rect *origin* (- box-width 4) (aref *shot-state* idx) :fill-paint *red*)) (draw-text (string-downcase (symbol-name key)) *origin*))) (iter (for shot :in *shots*) (iter (for idx :from (shot-ilo shot) :to (shot-ihi shot)) (with-pushed-canvas () (translate-canvas (+ 2 (* idx box-width)) *arena-height*) (draw-rect *origin* (- box-width 4) (aref *shot-state* idx) :fill-paint *red*) (draw-text (string-downcase (symbol-name (nth idx *keys*))) *origin*))))))
16,876
Common Lisp
.lisp
389
32.534704
86
0.526191
smithzvk/Split-Shot
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
52fc67b1ecea7f68bd89c714ca5895520efe0e2c3ed603dba64606f3f2e86fb1
26,729
[ -1 ]
26,730
utils.lisp
smithzvk_Split-Shot/utils.lisp
(in-package :split-shot) (defun ensure-list (x) (if (consp x) x (list x)))
91
Common Lisp
.lisp
5
14
24
0.571429
smithzvk/Split-Shot
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
57ed00770e7afefed551244b18deccd05727f2e5b5c742d0cdc73bd93e5fd6d5
26,730
[ -1 ]
26,731
split-shot.asd
smithzvk_Split-Shot/split-shot.asd
(asdf:defsystem #:split-shot :author "Zach Kost-Smith" :license "GPLv3 or later" :version "0.1" :serial t :components ((:file "package") (:file "utils") (:file "split-shot")) :depends-on (:iterate :trivial-gamekit))
259
Common Lisp
.asd
9
23
42
0.598394
smithzvk/Split-Shot
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3d2e3115b4d394b812c992499dc28a415affcf867de9084920a87d25bae272f8
26,731
[ -1 ]
26,750
rfc8439.lisp
hackergrrl_rfc-8439/rfc8439.lisp
;;;; Implementation of RFC 8439: ChaCha20 and Poly1305 for IETF Protocols. ;; https://datatracker.ietf.org/doc/html/rfc8439 (defconstant +state-constants+ #(#x61707865 #x3320646e #x79622d32 #x6b206574)) (defconstant +p+ (- (expt 2 130) 5)) (defun norm32 (n) "Computes n mod 2^32." (logand n #xFFFFFFFF)) (defun 32+ (x y) "Computes (x + y) mod 2^32." (declare ((unsigned-byte 32) x y)) (norm32 (+ x y))) (defun rotl32 (n times) "Performs a 32-bit bitwise shift left with wrap-around." (norm32 (logior (ash n times) (ash n (- times 32))))) ;; 2.1 The ChaCha Quarter Round (defun qround (a b c d) (declare ((unsigned-byte 32) a b c d)) (setf a (32+ a b) d (logxor d a) d (rotl32 d 16) c (32+ c d) b (logxor b c) b (rotl32 b 12) a (32+ a b) d (logxor d a) d (rotl32 d 8) c (32+ c d) b (logxor b c) b (rotl32 b 7)) (values a b c d)) ;; 2.1.1. Test Vector for the ChaCha Quarter Round (defun test-vector-211 () (multiple-value-bind (a b c d) (qround #x11111111 #x01020304 #x9b8d6f43 #x01234567) (format t "a = ~X~%" a) (format t "b = ~X~%" b) (format t "c = ~X~%" c) (format t "d = ~X~%" d))) (defun print-state (state) (dotimes (i 4) (let* ((z (* i 4)) (a (+ 0 z)) (b (+ 1 z)) (c (+ 2 z)) (d (+ 3 z))) (format t "~X ~X ~X ~X~%" (aref state a) (aref state b) (aref state c) (aref state d))))) ;; 2.2 A Quarter Round on the ChaCha State (defun quarterround (state x y z w) (multiple-value-bind (a b c d) (qround (aref state x) (aref state y) (aref state z) (aref state w)) (setf (aref state x) a (aref state y) b (aref state z) c (aref state w) d))) ;; 2.2.1 Test Vector for the Quarter Round on the ChaCha State (defun test-vector-221 () (let ((state (make-array 16 :element-type '(unsigned-byte 32) :initial-contents '( #x879531e0 #xc5ecf37d #x516461b1 #xc9a62f8a #x44c20ef3 #x3390af7f #xd9fc690b #x2a5f714c #x53372767 #xb00a5631 #x974c541a #x359e9963 #x5c971061 #x3d631689 #x2098d9d6 #x91dbd320)))) (quarterround state 2 7 8 13) (print-state state))) ;; 2.3. The ChaCha20 Block Function (defun state-add (s1 s2) (dotimes (i 16) (setf (aref s1 i) (32+ (aref s1 i) (aref s2 i))))) (defun print-array (a) (dotimes (i (length a)) (format t "~2,'0X " (aref a i))) (format t "~%")) ;; uint32 array -> uint8 array (defun serialize-state (s) (let ((result (make-array 64 :element-type '(unsigned-byte 8)))) (dotimes (i 16) (let ((word (aref s i))) (setf (aref result (* i 4)) (logand #x000000FF word)) (setf (aref result (+ (* i 4) 1)) (ash (logand #x0000FF00 word) -8)) (setf (aref result (+ (* i 4) 2)) (ash (logand #x00FF0000 word) -16)) (setf (aref result (+ (* i 4) 3)) (ash (logand #xFF000000 word) -24)))) result)) (defun inner-block (state) (quarterround state 0 4 8 12) (quarterround state 1 5 9 13) (quarterround state 2 6 10 14) (quarterround state 3 7 11 15) (quarterround state 0 5 10 15) (quarterround state 1 6 11 12) (quarterround state 2 7 8 13) (quarterround state 3 4 9 14)) ;; (key: u32[8], counter: number|u32[1], nonce: u32[3]) => u8[] (defun chacha20-block (key counter nonce) (let* ((cntr (if (numberp counter) (make-array 1 :element-type '(unsigned-byte 32) :initial-contents (list counter)) counter)) (state (concatenate 'vector +state-constants+ key cntr nonce)) (initial-state (copy-seq state))) (dotimes (i 10) (inner-block state)) (state-add state initial-state) (serialize-state state))) ;; 2.3.2. Test Vector for the ChaCha20 Block Function (defun test-vector-232 () (let* ((key (make-array 8 :element-type '(unsigned-byte 32) :initial-contents '(#x03020100 #x07060504 #x0b0a0908 #x0f0e0d0c #x13121110 #x17161514 #x1b1a1918 #x1f1e1d1c))) (nonce (make-array 3 :element-type '(unsigned-byte 32) :initial-contents '(#x09000000 #x4a000000 #x00000000))) (counter (make-array 1 :element-type '(unsigned-byte 32) :initial-contents '(#x00000001))) (result (chacha20-block key counter nonce))) (print-array result) result)) ;; 2.4.1. The ChaCha20 Encryption Algorithm ;; (key: u32[8], counter: number|u32[1], nonce: u32[3], plaintext: u8[]) => u8[] (defun chacha20-encrypt (key counter nonce plaintext) (let ((ciphertext (make-array (length plaintext) :element-type '(unsigned-byte 8))) (cntr (if (numberp counter) counter (aref counter 0)))) (dotimes (j (floor (/ (length plaintext) 64))) (let* ((key-stream (chacha20-block key (+ j cntr) nonce))) (loop for k from (* j 64) to (+ (* j 64) 63) do (setf (aref ciphertext k) (logxor (aref plaintext k) (aref key-stream (- k (* j 64)))))))) (unless (eql 0 (mod (length plaintext) 64)) (let* ((j (floor (/ (length plaintext) 64))) (key-stream (chacha20-block key (+ j cntr) nonce))) (loop for k from (* j 64) to (1- (length plaintext)) do (setf (aref ciphertext k) (logxor (aref plaintext k) (aref key-stream (- k (* j 64)))))))) ciphertext)) ;; 2.4.2. Test Vector for the ChaCha20 Cipher (defun test-vector-242 () (let* ((key (make-array 8 :element-type '(unsigned-byte 32) :initial-contents '(#x03020100 #x07060504 #x0b0a0908 #x0f0e0d0c #x13121110 #x17161514 #x1b1a1918 #x1f1e1d1c))) (nonce (make-array 3 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #x4a000000 #x00000000))) (counter (make-array 1 :element-type '(unsigned-byte 32) :initial-contents '(#x00000001))) (plaintext (make-array 114 :element-type '(unsigned-byte 8) :initial-contents '(#x4c #x61 #x64 #x69 #x65 #x73 #x20 #x61 #x6e #x64 #x20 #x47 #x65 #x6e #x74 #x6c #x65 #x6d #x65 #x6e #x20 #x6f #x66 #x20 #x74 #x68 #x65 #x20 #x63 #x6c #x61 #x73 #x73 #x20 #x6f #x66 #x20 #x27 #x39 #x39 #x3a #x20 #x49 #x66 #x20 #x49 #x20 #x63 #x6f #x75 #x6c #x64 #x20 #x6f #x66 #x66 #x65 #x72 #x20 #x79 #x6f #x75 #x20 #x6f #x6e #x6c #x79 #x20 #x6f #x6e #x65 #x20 #x74 #x69 #x70 #x20 #x66 #x6f #x72 #x20 #x74 #x68 #x65 #x20 #x66 #x75 #x74 #x75 #x72 #x65 #x2c #x20 #x73 #x75 #x6e #x73 #x63 #x72 #x65 #x65 #x6e #x20 #x77 #x6f #x75 #x6c #x64 #x20 #x62 #x65 #x20 #x69 #x74 #x2e))) (result (chacha20-encrypt key counter nonce plaintext))) (print-array result) result)) (defun test-vector-242-decrypt () (let* ((key (make-array 8 :element-type '(unsigned-byte 32) :initial-contents '(#x03020100 #x07060504 #x0b0a0908 #x0f0e0d0c #x13121110 #x17161514 #x1b1a1918 #x1f1e1d1c))) (nonce (make-array 3 :element-type '(unsigned-byte 32) :initial-contents '(#x00000000 #x4a000000 #x00000000))) (counter (make-array 1 :element-type '(unsigned-byte 32) :initial-contents '(#x00000001))) (plaintext (make-array 114 :element-type '(unsigned-byte 8) ;; This is the ciphertext output from ;; test-vector-242! :initial-contents '(#x6E #x2E #x35 #x9A #x25 #x68 #xF9 #x80 #x41 #xBA #x07 #x28 #xDD #x0D #x69 #x81 #xE9 #x7E #x7A #xEC #x1D #x43 #x60 #xC2 #x0A #x27 #xAF #xCC #xFD #x9F #xAE #x0B #xF9 #x1B #x65 #xC5 #x52 #x47 #x33 #xAB #x8F #x59 #x3D #xAB #xCD #x62 #xB3 #x57 #x16 #x39 #xD6 #x24 #xE6 #x51 #x52 #xAB #x8F #x53 #x0C #x35 #x9F #x08 #x61 #xD8 #x07 #xCA #x0D #xBF #x50 #x0D #x6A #x61 #x56 #xA3 #x8E #x08 #x8A #x22 #xB6 #x5E #x52 #xBC #x51 #x4D #x16 #xCC #xF8 #x06 #x81 #x8C #xE9 #x1A #xB7 #x79 #x37 #x36 #x5A #xF9 #x0B #xBF #x74 #xA3 #x5B #xE6 #xB4 #x0B #x8E #xED #xF2 #x78 #x5E #x42 #x87 #x4D))) (result (chacha20-encrypt key counter nonce plaintext))) (print-array result) ;; Should be the original plaintext. result)) ;; 2.5.1. The Poly1305 Algorithm (defun clamp (r) (logand r #x0ffffffc0ffffffc0ffffffc0fffffff)) ;; lo, hi => inclusive range of indexes to use ;; (arr: u8[], lo: number, hi: number) => number (defun le-bytes-to-num (arr lo hi) (let ((result 0)) (dotimes (i (- hi lo)) (let ((j (+ i lo))) (setf result (+ result (ash (aref arr j) (* i 8)))))) result)) ;; (num: number) => u8[16] (defun num-to-16-le-bytes (num) (let ((result (make-array 16 :element-type '(unsigned-byte 8)))) (dotimes (i 16) (let* ((mask (ash #xFF (* i 8))) (octet (ash (logand num mask) (- (* i 8))))) (setf (aref result i) octet))) result)) ;; (num: number) => u8[8] (defun num-to-8-le-bytes (num) (let ((result (make-array 8 :element-type '(unsigned-byte 8)))) (dotimes (i 8) (let* ((mask (ash #xFF (* i 8))) (octet (ash (logand num mask) (- (* i 8))))) (setf (aref result i) octet))) result)) ;; key: array of (unsigned-byte 8) (defun poly1305-mac (msg key) (let ((r (clamp (le-bytes-to-num key 0 16))) (s (le-bytes-to-num key 16 32)) (a 0)) (dotimes (i (ceiling (/ (length msg) 16))) (let* ((lo (* i 16)) (hi (min (length msg) (* (1+ i) 16))) (n0 (le-bytes-to-num msg lo hi)) (n0-bits (* 8 (- hi lo))) (extra-bit (ash 1 n0-bits)) (n (+ n0 extra-bit))) (setf a (+ a n)) (setf a (mod (* r a) +p+)))) (setf a (+ a s)) (num-to-16-le-bytes a))) ;; 2.5.2. Poly1305 Test Vector (defun test-vector-252 () (let* ((key (make-array 32 :element-type '(unsigned-byte 8) :initial-contents '(#x85 #xd6 #xbe #x78 #x57 #x55 #x6d #x33 #x7f #x44 #x52 #xfe #x42 #xd5 #x06 #xa8 #x01 #x03 #x80 #x8a #xfb #x0d #xb2 #xfd #x4a #xbf #xf6 #xaf #x41 #x49 #xf5 #x1b))) (msg (make-array 34 :element-type '(unsigned-byte 8) :initial-contents '(#x43 #x72 #x79 #x70 #x74 #x6f #x67 #x72 #x61 #x70 #x68 #x69 #x63 #x20 #x46 #x6f #x72 #x75 #x6d #x20 #x52 #x65 #x73 #x65 #x61 #x72 #x63 #x68 #x20 #x47 #x72 #x6f #x75 #x70))) (result (poly1305-mac msg key))) (print-array result))) ;; 2.6.1. Poly1305 Key Generation ;; (arr: u8[], from: number, to: number) => u8[] (defun slice-u8 (arr from to) (let ((result (make-array (- to from) :element-type '(unsigned-byte 8)))) (dotimes (i (- to from)) (setf (aref result i) (aref arr (+ i from)))) result)) ;; Convert a u8 array to a u32 array. ;; (arr: u8[]) => u32-array (defun u8*-to-u32* (arr) (let ((result (make-array (floor (/ (length arr) 4)) :element-type '(unsigned-byte 32)))) (dotimes (i (floor (/ (length arr) 4))) (setf (aref result i) (logior (aref arr (* i 4)) (ash (aref arr (+ (* i 4) 1)) 8) (ash (aref arr (+ (* i 4) 2)) 16) (ash (aref arr (+ (* i 4) 3)) 24)))) result)) ;; (key: u8[32], nonce: u8[12]) => u8[] (defun poly1305-key-gen (key nonce) (slice-u8 (chacha20-block (u8*-to-u32* key) 0 (u8*-to-u32* nonce)) 0 32)) ;; 2.6.2. Poly1305 Key Generation Test Vector (defun test-vector-262 () (let* ((key (make-array 32 :element-type '(unsigned-byte 8) :initial-contents '(#x80 #x81 #x82 #x83 #x84 #x85 #x86 #x87 #x88 #x89 #x8a #x8b #x8c #x8d #x8e #x8f #x90 #x91 #x92 #x93 #x94 #x95 #x96 #x97 #x98 #x99 #x9a #x9b #x9c #x9d #x9e #x9f))) (nonce (make-array 12 :element-type '(unsigned-byte 8) :initial-contents '(#x00 #x00 #x00 #x00 #x00 #x01 #x02 #x03 #x04 #x05 #x06 #x07))) (result (poly1305-key-gen key nonce))) (print-array result))) ;; 2.8. AEAD Construction (defun make-u8* (len) (make-array len :element-type '(unsigned-byte 8))) (defun concat-u8* (&rest args) (apply #'concatenate 'vector args)) ;; Generates an array of zeroes that, if concatenated to `arr`, would result in an array with a ;; length divisible by 16. ;; (arr: u8[]) => u8[] (defun pad16 (arr) (let ((n (mod (length arr) 16))) (if (= 0 n) (make-u8* 0) (make-u8* (- 16 n))))) ;; (aad: u8[], key: u8[32], iv: u8[8], constant: u8[4], plaintext: u8[]) => u8[], u8[16] (defun chacha20-aead-encrypt (aad key iv constant plaintext) (let* ((nonce (concat-u8* constant iv)) (otk (poly1305-key-gen key nonce)) (key32 (u8*-to-u32* key)) (nonce32 (u8*-to-u32* nonce)) (ciphertext (chacha20-encrypt key32 1 nonce32 plaintext)) (mac-data (concat-u8* aad (pad16 aad) ciphertext (pad16 ciphertext) (num-to-8-le-bytes (length aad)) (num-to-8-le-bytes (length ciphertext)))) (tag (poly1305-mac mac-data otk))) (values ciphertext tag))) ;; (aad: u8[], key: u8[32], iv: u8[8], constant: u8[4], ciphertext: u8[]) => u8[], u8[16] (defun chacha20-aead-decrypt (aad key iv constant ciphertext) (let* ((nonce (concat-u8* constant iv)) (otk (poly1305-key-gen key nonce)) (key32 (u8*-to-u32* key)) (nonce32 (u8*-to-u32* nonce)) (plaintext (chacha20-encrypt key32 1 nonce32 ciphertext)) (mac-data (concat-u8* aad (pad16 aad) ciphertext (pad16 ciphertext) (num-to-8-le-bytes (length aad)) (num-to-8-le-bytes (length ciphertext)))) (tag (poly1305-mac mac-data otk))) (values plaintext tag))) ;; 2.8.2. Test Vector for AEAD_CHACHA20_POLY1305 (defun test-vector-282 () (let* ((plaintext (make-array 114 :element-type '(unsigned-byte 8) :initial-contents '(#x4c #x61 #x64 #x69 #x65 #x73 #x20 #x61 #x6e #x64 #x20 #x47 #x65 #x6e #x74 #x6c #x65 #x6d #x65 #x6e #x20 #x6f #x66 #x20 #x74 #x68 #x65 #x20 #x63 #x6c #x61 #x73 #x73 #x20 #x6f #x66 #x20 #x27 #x39 #x39 #x3a #x20 #x49 #x66 #x20 #x49 #x20 #x63 #x6f #x75 #x6c #x64 #x20 #x6f #x66 #x66 #x65 #x72 #x20 #x79 #x6f #x75 #x20 #x6f #x6e #x6c #x79 #x20 #x6f #x6e #x65 #x20 #x74 #x69 #x70 #x20 #x66 #x6f #x72 #x20 #x74 #x68 #x65 #x20 #x66 #x75 #x74 #x75 #x72 #x65 #x2c #x20 #x73 #x75 #x6e #x73 #x63 #x72 #x65 #x65 #x6e #x20 #x77 #x6f #x75 #x6c #x64 #x20 #x62 #x65 #x20 #x69 #x74 #x2e))) (aad (make-array 12 :element-type '(unsigned-byte 8) :initial-contents '(#x50 #x51 #x52 #x53 #xc0 #xc1 #xc2 #xc3 #xc4 #xc5 #xc6 #xc7))) (key (make-array 32 :element-type '(unsigned-byte 8) :initial-contents '(#x80 #x81 #x82 #x83 #x84 #x85 #x86 #x87 #x88 #x89 #x8a #x8b #x8c #x8d #x8e #x8f #x90 #x91 #x92 #x93 #x94 #x95 #x96 #x97 #x98 #x99 #x9a #x9b #x9c #x9d #x9e #x9f))) (iv (make-array 8 :element-type '(unsigned-byte 8) :initial-contents '(#x40 #x41 #x42 #x43 #x44 #x45 #x46 #x47))) (constant (make-array 4 :element-type '(unsigned-byte 8) :initial-contents '(#x07 #x00 #x00 #x00)))) (multiple-value-bind (ciphertext tag) (chacha20-aead-encrypt aad key iv constant plaintext) (format t "Ciphertext: ") (print-array ciphertext) (format t "Tag : ") (print-array tag) (multiple-value-bind (ptext tag2) (chacha20-aead-decrypt aad key iv constant ciphertext) (format t "Decrypted : ") (print-array ptext) (format t "Tag : ") (print-array tag2)))))
19,315
Common Lisp
.lisp
406
32.426108
95
0.468419
hackergrrl/rfc-8439
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9ff413b6f761827db3c8510a4bfbc7e112f50b8601fc4a7ae80f1d2c95161bd2
26,750
[ -1 ]
26,767
miguedrez.lisp
html_cl-chess/miguedrez.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; miguedrez.lisp ;;; Main ;;; gamallo, February 11, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (defpackage :miguedrez (:use :cl :cl-user) (:export :ajz :make-move :make-pos :*pieces* :make-player :create-initial-board-white-bottom :board-board :valid :execute-move :checkmatep :player-color :black :white)) (in-package :miguedrez) (defvar *calls* 0) (defmacro define-constant (name value &optional doc) `(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (define-constant +knight-bishop-pos-weigh+ (make-array 8 :initial-contents '(10 10 30 60 60 30 10 10))) (define-constant +rook-pos-weigh+ (make-array 8 :initial-contents '(60 30 30 10 10 30 30 60))) (define-constant +pawn-pos-v-weigh+ (make-array 8 :initial-contents '(0 0 5 10 30 100 250 900))) (define-constant +pawn-pos-h-weigh+ (make-array 8 :initial-contents '(2 5 10 20 20 10 5 2))) (defun ajz () ;; initialize (let* ((player1 (make-player :type 'manual :color 'white)) (player2 (make-player :type 'auto :color 'black)) ;; (table (create-initial-board-tests)) (table (create-initial-board-white-bottom)) (current-player) (current-move)) (setf current-player player1) (loop (show-board table) (setf *calls* 0) ;; checkmate? (if (checkmatep table current-player) ;; Yes -> end (progn (format t "Pierde el color ~A.~%" (player-color current-player)) (return)) ;; No -> load move (setf current-move (load-move table current-player))) ;; check move - including castlings (if (valid table current-move (player-color current-player)) ;; valid -> do movement (progn (execute-move table current-move) (if (eq current-player player1) (setf current-player player2) (setf current-player player1))) ;; invalid -> automatic? (if (eq (player-type current-player) 'auto) ;; yes -> error (progn (print "Esto es una mierda...") (return)) ;; not -> ask again (print "Movimiento de mierda. Otro, anda...")))))) (defun load-move (table player) (if (eq (player-type player) 'manual) (read-move) (choose-move table (player-color player))))
3,140
Common Lisp
.lisp
75
36.266667
170
0.646418
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
37556cd78a119d9a3e68922ab1dd7e04d4a5565d3a280f756a507ce2317eb8d4
26,767
[ -1 ]
26,768
io.lisp
html_cl-chess/io.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; io.lisp ;;; Input/Output ;;; gamallo, February 11, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. ;;; Hash table containing the descriptions of the pieces (in-package :miguedrez) (defvar *pieces* (make-hash-table)) (setf (gethash 'TN *pieces*) "BR") (setf (gethash 'TB *pieces*) "WR") (setf (gethash 'CN *pieces*) "BN") (setf (gethash 'CB *pieces*) "WN") (setf (gethash 'AN *pieces*) "BB") (setf (gethash 'AB *pieces*) "WB") (setf (gethash 'RN *pieces*) "BK") (setf (gethash 'RB *pieces*) "WK") (setf (gethash 'DN *pieces*) "BQ") (setf (gethash 'DB *pieces*) "WQ") (setf (gethash 'PN *pieces*) "BP") (setf (gethash 'PB *pieces*) "WP") (setf (gethash 'VV *pieces*) "..") ;;; Show board to the user (defun show-board (board) (format t "~% A B C D E F G H~%~%") (dotimes (row 8) (format t " ~A " (- 8 row)) (dotimes (column 8) (format t "~A " (gethash (aref (board-board board) row column) *pieces*))) (format t "~%~%"))) ;;; Ask the user for a move (defun read-move () (let (row-from column-from row-to column-to) (loop (when (and (not (null row-from)) (not (null column-from)) (not (null row-to)) (not (null column-to))) (return)) (format t "Movimiento: ") (let ((mov1 (read)) (mov2 (read))) (ignore-errors (when (= 2 (length (string mov1))) (setf row-from (digit-char-p (aref (string mov1) 1))) (setf column-from (position (aref (string mov1) 0) "ABCDEFGH" :test (function string-equal)))) (when (= 2 (length (string mov2))) (setf row-to (digit-char-p (aref (string mov2) 1))) (setf column-to (position (aref (string mov2) 0) "ABCDEFGH" :test (function string-equal))))))) ;; (format t "~A ~A ~A ~A" row-from column-from row-to column-to) (make-move :from (make-pos :row (- 8 row-from) :col column-from) :to (make-pos :row (- 8 row-to) :col column-to))))
2,839
Common Lisp
.lisp
69
36.028986
75
0.598188
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1a573d7c9a3f53778d41071e93b3026c8c607b4a8cc544ac5db1ca26bc9a22cb
26,768
[ -1 ]
26,769
data.lisp
html_cl-chess/data.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; data.lisp ;;; Data definitions and manipulation functions ;;; gamallo, February 11, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. ;;; Main data type (in-package :miguedrez) (defstruct board (board) (whites) (blacks) (whites-enpass) (blacks-enpass) (whites-initial-pos) (white-king-pos) (black-king-pos) (white-king-moved) (black-king-moved)) ;;; Player (defstruct player (type) ;; 'auto, 'manual (color)) ;; 'white, 'black (defun copy-board (board) (make-board :board (copy-board-array (board-board board)) :whites (copy-board-array (board-whites board)) :blacks (copy-board-array (board-blacks board)) :whites-enpass (copy-board-row (board-whites-enpass board)) :blacks-enpass (copy-board-row (board-blacks-enpass board)) :whites-initial-pos (board-whites-initial-pos board) :white-king-pos (copy-pos (board-white-king-pos board)) :black-king-pos (copy-pos (board-black-king-pos board)) :white-king-moved (board-white-king-moved board) :black-king-moved (board-black-king-moved board))) (defun copy-board-array (board-array) (let ((new-board-array (make-array '(8 8)))) (dotimes (row 8) (dotimes (col 8) (setf (aref new-board-array row col) (aref board-array row col)))) new-board-array)) (defun copy-board-row (row-array) (let ((new-row-array (make-array 8))) (dotimes (i 8 new-row-array) (setf (aref new-row-array i) (aref row-array i))))) (defun invert-color (color) (if (eq color 'white) 'black 'white)) (defun whitep (color) (eq color 'white)) ;;; Is a given position occupied by a color? (defun color-occupied-p (board-color row col) (eq (aref board-color row col) '1)) ;;; Position (defstruct pos (row) (col)) (defun equal-pos (pos1 pos2) (and (eq (pos-row pos1) (pos-row pos2)) (eq (pos-col pos1) (pos-col pos2)))) ;;; Creates a new pos given row and column and adds to the list (defmacro add-pos (pos-list row col) `(setf ,pos-list (cons (make-pos :row ,row :col ,col) ,pos-list))) ;;; A movement (defstruct move (from) (to)) (defun equal-moves (mov1 mov2) (and (equal-pos (move-from mov1) (move-from mov2)) (equal-pos (move-to mov1) (move-to mov2)))) ;;; A very used construction: a cell from a 8x8 vector (defmacro board-pos (board pos) `(aref ,board (pos-row ,pos) (pos-col ,pos))) ;;; Creates an initial board with the white pieces at the bottom (defun create-initial-board-white-bottom () (make-board :board (make-array '(8 8) :initial-contents '((TN CN AN DN RN AN CN TN) (PN PN PN PN PN PN PN PN) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (PB PB PB PB PB PB PB PB) (TB CB AB DB RB AB CB TB))) :whites (make-array '(8 8) :initial-contents '((0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1))) :blacks (make-array '(8 8) :initial-contents '((1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0))) :whites-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :blacks-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :whites-initial-pos 'bottom :white-king-pos (make-pos :row 7 :col 4) :black-king-pos (make-pos :row 0 :col 4) :white-king-moved nil :black-king-moved nil)) ;;; Creates an initial board with the white pieces at the top (defun create-initial-board-white-top () (make-board :board (make-array '(8 8) :initial-contents '((TB CB AB RB DB AB CB TB) (PB PB PB PB PB PB PB PB) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV VV VV VV) (PN PN PN PN PN PN PN PN) (TN CN AN RN DN AN CN TN))) :whites (make-array '(8 8) :initial-contents '((1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0))) :blacks (make-array '(8 8) :initial-contents '((0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (1 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1))) :whites-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :blacks-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :whites-initial-pos 'top :white-king-pos (make-pos :row 0 :col 3) :black-king-pos (make-pos :row 7 :col 3) :white-king-moved nil :black-king-moved nil)) ;;; Creates an initial test board (defun create-initial-board-tests () (make-board :board (make-array '(8 8) :initial-contents '((VV VV VV VV VV VV RN VV) (VV VV DB VV VV VV VV VV) (VV VV VV VV RB VV VV VV) (VV VV VV VV VV VV VV PN) (VV VV VV VV VV VV VV PB) (VV VV VV VV VV VV VV VV) (VV VV VV VV VV PB VV VV) (VV VV VV VV VV VV VV VV))) :whites (make-array '(8 8) :initial-contents '((0 0 0 0 0 0 0 0) (0 0 1 0 0 0 0 0) (0 0 0 0 1 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 1) (0 0 0 0 0 0 0 0) (0 0 0 0 0 1 0 0) (0 0 0 0 0 0 0 0))) :blacks (make-array '(8 8) :initial-contents '((0 0 0 0 0 0 1 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 1) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0) (0 0 0 0 0 0 0 0))) :whites-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :blacks-enpass (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0)) :whites-initial-pos 'bottom :white-king-pos (make-pos :row 2 :col 4) :black-king-pos (make-pos :row 0 :col 6) :white-king-moved t :black-king-moved t))
7,207
Common Lisp
.lisp
219
26.730594
75
0.570012
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
196f1dc29e8741696d7ceb3ed024b2827e60744618710c5d139fbe10336a80b9
26,769
[ -1 ]
26,770
ai.lisp
html_cl-chess/ai.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; ai.lisp ;;; Artificial Intelligence ;;; gamallo, February 11, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) ;; Pieces weight more or less depending on their proximity to the ;; center of the board. (defun choose-move (board color) (second (multiple-value-list (alpha-beta board 3 -1000000 1000000 color)))) (defun alpha-beta (board depth alpha beta color) (if (eq depth 0) (fev board) (let ((move) (children (children board color))) (dolist (a-move children) (when (king-valid board a-move color) (when (null move) (setf move a-move)) (let* ((new-board (execute-move (copy-board board) a-move)) (val (alpha-beta new-board (- depth 1) alpha beta (invert-color color)))) (if (eq color 'white) (progn (when (> val alpha) (setf alpha val) (setf move a-move)) (when (> alpha beta) (values alpha move))) (progn (when (< val beta) (setf beta val) (setf move a-move)) (when (> alpha beta) (values beta move))))))) (if (eq color 'white) (values alpha move) (values beta move))))) (defun fev (board) (let ((fev 0)) (dotimes (i 8) (dotimes (j 8) (let ((piece (aref (board-board board) i j))) (cond ((eq piece 'PB) (setf fev (+ fev 100 (if (eq (board-whites-initial-pos board) 'bottom) (aref +pawn-pos-v-weigh+ (- 7 i)) (aref +pawn-pos-v-weigh+ i)) (aref +pawn-pos-h-weigh+ j)))) ((eq piece 'PN) (setf fev (- fev 100 (if (eq (board-whites-initial-pos board) 'bottom) (aref +pawn-pos-v-weigh+ i) (aref +pawn-pos-v-weigh+ (- 7 i))) (aref +pawn-pos-h-weigh+ j)))) ((eq piece 'TB) (setf fev (+ fev 500 (aref +rook-pos-weigh+ i) (aref +rook-pos-weigh+ j)))) ((eq piece 'TN) (setf fev (- fev 500 (aref +rook-pos-weigh+ i) (aref +rook-pos-weigh+ j)))) ((eq piece 'AB) (setf fev (+ fev 300 (aref +knight-bishop-pos-weigh+ i) (aref +knight-bishop-pos-weigh+ j)))) ((eq piece 'AN) (setf fev (- fev 300 (aref +knight-bishop-pos-weigh+ i) (aref +knight-bishop-pos-weigh+ j)))) ((eq piece 'CB) (setf fev (+ fev 300 (aref +knight-bishop-pos-weigh+ i) (aref +knight-bishop-pos-weigh+ j)))) ((eq piece 'CN) (setf fev (- fev 300 (aref +knight-bishop-pos-weigh+ i) (aref +knight-bishop-pos-weigh+ j)))) ((eq piece 'RB) (setf fev (+ fev 1000))) ((eq piece 'RN) (setf fev (- fev 1000))) ((eq piece 'DB) (setf fev (+ fev 900))) ((eq piece 'DN) (setf fev (- fev 900))))))) fev))
3,556
Common Lisp
.lisp
113
25.893805
78
0.588733
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
436d159b066a8c9d53f9ca29b021d56bd088b894193f6d718d63959ca9b93ea8
26,770
[ -1 ]
26,771
pawn.lisp
html_cl-chess/moves/pawn.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; pawn.lisp ;;; Pawn movements ;;; gamallo, March 22, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) ;;; Places to which a pawn can move whitout atacking (defun free-pos-pawn (board pos) (let ((positions '())) ;; White pieces at the bottom (if (eq (board-whites-initial-pos board) 'bottom) ;; The pawn is white (if (eq (board-pos (board-board board) pos) 'PB) (progn ;; We are NOT at the upper border (when (not (= (pos-row pos) 0)) (add-pos positions (1- (pos-row pos)) (pos-col pos))) ;; We are in the initial pos: we can advance two ;; cells if way is clear (when (and (= (pos-row pos) 6) (eq (aref (board-board board) 5 (pos-col pos)) 'VV)) (add-pos positions 4 (pos-col pos)))) ;; The pawn is black (progn ;; We are NOT at the lower border (when (not (= (pos-row pos) 7)) (add-pos positions (1+ (pos-row pos)) (pos-col pos))) ;; We are int the initial pos: we can advance two ;; cells if the way is clear (when (and (= (pos-row pos) 1) (eq (aref (board-board board) 2 (pos-col pos)) 'VV)) (add-pos positions 3 (pos-col pos))))) ;; White pieces at the top ;; Pawn is white (if (eq (board-pos (board-board board) pos) 'PB) (progn ;; We are not at the lower border (when (not (= (pos-row pos) 7)) (add-pos positions (1+ (pos-row pos)) (pos-col pos))) ;; We are in the initial pos: we can advance two ;; cells if way is clear (when (and (= (pos-row pos) 1) (eq (aref (board-board board) 2 (pos-col pos)) 'VV)) (add-pos positions 3 (pos-col pos)))) ;; Pawn is black (progn ;; We are not at the upper border (when (not (= (pos-row pos) 0)) (add-pos positions (1- (pos-row pos)) (pos-col pos))) ;; We are in the initial pos: we can advance two ;; cells if way is clear (when (and (= (pos-row pos) 6) (eq (aref (board-board board) 5 (pos-col pos)) 'VV)) (add-pos positions 4 (pos-col pos)))))) positions)) ;;; Places an ataccking pawn can move to (defun attack-pos-pawn (board pos) (let ((positions '())) ;; White pieces at the bottom (if (eq (board-whites-initial-pos board) 'bottom) ;; Pawn is white (if (eq (board-pos (board-board board) pos) 'PB) ;; We are not at the upper border (when (not (= (pos-row pos) 0)) ;; We are not at the left border (when (not (= (pos-col pos) 0)) (add-pos positions (1- (pos-row pos)) (1- (pos-col pos)))) ;; We are not at the right border (when (not (= (pos-col pos) 7)) (add-pos positions (1- (pos-row pos)) (1+ (pos-col pos))))) ;; The pawn is black ;; We are not at the lower border (when (not (= (pos-row pos) 7)) ;; We are not at the left border (when (not (= (pos-col pos) 0)) (add-pos positions (1+ (pos-row pos)) (1- (pos-col pos)))) ;; We are not at the right border (when (not (= (pos-col pos) 7)) (add-pos positions (1+ (pos-row pos)) (1+ (pos-col pos)))))) ;; White pieces at the top ;; Pawn is white (if (eq (board-pos (board-board board) pos) 'PB) ;; We are not at the lower border (when (not (= (pos-row pos) 7)) ;; We are not at the left border (when (not (= (pos-col pos) 0)) (add-pos positions (1+ (pos-row pos)) (1- (pos-col pos)))) ;; We are not at the right border (when (not (= (pos-col pos) 7)) (add-pos positions (1+ (pos-row pos)) (1+ (pos-col pos))))) ;; Pawn is black ;; We are not at the upper border (when (not (= (pos-row pos) 0)) ;; We are not at the left border (when (not (= (pos-col pos) 0)) (add-pos positions (1- (pos-row pos)) (1- (pos-col pos)))) ;; We are not at the right border (when (not (= (pos-col pos) 7)) (add-pos positions (1- (pos-row pos)) (1+ (pos-col pos))))))) positions)) ;;; Places to which a pawn can move. (defun possible-free-pawn (board pos positions) (dolist (a-pos (free-pos-pawn board pos)) (when (eq (board-pos (board-board board) a-pos) 'VV) (setf positions (cons a-pos positions)))) positions) ;;; Places to which an attacking pawn can move. ;;; NOTE: We take into account enpases (defun possible-attack-pawn (board pos positions) (if (eq (board-pos (board-board board) pos) 'PB) ;; Pawn is white (dolist (a-pos (attack-pos-pawn board pos)) (cond ((color-occupied-p (board-blacks board) (pos-row a-pos) (pos-col a-pos)) ;; Dest pos is occupied by a black piece (setf positions (cons a-pos positions))) ((and (eq (pos-row a-pos) 2) (eq (board-whites-initial-pos board) 'bottom) (eq (aref (board-blacks-enpass board) (pos-col a-pos)) '1)) ;; White pieces are at the bottom, the pawn moves to the row ;; of enpass captures and, yes, there is a pawn that can be ;; enpass-captured (setf positions (cons a-pos positions))) ((and (eq (pos-row a-pos) 5) (eq (board-whites-initial-pos board) 'top) (eq (aref (board-blacks-enpass board) (pos-col a-pos)) '1)) ;; White pieces are at the top, the pawn moves to the row ;; of enpass captures and, yes, there is a pawn that can be ;; enpass-captured (setf positions (cons a-pos positions))))) ;; Pawn is black (dolist (a-pos (attack-pos-pawn board pos)) (cond ((color-occupied-p (board-whites board) (pos-row a-pos) (pos-col a-pos)) ;; Dest pos is occupied by a white piece (setf positions (cons a-pos positions))) ((and (eq (pos-row a-pos) 5) (eq (board-whites-initial-pos board) 'bottom) (eq (aref (board-whites-enpass board) (pos-col a-pos)) '1)) ;; White pieces are at the bottom, the pawn moves to the row ;; of enpass captures and, yes, there is a pawn that can be ;; enpass-captured (setf positions (cons a-pos positions))) ((and (eq (pos-row a-pos) 2) (eq (board-whites-initial-pos board) 'top) (eq (aref (board-whites-enpass board) (pos-col a-pos)) '1)) ;; White pieces are at the top, the pawn moves to the row ;; of enpass captures and, yes, there is a pawn that can be ;; enpass-captured (setf positions (cons a-pos positions)))))) positions) (defun possible-pawn (board pos) (incf *calls*) (let ((positions '())) (setf positions (possible-attack-pawn board pos positions)) (setf positions (possible-free-pawn board pos positions)) positions))
7,623
Common Lisp
.lisp
216
29.467593
75
0.597153
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
2b85875fade4b0ba4bd43221e4b0573721f97071d6ea2b78bc0469f8ec4955f7
26,771
[ -1 ]
26,772
knight.lisp
html_cl-chess/moves/knight.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; knight.lisp ;;; Movements of the knights ;;; gamallo, April 1, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) ;;; Places threatened by a knight (defun pos-knight (board pos) (let ((positions '())) ;; One o'clock (if (and (> (pos-row pos) 1) (< (pos-col pos) 7)) (setf positions (cons (make-pos :row (- (pos-row pos) 2) :col (1+ (pos-col pos))) positions))) ;; Two o'clock (if (and (> (pos-row pos) 0) (< (pos-col pos) 6)) (setf positions (cons (make-pos :row (1- (pos-row pos)) :col (+ (pos-col pos) 2)) positions))) ;; Four o'clock (if (and (< (pos-row pos) 7) (< (pos-col pos) 6)) (setf positions (cons (make-pos :row (1+ (pos-row pos)) :col (+ (pos-col pos) 2)) positions))) ;; Five o'clock (if (and (< (pos-row pos) 6) (< (pos-col pos) 7)) (setf positions (cons (make-pos :row (+ (pos-row pos) 2) :col (1+ (pos-col pos))) positions))) ;; Seven o'clock (if (and (< (pos-row pos) 6) (> (pos-col pos) 0)) (setf positions (cons (make-pos :row (+ (pos-row pos) 2) :col (1- (pos-col pos))) positions))) ;; Eight o'clock (if (and (< (pos-row pos) 7) (> (pos-col pos) 1)) (setf positions (cons (make-pos :row (1+ (pos-row pos)) :col (- (pos-col pos) 2)) positions))) ;; Ten o'clock (if (and (> (pos-row pos) 0) (> (pos-col pos) 1)) (setf positions (cons (make-pos :row (1- (pos-row pos)) :col (- (pos-col pos) 2)) positions))) ;; Eleven o'clock (if (and (> (pos-row pos) 1) (> (pos-col pos) 0)) (setf positions (cons (make-pos :row (- (pos-row pos) 2) :col (1- (pos-col pos))) positions))) positions)) (defun possible-knight (board pos) (let ((positions '())) (dolist (a-pos (pos-knight board pos)) (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'CB) ;; Knight is white (if (eq (aref (board-whites board) (pos-row a-pos) (pos-col a-pos)) '0) (setf positions (cons a-pos positions))) ;; Knight is black (if (eq (aref (board-blacks board) (pos-row a-pos) (pos-col a-pos)) '0) (setf positions (cons a-pos positions))))) positions))
3,106
Common Lisp
.lisp
99
26.616162
75
0.582498
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f84d02ba7f44480b90ae220b29f016959bc65b0de4ac1faf276ee8f360557745
26,772
[ -1 ]
26,773
bishop.lisp
html_cl-chess/moves/bishop.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; bishop.lisp ;;; Movements of the bishops ;;; gamallo, April 2, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) (defun possible-white-move (board pos) (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'VV)) (defun possible-white-capture (board pos) (eq (aref (board-blacks board) (pos-row pos) (pos-col pos)) '1)) (defun possible-black-move (board pos) (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'VV)) (defun possible-black-capture (board pos) (eq (aref (board-whites board) (pos-row pos) (pos-col pos)) '1)) (defun diagonal-move (pos f c) (make-pos :row (+ (pos-row pos) f) :col (+ (pos-col pos) c))) (defun possible-white-bishop (board pos) (let ((positions '())) ;; NE (dotimes (c (min (pos-row pos) (- 7 (pos-col pos)))) (let ((new-pos (diagonal-move pos (- (1+ c)) (1+ c)))) (cond ((possible-white-move board new-pos) (setf positions (cons new-pos positions))) ((possible-white-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; SE (dotimes (c (min (- 7 (pos-row pos)) (- 7 (pos-col pos)))) (let ((new-pos (diagonal-move pos (1+ c) (1+ c)))) (cond ((possible-white-move board new-pos) (setf positions (cons new-pos positions))) ((possible-white-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; SW (dotimes (c (min (- 7 (pos-row pos)) (pos-col pos))) (let ((new-pos (diagonal-move pos (1+ c) (- (1+ c))))) (cond ((possible-white-move board new-pos) (setf positions (cons new-pos positions))) ((possible-white-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; NW (dotimes (c (min (pos-row pos) (pos-col pos))) (let ((new-pos (diagonal-move pos (- (1+ c)) (- (1+ c))))) (cond ((possible-white-move board new-pos) (setf positions (cons new-pos positions))) ((possible-white-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) positions)) (defun possible-black-bishop (board pos) (let ((positions '())) ;; NE (dotimes (c (min (pos-row pos) (- 7 (pos-col pos)))) (let ((new-pos (diagonal-move pos (- (1+ c)) (1+ c)))) (cond ((possible-black-move board new-pos) (setf positions (cons new-pos positions))) ((possible-black-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; SE (dotimes (c (min (- 7 (pos-row pos)) (- 7 (pos-col pos)))) (let ((new-pos (diagonal-move pos (1+ c) (1+ c)))) (cond ((possible-black-move board new-pos) (setf positions (cons new-pos positions))) ((possible-black-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; SW (dotimes (c (min (- 7 (pos-row pos)) (pos-col pos))) (let ((new-pos (diagonal-move pos (1+ c) (- (1+ c))))) (cond ((possible-black-move board new-pos) (setf positions (cons new-pos positions))) ((possible-black-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) ;; NW (dotimes (c (min (pos-row pos) (pos-col pos))) (let ((new-pos (diagonal-move pos (- (1+ c)) (- (1+ c))))) (cond ((possible-black-move board new-pos) (setf positions (cons new-pos positions))) ((possible-black-capture board new-pos) (setf positions (cons new-pos positions)) (return nil)) (t (return nil))))) positions)) (defun possible-bishop (board pos) (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'AB) ;; Bishop is white (possible-white-bishop board pos) ;; Bishop is black (possible-black-bishop board pos)))
4,966
Common Lisp
.lisp
141
29.560284
75
0.600835
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
8d173c8be74c7ed875c4d6151ea2e4ee1d8303b3e9be4280b0d1837c3351070d
26,773
[ -1 ]
26,774
queen.lisp
html_cl-chess/moves/queen.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; queen.lisp ;;; Movements of the queens ;;; gamallo, July 9, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) (defun possible-queen (board pos) (let* ((rook-functions '((white possible-white-rook) (black possible-back-rook))) (bishop-functions '((white possible-white-bishop) (black possible-black-bishop))) (color (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'DB) 'white 'black)) (rook-function (second (assoc color rook-functions))) (bishop-function (second (assoc color bishop-functions))) (positions '())) (setf positions (funcall rook-function board pos)) (setf positions (append positions (funcall bishop-function board pos)))))
1,525
Common Lisp
.lisp
36
39.083333
75
0.691892
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
26770fd524ed3ccc7b82f6178878d735588d8727069cdde35a7c3eebb025389b
26,774
[ -1 ]
26,775
rook.lisp
html_cl-chess/moves/rook.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; rook.lisp ;;; Movements of the rooks ;;; gamallo, April 1, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Foobar. ;; Foobar is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Foobar is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Foobar. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) (defun possible-white-rook (board pos) (let ((positions '())) ;; Twelve o'clock (dotimes (row (pos-row pos)) (cond ((eq (aref (board-board board) (- (pos-row pos) (1+ row)) (pos-col pos)) 'VV) (setf positions (cons (make-pos :row (- (pos-row pos) (1+ row)) :col (pos-col pos)) positions))) ((eq (aref (board-blacks board) (- (pos-row pos) (1+ row)) (pos-col pos)) '1) (setf positions (cons (make-pos :row (- (pos-row pos) (1+ row)) :col (pos-col pos)) positions)) (return nil)) (t (return nil)))) ;; Three o'clock (dotimes (col (- 7 (pos-col pos))) (cond ((eq (aref (board-board board) (pos-row pos) (+ (pos-col pos) col 1)) 'VV) (setf positions (cons (make-pos :row (pos-row pos) :col (+ (pos-col pos) col 1)) positions))) ((eq (aref (board-blacks board) (pos-row pos) (+ (pos-col pos) col 1)) '1) (setf positions (cons (make-pos :row (pos-row pos) :col (+ (pos-col pos) col 1)) positions)) (return nil)) (t (return nil)))) ;; Six o'clock (dotimes (row (- 7 (pos-row pos))) (cond ((eq (aref (board-board board) (+ (pos-row pos) row 1) (pos-col pos)) 'VV) (setf positions (cons (make-pos :row (+ (pos-row pos) row 1) :col (pos-col pos)) positions))) ((eq (aref (board-blacks board) (+ (pos-row pos) row 1) (pos-col pos)) '1) (setf positions (cons (make-pos :row (+ (pos-row pos) row 1) :col (pos-col pos)) positions)) (return nil)) (t (return nil)))) ;; Nine o'clock (dotimes (col (pos-col pos)) (cond ((eq (aref (board-board board) (pos-row pos) (- (pos-col pos) (1+ col))) 'VV) (setf positions (cons (make-pos :row (pos-row pos) :col (- (pos-col pos) (1+ col))) positions))) ((eq (aref (board-blacks board) (pos-row pos) (- (pos-col pos) (1+ col))) '1) (setf positions (cons (make-pos :row (pos-row pos) :col (- (pos-col pos) (1+ col))) positions)) (return nil)) (t (return nil)))) positions)) (defun possible-back-rook (board pos) (let ((positions '())) ;; Twelve o'clock (dotimes (row (pos-row pos)) (cond ((eq (aref (board-board board) (- (pos-row pos) (1+ row)) (pos-col pos)) 'VV) (setf positions (cons (make-pos :row (- (pos-row pos) (1+ row)) :col (pos-col pos)) positions))) ((eq (aref (board-whites board) (- (pos-row pos) (1+ row)) (pos-col pos)) '1) (setf positions (cons (make-pos :row (- (pos-row pos) (1+ row)) :col (pos-col pos)) positions)) (return nil)) (t (return nil)))) ;; Three o'clock (dotimes (col (- 7 (pos-col pos))) (cond ((eq (aref (board-board board) (pos-row pos) (+ (pos-col pos) col 1)) 'VV) (setf positions (cons (make-pos :row (pos-row pos) :col (+ (pos-col pos) col 1)) positions))) ((eq (aref (board-whites board) (pos-row pos) (+ (pos-col pos) col 1)) '1) (setf positions (cons (make-pos :row (pos-row pos) :col (+ (pos-col pos) col 1)) positions)) (return nil)) (t (return nil)))) ;; Six o'clock (dotimes (row (- 7 (pos-row pos))) (cond ((eq (aref (board-board board) (+ (pos-row pos) row 1) (pos-col pos)) 'VV) (setf positions (cons (make-pos :row (+ (pos-row pos) row 1) :col (pos-col pos)) positions))) ((eq (aref (board-whites board) (+ (pos-row pos) row 1) (pos-col pos)) '1) (setf positions (cons (make-pos :row (+ (pos-row pos) row 1) :col (pos-col pos)) positions)) (return nil)) (t (return nil)))) ;; Nine o'clock (dotimes (col (pos-col pos)) (cond ((eq (aref (board-board board) (pos-row pos) (- (pos-col pos) (1+ col))) 'VV) (setf positions (cons (make-pos :row (pos-row pos) :col (- (pos-col pos) (1+ col))) positions))) ((eq (aref (board-whites board) (pos-row pos) (- (pos-col pos) (1+ col))) '1) (setf positions (cons (make-pos :row (pos-row pos) :col (- (pos-col pos) (1+ col))) positions)) (return nil)) (t (return nil)))) positions)) (defun possible-rook (board pos) (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'TB) ;; The rook is white (possible-white-rook board pos) ;; The rook is black (possible-back-rook board pos)))
5,757
Common Lisp
.lisp
214
20.892523
75
0.53899
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
501518dd7f92d7ce7aa26d114532a7f6ef2ed0f4db3cc630ae49bfd118a3bbdc
26,775
[ -1 ]
26,776
king.lisp
html_cl-chess/moves/king.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; king.lisp ;;; Movements of kings ;;; gamallo, July 25, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) (defun maybe-pos-king (pos) (let ((row (pos-row pos)) (col (pos-col pos)) (maybe-positions '())) (when (> row 0) ; Twelve o'clock (add-pos maybe-positions (- row 1) col)) (when (and (> row 0) (< col 7)) ; Half-past one (add-pos maybe-positions (- row 1) (1+ col))) (when (< col 7) ; Three o'clock (add-pos maybe-positions row (1+ col))) (when (and (< row 7) (< col 7)) ; Half-past four (add-pos maybe-positions (1+ row) (1+ col))) (when (< row 7) ; Six o'clock (add-pos maybe-positions (1+ row) col)) (when (and (< row 7) (> col 0)) ; Half-past seven (add-pos maybe-positions (1+ row) (- col 1))) (when (> col 0) ; nine o'clock (add-pos maybe-positions row (- col 1))) (when (and (> row 0) (> col 0)) ; Half-past ten (add-pos maybe-positions (- row 1) (- col 1))) maybe-positions)) (defun empty-pos (board pos) (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'VV)) (defun occupied-pos (board pos funcion) (eq (aref (funcall funcion board) (pos-row pos) (pos-col pos)) '1)) (defun possible-king-without-castling (board pos) (let ((opponent-function (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'RB) #'board-blacks #'board-whites)) (color (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'RB) 'white 'black)) (maybe-positions (maybe-pos-king pos)) (positions '())) (dolist (p maybe-positions) (if (or (empty-pos board p) (occupied-pos board p opponent-function)) (setf positions (cons p positions)))) positions)) (defun possible-king (board pos) (let ((color (if (eq (aref (board-board board) (pos-row pos) (pos-col pos)) 'RB) 'white 'black)) (positions (possible-king-without-castling board pos))) (setf positions (append positions (short-castle-if-possible board positions color))) (setf positions (append positions (long-castle-if-possible board positions color))) positions)) (defun short-castle-if-possible (board a-list color) (cond ((and (eq color 'white) (eq (board-whites-initial-pos board) 'bottom)) (when (and (not (board-white-king-moved board)) (empty-pos board (make-pos :row 7 :col 5)) (empty-pos board (make-pos :row 7 :col 6)) (eq (board-pos (board-board board) (make-pos :row 7 :col 7)) 'TB) (not (king-threatened board color))) (add-pos a-list 7 6))) ((and (eq color 'white) (eq (board-whites-initial-pos board) 'top)) (when (and (not (board-white-king-moved board)) (empty-pos board (make-pos :row 0 :col 2)) (empty-pos board (make-pos :row 0 :col 1)) (eq (board-pos (board-board board) (make-pos :row 0 :col 0)) 'TB) (not (king-threatened board color))) (add-pos a-list 0 1))) ((and (eq color 'black) (eq (board-whites-initial-pos board) 'bottom)) (when (and (not (board-black-king-moved board)) (empty-pos board (make-pos :row 0 :col 5)) (empty-pos board (make-pos :row 0 :col 6)) (eq (board-pos (board-board board) (make-pos :row 0 :col 7)) 'TN) (not (king-threatened board color))) (add-pos a-list 0 6))) ((and (eq color 'black) (eq (board-whites-initial-pos board) 'top)) (when (and (not (board-black-king-moved board)) (empty-pos board (make-pos :row 7 :col 2)) (empty-pos board (make-pos :row 7 :col 1)) (eq (board-pos (board-board board) (make-pos :row 7 :col 0)) 'TN) (not (king-threatened board color))) (add-pos a-list 7 1))))) (defun long-castle-if-possible (board a-list color) (cond ((and (eq color 'white) (eq (board-whites-initial-pos board) 'bottom)) (when (and (not (board-white-king-moved board)) (empty-pos board (make-pos :row 7 :col 2)) (empty-pos board (make-pos :row 7 :col 3)) (eq (board-pos (board-board board) (make-pos :row 7 :col 0)) 'TB) (not (king-threatened board color))) (add-pos a-list 7 2))) ((and (eq color 'white) (eq (board-whites-initial-pos board) 'top)) (when (and (not (board-white-king-moved board)) (empty-pos board (make-pos :row 0 :col 5)) (empty-pos board (make-pos :row 0 :col 4)) (eq (board-pos (board-board board) (make-pos :row 0 :col 7)) 'TB) (not (king-threatened board color))) (add-pos a-list 0 5))) ((and (eq color 'black) (eq (board-whites-initial-pos board) 'bottom)) (when (and (not (board-black-king-moved board)) (empty-pos board (make-pos :row 0 :col 2)) (empty-pos board (make-pos :row 0 :col 3)) (eq (board-pos (board-board board) (make-pos :row 0 :col 0)) 'TN) (not (king-threatened board color))) (add-pos a-list 0 2))) ((and (eq color 'black) (eq (board-whites-initial-pos board) 'top)) (when (and (not (board-black-king-moved board)) (empty-pos board (make-pos :row 7 :col 5)) (empty-pos board (make-pos :row 7 :col 4)) (eq (board-pos (board-board board) (make-pos :row 7 :col 7)) 'TN) (not (king-threatened board color))) (add-pos a-list 7 5)))))
6,382
Common Lisp
.lisp
188
28.111702
88
0.597339
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
242eef2945774803d22d990a184a276bff36221a1fd90ba3bee6202623162f06
26,776
[ -1 ]
26,777
moves.lisp
html_cl-chess/moves/moves.lisp
;;; -*- encoding: utf-8 -*- ;;; ;;; moves.lisp ;;; Movements of the pieces ;;; gamallo, March 8, 2007 ;;; ;; Copyright 2007, 2008, 2009 Manuel Felipe Gamallo Rivero. ;; This file is part of Miguedrez. ;; Miguedrez is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; Miguedrez is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with Miguedrez. If not, see <http://www.gnu.org/licenses/>. (in-package :miguedrez) ;;; This function executes a move on a board ;;; It DOES NOT CHECK that the dest pos is void, that is job for ;;; check-move. (defun execute-move (board move) (execute-move-enpass board move) (execute-move-board board move) (if (eq (board-pos (board-whites board) (move-from move)) '1) (progn (execute-move-white board move) (when (equal-pos (board-white-king-pos board) (move-from move)) (setf (board-white-king-pos board) (move-to move)) (when (not (board-white-king-moved board)) (setf (board-white-king-moved board) t) ;; We check if it's a castling and, in that case, ;; we move the corresponding rook (if (eq (board-whites-initial-pos board) 'bottom) (cond ((equal-pos (move-to move) (make-pos :row 7 :col 6)) (execute-move board (make-move :from (make-pos :row 7 :col 7) :to (make-pos :row 7 :col 5)))) ((equal-pos (move-to move) (make-pos :row 7 :col 2)) (execute-move board (make-move :from (make-pos :row 7 :col 0) :to (make-pos :row 7 :col 3))))) (cond ((equal-pos (move-to move) (make-pos :row 0 :col 5)) (execute-move board (make-move :from (make-pos :row 0 :col 7) :to (make-pos :row 0 :col 4)))) ((equal-pos (move-to move) (make-pos :row 0 :col 1)) (execute-move board (make-move :from (make-pos :row 0 :col 0) :to (make-pos :row 0 :col 2)))))))) (queen-if-promotion board move)) (progn (execute-move-black board move) (when (equal-pos (board-black-king-pos board) (move-from move)) (setf (board-black-king-pos board) (move-to move)) (when (not (board-black-king-moved board)) (setf (board-black-king-moved board) t) ;; We check if it's a castling and, in that case, ;; move the corresponding rook (if (eq (board-whites-initial-pos board) 'top) (cond ((equal-pos (move-to move) (make-pos :row 7 :col 5)) (execute-move board (make-move :from (make-pos :row 7 :col 7) :to (make-pos :row 7 :col 4)))) ((equal-pos (move-to move) (make-pos :row 7 :col 1)) (execute-move board (make-move :from (make-pos :row 7 :col 0) :to (make-pos :row 7 :col 2))))) (cond ((equal-pos (move-to move) (make-pos :row 0 :col 6)) (execute-move board (make-move :from (make-pos :row 0 :col 7) :to (make-pos :row 0 :col 5)))) ((equal-pos (move-to move) (make-pos :row 0 :col 2)) (execute-move board (make-move :from (make-pos :row 0 :col 0) :to (make-pos :row 0 :col 1)))))))) (queen-if-promotion board move))) board) ;;; Function to move a piece on the main board (defun execute-move-board (board move) (setf (board-pos (board-board board) (move-to move)) (board-pos (board-board board) (move-from move))) (setf (board-pos (board-board board) (move-from move)) 'VV)) ;;; Function to move a piece in the white pieces board (defun execute-move-white (board move) (setf (board-pos (board-whites board) (move-to move)) '1) (setf (board-pos (board-whites board) (move-from move)) '0) (when (eq (board-pos (board-blacks board) (move-to move)) '1) (setf (board-pos (board-blacks board) (move-to move)) '0))) ;;; Function to move a piece in the black pieces board (defun execute-move-black (board move) (setf (board-pos (board-blacks board) (move-to move)) '1) (setf (board-pos (board-blacks board) (move-from move)) '0) (when (eq (board-pos (board-whites board) (move-to move)) '1) (setf (board-pos (board-whites board) (move-to move)) '0))) (defun queen-if-promotion (board move) (cond ((and (or (eq (pos-row (move-to move)) '7) (eq (pos-row (move-to move)) '0)) (eq (board-pos (board-board board) (move-to move)) 'PB)) (setf (board-pos (board-board board) (move-to move)) 'DB)) ((and (or (eq (pos-row (move-to move)) '7) (eq (pos-row (move-to move)) '0)) (eq (board-pos (board-board board) (move-to move)) 'PN)) (setf (board-pos (board-board board) (move-to move)) 'DN)))) ;;; Function that takes care of the enpass arrays when moving (defun execute-move-enpass (board move) (if (eq (board-whites-initial-pos board) 'bottom) ;; White pieces at the bottom (let ((a-board (board-board board)) (from (move-from move)) (to (move-to move))) (cond ((and (eq (board-pos a-board from) 'PN) (eq (pos-row to) 5) (eq (aref (board-whites-enpass board) (pos-col to)) '1)) ;; We are capturing a white pawn in the enpass position (setf (aref a-board 4 (pos-col to)) 'VV) (setf (aref (board-whites board) 4 (pos-col to)) '0)) ((and (eq (board-pos a-board from) 'PB) (eq (pos-row to) 2) (eq (aref (board-blacks-enpass board) (pos-col to)) '1)) ;; We are capturing a black pawn in the enpass position (setf (aref a-board 3 (pos-col to)) 'VV) (setf (aref (board-blacks board) 3 (pos-col to)) '0))) (setf (board-whites-enpass board) (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0))) (setf (board-blacks-enpass board) (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0))) (cond ((eq (board-pos a-board from) 'PB) ;; The piece we are moving is a white pawn (if (and (eq (pos-row from) '6) (eq (pos-row to) '4)) ;; The pawn is in its initial position and we want to ;; advance two cells (setf (aref (board-whites-enpass board) (pos-col to)) '1))) ((eq (board-pos a-board from) 'PN) ;; The piece we are moving is a black pawn (if (and (eq (pos-row from) '1) (eq (pos-row to) '3)) ;; The pawn is in its initial position and we want to ;; advance two cells (setf (aref (board-blacks-enpass board) (pos-col to)) '1))))) ;; White pieces at the top (let ((a-board (board-board board)) (from (move-from move)) (to (move-to move))) (cond ((and (eq (board-pos a-board from) 'PN) (eq (pos-row to) 2) (eq (aref (board-whites-enpass board) (pos-col to)) '1)) ;; We are capturing a white pawn in the enpass position (setf (aref a-board 3 (pos-col to)) 'VV) (setf (aref (board-whites board) 3 (pos-col to)) '0)) ((and (eq (board-pos a-board from) 'PB) (eq (pos-row to) 5) (eq (aref (board-blacks-enpass board) (pos-col to)) '1)) ;; We are capturing a black pawn in the enpass position (setf (aref a-board 4 (pos-col to)) 'VV) (setf (aref (board-blacks board) 4 (pos-col to)) '0))) (setf (board-whites-enpass board) (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0))) (setf (board-blacks-enpass board) (make-array 8 :initial-contents '(0 0 0 0 0 0 0 0))) (cond ((eq (board-pos a-board from) 'PB) ;; We are about to move a white pawn (if (and (eq (pos-row from) '1) (eq (pos-row to) '3)) ;; The pawn is in its initial position, and we want to ;; advance two cells (setf (aref (board-whites-enpass board) (pos-col to)) '1))) ((eq (aref a-board (pos-row from) (pos-col from)) 'PN) ;; We are about to move a black pawn (if (and (eq (pos-row from) '6) (eq (pos-row to) '4)) ;; The pawn is in its initial position and we want to ;; advance two cells (setf (aref (board-blacks-enpass board) (pos-col to)) '1))))))) (defun children-piece (board pos &key castle) (let ((children '()) (piece (board-pos (board-board board) pos))) (cond ((or (eq piece 'PB) (eq piece 'PN)) (setf children (possible-pawn board pos))) ((or (eq piece 'CB) (eq piece 'CN)) (setf children (possible-knight board pos))) ((or (eq piece 'TB) (eq piece 'TN)) (setf children (possible-rook board pos))) ((or (eq piece 'AB) (eq piece 'AN)) (setf children (possible-bishop board pos))) ((or (eq piece 'DB) (eq piece 'DN)) (setf children (possible-queen board pos))) ((or (eq piece 'RB) (eq piece 'RN)) (setf children (if (eq castle 'without-castling) (possible-king-without-castling board pos) (possible-king board pos))))) (mapcar #'(lambda (to) (make-move :from pos :to to)) children))) (defun children (board color &key castle) (let ((board-color (if (whitep color) (board-whites board) (board-blacks board))) (children '())) (dotimes (row 8 children) (dotimes (col 8) (when (color-occupied-p board-color row col) (let ((current-pos (make-pos :row row :col col))) (setf children (nconc children (children-piece board current-pos :castle castle))))))))) ;;; Is this position threatened by this color? (defun pos-threatened (a-board a-pos a-color) (member a-pos (mapcar #'move-to (children a-board (invert-color a-color) :castle 'without-castling)) :test #'equal-pos)) (defun valid (board move color) (let ((piece (if (eq color 'white) 'RB 'RN))) (and (member move (children board color) :test #'equal-moves) (king-valid board move color)))) (defun king-valid (board move color) (let ((new-board (copy-board board))) (execute-move new-board move) (null (king-threatened new-board color)))) (defun king-threatened (board color) (pos-threatened board (if (eq color 'white) (board-white-king-pos board) (board-black-king-pos board)) color)) (defun checkmatep (a-board a-player) (and ;; The king is threatened (king-threatened a-board (player-color a-player)) ;; For all of the children for the king, he stays threatened (let ((a-pos (if (eq (player-color a-player) 'white) (board-white-king-pos a-board) (board-black-king-pos a-board))) (some-move-allowed)) (dolist (a-move (children a-board (player-color a-player) :castle 'without-castling) (not some-move-allowed)) ;; If some move is possible, we set some-move-allowed to T (let* ((new-board (execute-move (copy-board a-board) a-move)) (new-king-pos (if (eq (player-color a-player) 'white) (board-white-king-pos new-board) (board-black-king-pos new-board)))) (when (not (pos-threatened new-board new-king-pos (player-color a-player))) (setf some-move-allowed t)))))))
11,295
Common Lisp
.lisp
303
32.09901
76
0.623936
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
7b0f5013429f6651107d397a58e9a8235355f0d9559bf5e1a6ecd5aa18268fcd
26,777
[ -1 ]
26,778
cl-chess.asd
html_cl-chess/cl-chess.asd
(defpackage #:cl-chess-asd (:use :cl :asdf)) (in-package :cl-chess-asd) (defsystem cl-chess :name "miguedrez" :version "0.9.5" :maintainer "Olexiy Zamkoviy" :author "Manuel Felipe Gamallo Rivero" :licence "GPL v3" :description "Chess library" :components ( (:file "miguedrez") (:file "data" :depends-on ("miguedrez")) (:file "io" :depends-on ("miguedrez")) (:file "ai" :depends-on ("miguedrez")) (:module "moves" :components ( (:file "moves") (:file "bishop" :depends-on ("moves")) (:file "king" :depends-on ("moves")) (:file "knight" :depends-on ("moves")) (:file "pawn" :depends-on ("moves")) (:file "queen" :depends-on ("moves")) (:file "rook")) :depends-on ("miguedrez"))))
1,015
Common Lisp
.asd
25
26.12
63
0.450405
html/cl-chess
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
70c67cc239565da83adcd98623465a5ca74ff4f8f8a34d9c882f5fee1b268cb0
26,778
[ -1 ]
26,807
repl-history.json
wegfawefgawefg_clisp-web-dsl/.vscode/alive/repl-history.json
[{"pkgName":"cl-user","text":"(+ (hi) (hi))"},{"pkgName":"cl-user","text":"(+ hi hi hi)"},{"pkgName":"cl-user","text":"(hi)"},{"pkgName":"cl-user","text":"hi"},{"pkgName":"cl-user","text":"(defun hi () 4)"},{"pkgName":"cl-user","text":"(defun (potato) 4)"},{"pkgName":"cl-user","text":"(defun potato 4)"}]
305
Common Lisp
.l
1
305
305
0.540984
wegfawefgawefg/clisp-web-dsl
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
874f6613700244686b32572ddd54e7e780c4edf986b8ad7b0c6bcec0908c232f
26,807
[ -1 ]
26,822
package.lisp
hai-nc_htm-cl/src/package.lisp
(in-package #:common-lisp-user) (defpackage htm-helper (:use #:common-lisp) (:export #:next-after-float32)) (defpackage htm-scalar-encoder (:use #:common-lisp) (:export #:category-input-p #:clip-input-p #:encode #:minimum-input #:maximum-input #:num-consecutive-1-bits #:periodic-input-p #:radius #:resolution #:scalar-encoder #:size #:sparsity))
481
Common Lisp
.lisp
18
18.277778
35
0.545852
hai-nc/htm-cl
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
25c62f83a70abdafff6af6f807a43abd307fa79c729f44e363fc39716ab9a2ec
26,822
[ -1 ]
26,823
scalar-encoder.lisp
hai-nc_htm-cl/src/scalar-encoder.lisp
;;; This is based on the HTM Community Edition of NuPIC <https://github.com/htm-community/htm.core/encoders/ScalarEncoder.cpp> commit d9ee57970f2a9dd96d9149fd74308261a216e525 date 17 Jun 2019 at 20:37:52. ;;; ;;; Compared to Scalar-Encoder.cpp, this library outputs have some differences: ;;; - output format: this library outputs a list of at most 2 dotted pairs of the form (start index . end index), each pair represents the start and end indices of a continuous sequence of the output array where all the bit values each has a value of 1. The remaining array elements not in any of the returned (start index . end-index) range have bit value 0. If the output is periodic and the slice \"wrap around\" to the beginning of the output array, then at most 2 pairs of (start index . end index) is provided (please refer to the `encode' method below). ;;; - due to rounding error, some outputs from this library are off-1-index compared to those expected from Scalar-Encoder.cpp, for instance this library encodes 10.5 into the 1-bit slice of [0,2] instead of [1,3] as in Scalar-Encoder.cpp, or 14.5 into [4,6] instead of [5,7]. (in-package #:htm-scalar-encoder) (defclass scalar-encoder () (;; slots: ;; The number of consecutive bits of value 1's in the encoded output SDR. (num-consecutive-1-bits :initarg :num-consecutive-1-bits :initform 0 :accessor num-consecutive-1-bits :type 'integer) ;; If true then this encoder will only encode unsigned integers, and all inputs shall have a unique/non-overlapping representations. (category-input-p :initarg :category-input-p :initform nil :accessor category-input-p) ;; Members 'minimum-input' and 'maximum-input' defines the range of the inputs. These endpoints are inclusive. (minimum-input :initarg :minimum-input :initform 0.0 :accessor minimum-input :type 'single-float) (maximum-input :initarg :maximum-input :initform 0.0 :accessor maximum-input :type 'single-float) ;; If true, inputs outside the range [minimum-input, maximum-input] will be clipped into the range [minimum-input, maximum-input] (which includes minimum-input, maximum-input endpoints). If false, inputs outside the range will raise an error. (clip-input-p :initarg :clip-input-p :initform nil :accessor clip-input-p) ;; If true, then the minimum-input & maximum-input inputs are the same and the first and last bits of the output SDR are adjacent. The contiguous block of 1's wraps around the end back to the beginning. (eg. hours of day - last hour of one day will proceed to beginning hour of day of the next day). ;; ;; If false, then minimum-input & maximum-input inputs are the endpoints of the input range, are not adjacent, and activity does not wrap around. (periodic-input-p :initarg :periodic-input-p :initform nil :accessor periodic-input-p) ;; Minimum-Input difference (inclusive) between two inputs to have different representations for them, including when the difference equals this amount. (resolution :initarg :resolution :initform 0.0 :accessor resolution :type 'single-float) ;; The total number of bits in the encoded output SDR. (size :initarg :size :initform 0 :accessor size :type 'integer) ;; An alternative way to specify the member 'num-consecutive-1-bits'. Sparsity requires that the size also needs specifying. Specify only one of num-consecutive-1-bits or sparsity. (sparsity :initarg :sparsity :initform 0.0 :accessor sparsity :type 'single-float) ;; Two inputs separated by more than the radius have non-overlapping representations. Two inputs separated by less than the radius will in general overlap in at least some of their bits. You can think of this as the radius of the input. (radius :initarg :radius :initform 0.0 :accessor radius :type 'single-float)) (:documentation "Encodes a floating point number into an array of bits. The output is 0's except for a contiguous block of 1's. The location of this contiguous block varies continuously with the input value.")) (defmethod assert-exactly-one-non-zero-slot ((encoder scalar-encoder) slot-symbol-list) (loop with attributes = slot-symbol-list with non-zero-attributes = nil with attribute-value = nil for attribute in attributes do (progn (setf attribute-value (slot-value encoder attribute)) (when (and attribute-value (numberp attribute-value) (null (zerop attribute-value))) (push attribute non-zero-attributes))) finally (progn (unless (equalp (length non-zero-attributes) 1) (error "Expecting *exactly one* of these slot to be non-zero: ~a~%, got ~a such slots: ~a" attributes (length non-zero-attributes) non-zero-attributes)) non-zero-attributes))) (defmethod initialize-instance :after ((encoder scalar-encoder) &key) ;; These four (4) mutually-exclusive members define the total ;; number of bits in the output, and only one of them should be ;; non-zero when constructing the encoder: (assert-exactly-one-non-zero-slot encoder '(size radius category-input-p resolution)) (assert-exactly-one-non-zero-slot encoder '(num-consecutive-1-bits sparsity)) (with-slots (resolution minimum-input maximum-input size radius sparsity category-input-p clip-input-p periodic-input-p num-consecutive-1-bits) encoder ;; validate parameters (assert (< minimum-input maximum-input)) (when category-input-p (when clip-input-p (error "Incompatible arguments: category-input-p & clip-input-p!")) (when periodic-input-p (error "Incompatible arguments: category-input-p & periodic-input-p!")) (unless (>= minimum-input 0.0) (error "Minimum-Input input value of category-input-p encoder must be non-negative!")) (unless (> maximum-input 0.0) (warn "Maximum-Input input value of category-input-p encoder must be a positive!"))) (when category-input-p (setf radius 1.0)) (when (> sparsity 0.0) (assert (<= 0.0 sparsity 1.0)) (unless (> size 0) (error "Argument 'size' (value: ~a) should be > 0!" size)) (round (* size sparsity))) ;; Determine resolution & size: (let ((extent-width (- (if periodic-input-p maximum-input ;; else increase the max by the smallest possible amount: (htm-helper:next-after-float32 (coerce maximum-input 'single-float))) minimum-input)) needed-bands) (if (> size 0) ;; Distribute the active bits along the domain [minimum-input, maximum-input], including the endpoints. The resolution is the width of each band between the points. (setf resolution (/ extent-width (if periodic-input-p size (1- (- size (1- num-consecutive-1-bits)) ; number of buckets )))) (progn (when (> radius 0.0) (setf resolution (/ radius num-consecutive-1-bits))) (setf needed-bands (ceiling (/ extent-width resolution)) size (if periodic-input-p needed-bands (+ needed-bands (1- num-consecutive-1-bits))))))) ;; Determine radius. Always calculate this even if it was given, ;; to correct for rounding error: (setf radius (* num-consecutive-1-bits resolution)) ;; Determine sparsity. Always calculate this even if it was ;; given, to correct for rounding error. (setf sparsity (/ num-consecutive-1-bits size)) (assert (> size 0)) (assert (> num-consecutive-1-bits 0)) (assert (< num-consecutive-1-bits size)) ;; (call-next-method :dimensions size) )) (defmethod encode ((encoder scalar-encoder) input) "Returns a list of at most 2 dotted pairs of the form (start index . end index), each pair represents the start and end indices of a continuous sequence of the output array where all the bit values each has a value of 1. The remaining array elements not in any of the returned (start index . end-index) range have bit value 0. If the output is periodic and the slice \"wrap around\" to the beginning of the output array, then at most 2 pairs of (start index . end index) is provided. INPUT: a floating-point number." (with-slots (size clip-input-p periodic-input-p category-input-p minimum-input maximum-input resolution num-consecutive-1-bits) encoder (assert (and input (numberp input))) (unless (<= minimum-input input maximum-input) (if clip-input-p (if periodic-input-p (setf input (+ minimum-input (mod input (- maximum-input minimum-input)))) (setf input (max input minimum-input) input (min input maximum-input))) (error "Input (~a) is out of bound [~a, ~a]" input minimum-input maximum-input))) (when category-input-p (assert (= input (ffloor input)))) (let* ((max-index (1- size)) ;; `mod' is used below for correction for edge case of rounding at 0.5 will become 1.0, which makes start-index 1 index higher that max-index (eg. case of minimum-input 10.0, maximum-input 20.0, resolution 1, periodic-input-p t, and input is 19.5) (start-index (mod (round (/ (- input minimum-input) resolution)) size)) (end-index (+ start-index (1- num-consecutive-1-bits)))) (assert (<= 0 start-index max-index)) (if (<= end-index max-index) (list (cons start-index end-index)) (if periodic-input-p ;; split the slice into 2: (start-index . max-index) and (0 . length-of-max-index-to-end-index-minus-1): (list (cons start-index max-index) (cons 0 (- end-index size))) ;; no wrap-around: shift (start-index . end-index) slice backwards until end-index matches with max-index: (list (cons (- size num-consecutive-1-bits) max-index)))))))
10,585
Common Lisp
.lisp
183
48.344262
560
0.657986
hai-nc/htm-cl
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
be67cf6f4483283eec240bd9d46bb50253d0637b73a3600e255a67fa83a87d32
26,823
[ -1 ]
26,824
helper.lisp
hai-nc_htm-cl/src/helper.lisp
;;;; Utility functions for testing. (in-package #:htm-helper) (defun next-after-float32 (a-float) "Return the smallest increment of a float (32-bit) number. This emulates C++ std::nextafter() function. This requires the Common Lisp 'ieee-floats' library." ;; references: moonshadow 2008 https://stackoverflow.com/questions/155378/how-to-alter-a-float-by-its-smallest-increment-or-close-to-it#155397 (ieee-floats:decode-float32 (1+ (ieee-floats:encode-float32 a-float))) ;; ;; optionally: check that we haven't flipped the sign or generated ;; ;; an overflow/underflow result by examining the sign and exponent ;; ;; bits!? )
646
Common Lisp
.lisp
13
47.076923
144
0.745628
hai-nc/htm-cl
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
3e62971a4a11bf4064e49194d8c284c2c3eb616e44d51cadb34004825866c368
26,824
[ -1 ]
26,825
scalar-encoder.lisp
hai-nc_htm-cl/t/scalar-encoder.lisp
;;;; Unit tests on scalar encoder ;;; Based on the community's htm.core/src/htm/tests/unit/encoders/ScalarEncoderTest.cpp viewed 2019-08-28. (in-package #:htm-scalar-encoder-test) ;; (defstruct test-data ;; ;; Test data ;; (input 0.0 :type 'single-float) ;; (expected-output nil) ; *sparse* indices of active bits. ;; ) (rove:deftest test-clipping-inputs (let ((encoder (make-instance 'htm-scalar-encoder:scalar-encoder :size 10 :num-consecutive-1-bits 2 :minimum-input 10 :maximum-input 20))) (rove:testing "With no input clipping:" (setf (htm-scalar-encoder:clip-input-p encoder) nil) (rove:ok (signals (htm-scalar-encoder:encode encoder 9.9) 'simple-error) (format nil "Input below minimum-input of ~a" (htm-scalar-encoder:minimum-input encoder))) (rove:ok (encode encoder 10.0)) (rove:ok (encode encoder 19.9)) (rove:ok (encode encoder 20.0)) (rove:ok (signals (encode encoder 20.1) 'simple-error) (format nil "Input above maximum-input of ~a" (htm-scalar-encoder:maximum-input encoder)))) ;; test with input-clipping allowed: (rove:testing "With input clipping:" (setf (htm-scalar-encoder:clip-input-p encoder) t) (rove:ok (encode encoder 9.9)) (rove:ok (encode encoder 20.1))))) ;;; Helper functions for subsequent test below (defun encode-cases (encoder data-array) "For each test-data in the DATA-ARRAY, encode its input and compare with its expected-output. DATA-ARRAY: a simple vector of struct test-data." (loop with each-input = nil with each-expected-output = nil for each-case in data-array do (progn (setf each-input (car each-case) each-expected-output (cdr each-case)) (rove:ok (equalp (htm-scalar-encoder:encode encoder each-input) each-expected-output))))) ;;; now back to the tests (rove:deftest non-integer-bucket-width (rove:testing "Non-integer-bucket-width:" (let ((encoder (make-instance 'htm-scalar-encoder:scalar-encoder :size 7 :num-consecutive-1-bits 3 :minimum-input 10.0 :maximum-input 20.0 )) (data-array '((10.0 . ((0 . 2))) (20.0 . ((4 . 6)))))) (encode-cases encoder data-array)))) ;;; another test (rove:deftest round-to-nearest-multiple-of-resolution (let ((encoder (make-instance 'htm-scalar-encoder:scalar-encoder :num-consecutive-1-bits 3 :minimum-input 10.0 :maximum-input 20.0 :resolution 1)) (cases '((10.00 . ((0 . 2))) (10.49 . ((0 . 2))) (10.50 . ((0 . 2))) ; (((1 . 3))) in Scalar-Encoder.cpp (11.49 . ((1 . 3))) (11.50 . ((2 . 4))) (14.49 . ((4 . 6))) (14.50 . ((4 . 6))) ; (((5 . 7))) in Scalar-Encoder.cpp (15.49 . ((5 . 7))) (15.50 . ((6 . 8))) (19.00 . ((9 . 11))) (19.49 . ((9 . 11))) (19.50 . ((10 . 12))) (20.00 . ((10 . 12)))))) (rove:testing "Round-to-nearest-multiple-of-resolution:" (rove:ok (equalp (htm-scalar-encoder:size encoder) 13)) (encode-cases encoder cases)))) (rove:deftest periodic-round-nearest-multiple-of-resolution (rove:testing "Periodic-round-nearest-multiple-of-resolution:" (let ((encoder (make-instance 'htm-scalar-encoder:scalar-encoder :num-consecutive-1-bits 3 :minimum-input 10.0 :maximum-input 20.0 :resolution 1 :periodic-input-p t)) (cases '((10.00 . ((0 . 2))) (10.49 . ((0 . 2))) (10.50 . ((0 . 2))) ; (((1 . 3))) (11.49 . ((1 . 3))) (11.50 . ((2 . 4))) (14.49 . ((4 . 6))) (14.50 . ((4 . 6))) ; (((5 . 7))) (15.49 . ((5 . 7))) (15.50 . ((6 . 8))) (19.49 . ((9 . 9) (0 . 1))) (19.50 . ((0 . 2))) (20.00 . ((0 . 2)))))) (rove:ok (equalp (htm-scalar-encoder:size encoder) 10)) (encode-cases encoder cases)))) (rove:deftest periodic-day-of-week (rove:testing "Periodic-day-of-week:" (let ((encoder (make-instance 'htm-scalar-encoder:scalar-encoder :num-consecutive-1-bits 3 :minimum-input 1.0 ; Monday :maximum-input 8.0 ; Monday :size 14 :periodic-input-p t) ;; equivalently: radius = 1.5 or resolution = 0.5 (12 hours) ) (cases '((1.0 . ((0 . 2))) (2.0 . ((2 . 4))) (3.0 . ((4 . 6))) (4.0 . ((6 . 8))) (5.0 . ((8 . 10))) (6.0 . ((10 . 12))) (7.0 . ((12 . 13) (0 . 0))) (8.0 . ((0 . 2)))))) (rove:ok (equalp (htm-scalar-encoder:resolution encoder) 0.5)) (format t "radius: ~a" (htm-scalar-encoder:radius encoder)) ;; (rove:ok (equalp (htm-scalar-encoder:radius encoder) 1.5)) (encode-cases encoder cases))))
5,984
Common Lisp
.lisp
119
33.932773
106
0.459459
hai-nc/htm-cl
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
07fee4bb2da9120e0a36f6dd7dbe4dbb1d1313f4ca06fa2963e976312af4bb10
26,825
[ -1 ]
26,826
htm-cl.asd
hai-nc_htm-cl/htm-cl.asd
(in-package #:common-lisp-user) (asdf:defsystem htm-cl :author "Hai NGUYEN" :maintainer "Hai NGUYEN" :licence "Please see the attached LICENCE file." :homepage "https://gitlab.com/haicnguyen/htm-cl" :version "0.0.1" :depends-on (#:ieee-floats #:cl-mop #:cl-portaudio) :components ((:module "src/" :serial t :components ((:file "package") (:file "helper") (:file "scalar-encoder")))) :description "This package implements Numenta's NUPIC in Common Lisp.") (asdf:defsystem htm-cl/test :author "Hai NGUYEN" :maintainer "Hai NGUYEN" :licence "Please see the attached LICENSE file." :depends-on (#:rove) :components ((:module "t/" :serial t :components ((:file "package") (:file "scalar-encoder")))))
877
Common Lisp
.asd
23
29.26087
73
0.582353
hai-nc/htm-cl
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1d9fd2580258b225719b500016fc7298876192f217886cb0fb68eca4f390cfd9
26,826
[ -1 ]
26,848
main.lisp
innaky_out-spaces/src/main.lisp
(defpackage out-spaces (:use :cl) (:export :space-trim :generic-trim :add-psfix :psfix-filter :replace-letter)) (in-package :out-spaces) (defmacro cc-s (&rest strs) `(concatenate 'string ,@strs)) (defun string-to-charlst (long-str &optional (position 0)) "The input is a string the output a list of characters, run from character 0 for default or for any other character, minor to length string." (if (not (numberp position)) (format t "~A is not type numb~%" position) (if (or (>= position (length long-str)) (< position 0)) nil (let ((end (length long-str))) (if (equal position end) nil (cons (char long-str position) (string-to-charlst long-str (+ 1 position)))))))) (defun del-letter (letter char-lst) "`letter' is a char, `char-lst' is a list of chars, this function return a list of chars without the `letter'." (cond ((equal char-lst nil) nil) ((char= letter (car char-lst)) (del-letter letter (cdr char-lst))) (t (cons (car char-lst) (del-letter letter (cdr char-lst)))))) (defun without-char (str char) "Delete any `char' for `str'." (let ((lst-chars (string-to-charlst str))) (cc-s (del-letter char lst-chars)))) (defun match? (elem lst) (if (equal nil lst) nil (or (equal elem (car lst)) (match? elem (cdr lst))))) (defun replace-atom (new old lst) "Replace `old' by `new' if exists inside `lst'. If not exists the `old' element return the same `lst'." (cond ((equal nil lst) nil) (t (cond ((equal (car lst) old) (cons new (replace-atom new old (cdr lst)))) (t (cons (car lst) (replace-atom new old (cdr lst)))))))) (defun replace-char (new old lst-paths) "Replace the `new' by `old' in the filename of a directory. If `old' match in the filename `new' is added, else return the same filename. The file extensions are not changed." (if (equal nil lst-paths) nil (let ((filename (file-namestring (namestring (car lst-paths)))) (head-path (directory-namestring (car lst-paths)))) (if (match? old (string-to-charlst filename)) (rename-file (car lst-paths) (cc-s head-path (replace-atom new old (string-to-charlst filename))))) (replace-char new old (cdr lst-paths))))) (defun not-char (char lst-paths) "Delete the match `char' of the filenames." (if (equal nil lst-paths) nil (let ((filename (file-namestring (namestring (car lst-paths)))) (head-path (directory-namestring (car lst-paths)))) (if (match? char (string-to-charlst filename)) (rename-file (car lst-paths) (cc-s head-path (without-char filename char)))) (not-char char (cdr lst-paths))))) (defun replace-letter (new-letter to-replace directory-path) "This function is a wrapper over the function `replace-char'. `directory-path' build the list of files for `replace-char'." (replace-char new-letter to-replace (cl-fad:list-directory directory-path))) (defun generic-trim (char directory-path) "Wrapper function, use a `char' and a `directory-path' and delete the `char' matching." (not-char char (cl-fad:list-directory directory-path))) (defun space-trim (directory-path) "Wrapper, capture the `directory-path' and return a list of files, this files are processed with the function `not-space'." (not-char #\space (cl-fad:list-directory directory-path))) (defun psfix (fix str-fix lst-paths) "Take the string \"pf\" for activate the prefix logic or the string \"sf\" for the sufix logic, the parameter `str-fix' is the string sufix or prefix and `lst-paths' is a list of files." (if (equal nil lst-paths) nil (let ((base-filename (pathname-name (namestring (car lst-paths)))) (head-path (directory-namestring (car lst-paths)))) (cond ((equal fix "pf") (rename-file (car lst-paths) (cc-s head-path str-fix base-filename))) ((equal fix "sf") (rename-file (car lst-paths) (cc-s head-path base-filename str-fix)))) (psfix fix str-fix (cdr lst-paths))))) (defun ext-filter (lst-paths ext) "The input is a list of filenames and a file extension. The output is a list of files with teh file extension. Not implement regex only plain file extension Ex: \"lisp\" for lisp filenames." (if (equal nil lst-paths) nil (if (equal (pathname-type (pathname (namestring (car lst-paths)))) ext) (cons (car lst-paths) (ext-filter (cdr lst-paths) ext)) (ext-filter (cdr lst-paths) ext)))) (defun psfix-filter (fix str-fix directory-path ext) "Extend the functionality of `psfix', this function is a wrapper and apply the filter filename." (psfix fix str-fix (ext-filter (cl-fad:list-directory directory-path) ext))) (defun add-psfix (fix str-fix directory-path) "This function is a wrapper of `psfix'" (psfix fix str-fix (cl-fad:list-directory directory-path)))
4,789
Common Lisp
.lisp
103
42.815534
113
0.694009
innaky/out-spaces
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
0b116b23775e6712317c1a085dd70bb75cf27067ea4a827cc2010dab87881a60
26,848
[ -1 ]
26,849
main.lisp
innaky_out-spaces/tests/main.lisp
(defpackage out-spaces/tests/main (:use :cl :out-spaces :rove)) (in-package :out-spaces/tests/main) ;; NOTE: To run this test file, execute `(asdf:test-system :out-spaces)' in your Lisp. (deftest test-target-1 (testing "should (= 1 1) to be true" (ok (= 1 1))))
288
Common Lisp
.lisp
9
28.111111
86
0.646209
innaky/out-spaces
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
030154b3a6cc8943abc3855d89ab563ced4acb0764952d0bccdd457c00c5f263
26,849
[ -1 ]
26,850
out-spaces.asd
innaky_out-spaces/out-spaces.asd
(defsystem "out-spaces" :version "0.1.0" :author "Innaky" :license "GPLv3" :depends-on ("cl-fad") :components ((:module "src" :components ((:file "main")))) :description "" :in-order-to ((test-op (test-op "out-spaces/tests")))) (defsystem "out-spaces/tests" :author "Innaky" :license "GPLv3" :depends-on ("out-spaces" "rove") :components ((:module "tests" :components ((:file "main")))) :description "Test system for out-spaces" :perform (test-op (op c) (symbol-call :rove :run c)))
589
Common Lisp
.asd
20
23.15
56
0.570423
innaky/out-spaces
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
51de4aa62b231fc24ff9ec21745a53c2021e2b35146ec055d2f1365c8b86cffe
26,850
[ -1 ]
26,869
experiment-bump.lisp
brobinson9999_ultrastar-file-manipulation/experiment-bump.lisp
;#!/usr/bin/clisp (load "ultrastar-file-manipulation.lisp") (defparameter *filename* "Britney Spears - Lucky.txt") (defparameter *file* (parse-ultrastar-file *filename*)) (defun bump-pitch (pitch-adjustment) (setf (getf *file* :notes) (loop for note in (getf *file* :notes) collecting (destructuring-bind (note-type note-start note-length note-pitch lyrics) note (list note-type note-start note-length (+ note-pitch pitch-adjustment) lyrics))))) (getf *file* :video) ;(bump-pitch 1) ;(write-file *filename* ; (generate-ultrastar-string *file*))
581
Common Lisp
.lisp
14
38.357143
89
0.713012
brobinson9999/ultrastar-file-manipulation
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c7c7854d43960732e51b5c4ca5cc07f9c1e4390eb2361d7e683e674fe57c1093
26,869
[ -1 ]
26,870
ultrastar-file-manipulation.lisp
brobinson9999_ultrastar-file-manipulation/ultrastar-file-manipulation.lisp
(load "brute-io.lisp") (load "split-sequence.lisp") ; an ultrastar-data is a plist. The following properties are recognized: ; title: (string) the title of the song (displayed in-game) ; artist: (string) the artist of the song (displayed in-game) ; mp3: (string) the filename of the mp3 that should be used ; bpm: (number) beats per minute ; gap: (number) milliseconds from the start of the MP3 to the first note ; cover: (string) the filename of a cover art file (JPG or PNG) ; background: (string) the filename of a background art file (JPG or PNG) ; relative: (boolean) This shows how the txt-file is written. If this tag is set to “yes”, the start of the notes is counted from zero in every line. If this tag is not available or set to “no”, the start of the notes is counted continuous from the beginning to the end of the txt-file. ; video: (string) the filename of a video file (avi, mpg, flv at least are supported) ; videogap: (number) the video file starts playing this many seconds from it's start ; start: (number) the MP3 file starts playing this many seconds from it's start ; genre: (string) genre of the song. this can be used for sorting songs, but has no other effect. ; edition: (string) what "edition" this song was ripped from. this can be used for sorting songs, but has no other effect. ; language: (string) language that the song is in. this can be used for sorting songs, but has no other effect. ; notes: (listof ultrastar-note-data) a list containing the body data of the ultrastar song ; an ultrastar-note-data is a (list note-type note-start note-length note-pitch lyrics) where: ; note-type is a symbol, one of :normal, :golden, :freestyle, or :line-break. Ultrastar files also support the note type "E" indicating end of file, but this is implicit and does not have a corresponding ultrastar-note-data. ; note-start is a number indicating the start time of the note. It is measured either from the beginning of the file or from the end of the previous line. ; note-length is a number indicating the length of the note. ; note-pitch is a number indicating the pitch of the note. ; lyrics is a string containing the lyrics for this note. ; generate-ultrastar-header-data: ultrastar-data symbol string -> string ; purpose: consumes an ultrastar-data structure, the key of one of it's properties, ; and a string title for that property. If the property is non-NIL, a string ; containing it's textual representation is produced, otherwise an empty string ; is produced. (defun generate-ultrastar-header-data (input-data header-key header-title) (if (getf input-data header-key) (format NIL "#~a:~a~%" header-title (getf input-data header-key)) "")) ; generate-ultrastar-note-string: ultrastar-note-data -> string ; purpose: consumes structured ultrastar-note-data and produces a string representing ; that data in the format of an ultrastar song file. (defun generate-ultrastar-note-string (input-data) (destructuring-bind (note-type note-start note-length note-pitch lyrics) input-data (case note-type (:normal (format NIL ": ~a ~a ~a ~a" note-start note-length note-pitch lyrics)) (:golden (format NIL "* ~a ~a ~a ~a" note-start note-length note-pitch lyrics)) (:freestyle (format NIL "F ~a ~a ~a ~a" note-start note-length note-pitch lyrics)) (:line-break (if (= note-length 0) (format NIL "- ~a" note-start) (format NIL "- ~a ~a" note-start note-length)))))) ; generate-ultrastar-string: ultrastar-data -> string ; purpose: consumes structured ultrastar-data and produces a string representing ; that data in the format of an ultrastar song file. (defun generate-ultrastar-string (input-data) (format NIL "~a~a~a~a~a~a~a~a~a~a~a~a~a~a~{~a~%~}E~%" (generate-ultrastar-header-data input-data :title "TITLE") (generate-ultrastar-header-data input-data :artist "ARTIST") (generate-ultrastar-header-data input-data :mp3 "MP3") (generate-ultrastar-header-data input-data :bpm "BPM") (generate-ultrastar-header-data input-data :gap "GAP") (generate-ultrastar-header-data input-data :cover "COVER") (generate-ultrastar-header-data input-data :background "BACKGROUND") (format NIL "#RELATIVE:~a~%" (if (getf input-data :relative) "YES" "NO")) (generate-ultrastar-header-data input-data :video "VIDEO") (generate-ultrastar-header-data input-data :videogap "VIDEOGAP") (generate-ultrastar-header-data input-data :start "START") (generate-ultrastar-header-data input-data :genre "GENRE") (generate-ultrastar-header-data input-data :edition "EDITION") (generate-ultrastar-header-data input-data :language "LANGUAGE") (mapcar #'generate-ultrastar-note-string (getf input-data :notes)))) ; generate-ultrastar-file: string ultrastar-data -> string ; purpose: consumes a filename and an ultrastar-data, and produces a string ; containing the text of an ultrastar file storing that data. The text is ; also written to disk at the filename given. (defun generate-ultrastar-file (file-name input-data) (write-file file-name (generate-ultrastar-string input-data))) ; string-starts-with: string string -> boolean ; purpose: produces true if the second string starts with the ; same characters as the first string. (defun string-starts-with (start-string input-string) (cond ((< (length input-string) (length start-string)) NIL) (T (equalp start-string (subseq input-string 0 (length start-string)))))) ; string-chomp: string string -> string ; purpose: consumes a string to chomp and a string to chomp ; it from. Produces the second string with the length of the ; first string removed from it's start. The second string does ; not have to start with the first string, only the length of ; the first string is used. If the length of the first string ; is greater than the length of the second string, the empty ; string is produced. (defun string-chomp (start-string input-string) (cond ((<= (length input-string) (length start-string)) "") (T (subseq input-string (length start-string) (length input-string))))) ; a condition raised when a line of a song file is not valid (define-condition invalid-song-file-line (error) ((text :initarg :text :reader text))) ; parse-ultrastar-notes: (listof string) -> (listof ultrastar-note-data) ; purpose: consumes a list of strings in the Ultrastar song file format, ; consisting only of notes, and produces a list of ultrastar-note-data ; representing the same notes (defun parse-ultrastar-notes (input-list) (cond ((eql input-list NIL) NIL) ((string-starts-with "E" (first input-list)) NIL) (T (cons (parse-ultrastar-note (first input-list)) (parse-ultrastar-notes (rest input-list)))))) ; parse-ultrastar-note: string -> ultrastar-note-data ; purpose: consumes a string representing a single note ; in the Ultrastar song file format, and produces the ; ultrastar-note-data representing that same note (defun parse-ultrastar-note (note-string) (let ((note-list (split-sequence:split-sequence #\Space note-string))) (list (cond ((equalp (first note-list) ":") :normal) ((equalp (first note-list) "*") :golden) ((equalp (first note-list) "F") :freestyle) ((equalp (first note-list) "-") :line-break) (T (error 'invalid-song-file-line :text (first note-list)))) (if (second note-list) (parse-integer (second note-list)) 0) (if (third note-list) (parse-integer (third note-list)) 0) (if (fourth note-list) (parse-integer (fourth note-list)) 0) (format NIL "~{~a~^ ~}" (cddddr note-list))))) ; parse-ultrastar-lines: (listof string) -> ultrastar-data ; purpose: consumes a list of strings in the format of ; an ultrastar song file, and produces structured ultrastar-data ; representing the contents of the file. Each element of the input ; list is one line of the song file. (defun parse-ultrastar-lines (input-list) (cond ((eql input-list NIL) NIL) ((string-starts-with "E" (first input-list)) NIL) ((string-starts-with "#TITLE:" (first input-list)) (add-str-prop-and-recurse "#TITLE:" :title input-list)) ((string-starts-with "#ARTIST:" (first input-list)) (add-str-prop-and-recurse "#ARTIST:" :artist input-list)) ((string-starts-with "#MP3:" (first input-list)) (add-str-prop-and-recurse "#MP3:" :mp3 input-list)) ((string-starts-with "#BPM:" (first input-list)) (add-num-prop-and-recurse "#BPM:" :bpm input-list)) ((string-starts-with "#GAP:" (first input-list)) (add-num-prop-and-recurse "#GAP:" :gap input-list)) ((string-starts-with "#COVER:" (first input-list)) (add-str-prop-and-recurse "#COVER:" :cover input-list)) ((string-starts-with "#BACKGROUND:" (first input-list)) (add-str-prop-and-recurse "#BACKGROUND:" :background input-list)) ((string-starts-with "#GENRE:" (first input-list)) (add-str-prop-and-recurse "#GENRE:" :genre input-list)) ((string-starts-with "#RELATIVE:" (first input-list)) (add-bool-prop-and-recurse "#RELATIVE:" :relative input-list)) ((string-starts-with "#EDITION:" (first input-list)) (add-str-prop-and-recurse "#EDITION:" :edition input-list)) ((string-starts-with "#LANGUAGE:" (first input-list)) (add-str-prop-and-recurse "#LANGUAGE:" :language input-list)) ((string-starts-with "#VIDEO:" (first input-list)) (add-str-prop-and-recurse "#VIDEO:" :video input-list)) ((string-starts-with "#VIDEOGAP:" (first input-list)) (add-num-prop-and-recurse "#VIDEOGAP:" :videogap input-list)) ((string-starts-with "#START:" (first input-list)) (add-num-prop-and-recurse "#START:" :start input-list)) ((or (string-starts-with ":" (first input-list)) (string-starts-with "*" (first input-list)) (string-starts-with "F" (first input-list)) (string-starts-with "-" (first input-list))) (list :notes (parse-ultrastar-notes input-list))) (T (error 'invalid-song-file-line :text (first input-list))))) (defun add-str-prop-and-recurse (string-start keyword input-list) (cons keyword (cons (string-chomp string-start (first input-list)) (parse-ultrastar-lines (rest input-list))))) ; Allows junk because BPM sometimes has a comma and a part after the comma. I haven't been able to find any ; documentation for what that comma is about. I'm currently throwing it out. (defun add-num-prop-and-recurse (string-start keyword input-list) (cons keyword (cons (parse-integer (string-chomp string-start (first input-list)) :junk-allowed T) (parse-ultrastar-lines (rest input-list))))) (defun add-bool-prop-and-recurse (string-start keyword input-list) (cons keyword (cons (eql (string-chomp string-start (first input-list)) "yes") (parse-ultrastar-lines (rest input-list))))) ; parse-ultrastar-string: string -> ultrastar-data ; purpose: consumes a string representing in the format of ; an ultrastar song file, and produces structured ultrastar-data ; representing the contents of the file. (defun parse-ultrastar-string (input-string) (parse-ultrastar-lines (split-sequence:split-sequence #\Newline input-string))) ; parse-ultrastar-file: string -> ultrastar-data ; purpose: consumes a filename, and produces ultrastar-data representing ; the contents of that file. (defun parse-ultrastar-file (file-name) (parse-ultrastar-string (read-file file-name)))
11,226
Common Lisp
.lisp
184
58.331522
286
0.73441
brobinson9999/ultrastar-file-manipulation
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
cfe600ad83b790e6e354628f819e3e94438efe1f092d0bbf28ea784051d2ff88
26,870
[ -1 ]
26,871
ultrastar-file-manipulation.test.lisp
brobinson9999_ultrastar-file-manipulation/ultrastar-file-manipulation.test.lisp
#!/usr/bin/clisp (load "ultrastar-file-manipulation.lisp") (load "../cl-tap-producerX/cl-tap-framework.lisp") (is (generate-ultrastar-header-data '() :title "TITLE") (format NIL "")) (is (generate-ultrastar-header-data '(:title "mytitle") :title "TITLE") (format NIL "#TITLE:mytitle~%")) (is (generate-ultrastar-header-data '(:something "else") :title "TITLE") (format NIL "")) (is (generate-ultrastar-note-string '(:normal 1 2 3 "meow")) ": 1 2 3 meow") (is (generate-ultrastar-note-string '(:golden 3 2 1 "gold")) "* 3 2 1 gold") (is (generate-ultrastar-note-string '(:freestyle 3 2 1 "free")) "F 3 2 1 free") (is (generate-ultrastar-note-string '(:line-break 3 2 1 "lb")) "- 3 2") (is (generate-ultrastar-note-string '(:line-break 3 0 0 "")) "- 3") (is (generate-ultrastar-string '()) (format NIL "#RELATIVE:NO~%E~%")) (is (generate-ultrastar-string '(:title "mytitle")) (format NIL "#TITLE:mytitle~%#RELATIVE:NO~%E~%")) (is (generate-ultrastar-string '(:irrelevant "text")) (format NIL "#RELATIVE:NO~%E~%")) (is (generate-ultrastar-string '(:title "mytitle" :artist "myartist")) (format NIL "#TITLE:mytitle~%#ARTIST:myartist~%#RELATIVE:NO~%E~%")) (is (generate-ultrastar-string '(:relative T)) (format NIL "#RELATIVE:YES~%E~%")) (is (generate-ultrastar-string '(:notes ((:normal 1 2 3 "yelp") (:golden 3 2 1 "bark")))) (format NIL "#RELATIVE:NO~%: 1 2 3 yelp~%* 3 2 1 bark~%E~%")) (is (string-starts-with "" "") T) (is (string-starts-with "a" "a") T) (is (string-starts-with "ab" "abab") T) (is (string-starts-with "abab" "baba") NIL) (is (string-starts-with "baba" "bab") NIL) (is (string-chomp "" "") "") (is (string-chomp "a" "a") "") (is (string-chomp "a" "ab") "b") (is (string-chomp "aaa" "b") "") (is (string-chomp "abab" "ababab") "ab") (is (parse-ultrastar-note ":") '(:normal 0 0 0 "")) (is (parse-ultrastar-note "F 0 4 20 I") '(:freestyle 0 4 20 "I")) (is (parse-ultrastar-note ": 0 4 20 I") '(:normal 0 4 20 "I")) (is (parse-ultrastar-note ": 0 4 20 I just") '(:normal 0 4 20 "I just")) (is (parse-ultrastar-note "* 20 24 200 I just") '(:golden 20 24 200 "I just")) (is-condition (parse-ultrastar-note "WTF? 0 4") (make-condition 'invalid-song-file-line :text "WTF?")) (is (parse-ultrastar-lines '("#ARTIST:Joe Blow")) '(:artist "Joe Blow")) (is (parse-ultrastar-lines '("#VIDEO:Lord Shenanigans - Pimp Cane[VD#0].mpg")) '(:video "Lord Shenanigans - Pimp Cane[VD#0].mpg")) (is (parse-ultrastar-lines '("#ARTIST:Joe Blow" "#TITLE:Country Blues")) '(:artist "Joe Blow" :title "Country Blues")) (is (parse-ultrastar-lines '("#ARTIST:Joe Blow" "#TITLE:Country Blues" ": 0 4 20 I just" "* 5 11 21 can't believe " "E")) '(:artist "Joe Blow" :title "Country Blues" :notes ((:normal 0 4 20 "I just") (:golden 5 11 21 " can't believe ")))) (is-condition (parse-ultrastar-lines '("#ARTIST:Joe Blow" "WTF? 0 4")) (make-condition 'invalid-song-file-line :text "WTF? 0 4")) ;(is (generate-ultrastar-string (parse-ultrastar-file "Pornophonique - Space Invaders.txt")) ; (read-file "Pornophonique - Space Invaders.txt")) (print-test-plan)
3,134
Common Lisp
.lisp
54
55.37037
130
0.642555
brobinson9999/ultrastar-file-manipulation
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a6d25dcf86977d8caa201bbafeacab569333f804d42a154cc9890b8fa17970e8
26,871
[ -1 ]
26,891
graph-util.lisp
elevatorsimulator_grand-theft-wumpus/graph-util.lisp
(defparameter *max-label-length* 30) (defparameter *wizard-nodes* '((garden (you are in a beautiful garden. there is a well in front of you.)) (living-room (you are in the living room. a wizard is snoring loudly on the couch.)) (attic (you are in the attic. there is a giant welding torch in the corner.)))) (defparameter *wizard-edges* '((garden (living-room east door)) (living-room (garden west door) (attic upstairs ladder)) (attic (living-room downstairs ladder)))) (defun dot-name (exp) (substitute-if #\_ (complement #'alphanumericp) (prin1-to-string exp))) (defun dot-label (exp) (if exp (let ((s (write-to-string exp :pretty nil))) (if (> (length s) *max-label-length*) (concatenate 'string (subseq s 0 (- *max-label-length* 3)) "...") s)) "")) (defun nodes->dot (nodes) (mapc (lambda (node) (fresh-line) (princ (dot-name (car node))) (princ "[label=\"") (princ (dot-label node)) (princ "\"];")) nodes)) (defun edges->dot (edges) (mapc (lambda (edges-from-source) (mapc (lambda (edge) (fresh-line) (princ (dot-name (car edges-from-source))) (princ "->") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];")) (cdr edges-from-source))) edges)) (defun graph->dot (nodes edges) (princ "digraph {") (nodes->dot nodes) (edges->dot edges) (princ "}")) (defun dot->png (fname thunk) (with-open-file (*standard-output* fname :direction :output :if-exists :supersede) (funcall thunk)) (sb-ext:run-program "dot" (list "-Tpng" "-O" fname) :search t)) (defun graph->png (nodes edges fname) (dot->png fname (lambda () (graph->dot nodes edges)))) (defun uedges->dot (edges) (maplist (lambda (lst) (mapc (lambda (edge) (unless (assoc (car edge) (cdr lst)) (fresh-line) (princ (dot-name (caar lst))) (princ "--") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];"))) (cdar lst))) edges)) (defun ugraph->dot (nodes edges) (princ "graph {") (nodes->dot nodes) (uedges->dot edges) (princ "}")) (defun ugraph->png (nodes edges fname) (dot->png fname (lambda () (ugraph->dot nodes edges))))
2,809
Common Lisp
.lisp
72
27.680556
115
0.501834
elevatorsimulator/grand-theft-wumpus
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
36374ec828e539c7e731acefe587f7b1b6396eabb1da5c81e4a96896a9c6e4c7
26,891
[ -1 ]
26,892
grand-theft-wumpus.lisp
elevatorsimulator_grand-theft-wumpus/grand-theft-wumpus.lisp
(load "graph-util.lisp") (defvar *congestion-city-nodes*) (defvar *congestion-city-edges*) (defvar *visited-nodes*) (defvar *player-pos*) (defparameter *node-num* 30) (defparameter *edge-num* 45) (defparameter *worm-num* 3) (defparameter *cop-odds* 15) (defun random-node () (1+ (random *node-num*))) (defun edge-pair (a b) (unless (eql a b) (list (cons a b) (cons b a)))) (defun make-edges () (remove-duplicates (apply #'append (loop repeat *edge-num* collect (edge-pair (random-node) (random-node)))) :test #'equalp)) (defun direct-edges (node edges) (remove-if-not (lambda (edge) (eql node (car edge))) edges)) (defun get-connected (node edges) (let ((visited ())) (labels ((traverse (node) (when (not (member node visited)) (push node visited) (mapc #'traverse (mapcar #'cdr (direct-edges node edges)))))) (traverse node) visited))) (defun find-islands (nodes edges) (let ((islands ())) (labels ((find-island (nodes) (when nodes (let* ((connected (get-connected (car nodes) edges)) (disconnected (set-difference nodes connected))) (push connected islands) (when disconnected (find-island disconnected)))))) (find-island nodes) islands))) (defun connect-with-bridges (islands) (when (cdr islands) (append (edge-pair (caar islands) (caadr islands)) (connect-with-bridges (cdr islands))))) (defun connect-all-islands (nodes edges) (append edges (connect-with-bridges (find-islands nodes edges)))) (defun edges-to-alist (nodes edges) (mapcar (lambda (node) (cons node (mapcar (lambda (edge) (list (cdr edge))) (direct-edges node edges)))) nodes)) (defun add-cops (edge-alist edges-with-cops) (mapcar (lambda (x) (let ((node1 (car x)) (edges (cdr x))) (cons node1 (mapcar (lambda (edge) (let ((node2 (car edge))) (if (intersection (edge-pair node1 node2) edges-with-cops :test #'equalp) (list node2 'cops) edge))) edges)))) edge-alist)) (defun make-city-edges () (let* ((nodes (loop for i from 1 to *node-num* collect i)) (edges (connect-all-islands nodes (make-edges))) (cops (remove-if-not (lambda (x) (declare (ignore x)) (zerop (random *cop-odds*))) edges))) (add-cops (edges-to-alist nodes edges) cops))) (defun neighbours (node edge-alist) (mapcar #'car (cdr (assoc node edge-alist)))) (defun within-one (node1 node2 edge-alist) (member node2 (neighbours node1 edge-alist))) (defun within-two (node1 node2 edge-alist) (or (within-one node1 node2 edge-alist) (some (lambda (node) (within-one node node2 edge-alist)) (neighbours node1 edge-alist)))) (defun make-city-nodes (edge-alist) (let ((wumpus (random-node)) (glow-worms (do ((worms () (adjoin (random-node) worms))) ((= (length worms) *worm-num*) worms)))) (loop for node from 1 to *node-num* collect (append (list node) (cond ((eql node wumpus) '(wumpus)) ((within-two node wumpus edge-alist) '(blood))) (cond ((member node glow-worms) '(glow-worm)) ((intersection glow-worms (neighbours node edge-alist)) '(lights!))) (when (some (lambda (edge) (member 'cops edge)) (cdr (assoc node edge-alist))) '(sirens!)))))) (defun find-empty-node () (loop (let ((node (random-node))) (unless (cdr (assoc node *congestion-city-nodes*)) (return node))))) (defun known-city-nodes () (mapcar (lambda (node) (cons node (if (member node *visited-nodes*) (let ((desc (cdr (assoc node *congestion-city-nodes*)))) (if (eql node *player-pos*) (append desc '(*)) desc)) '(?)))) (reduce #'union (mapcar (lambda (node) (neighbours node *congestion-city-edges*)) *visited-nodes*) :initial-value *visited-nodes*))) (defun known-city-edges () (mapcar (lambda (node) (cons node (mapcar (lambda (edge) (if (member (car edge) *visited-nodes*) edge (remove 'cops edge))) (cdr (assoc node *congestion-city-edges*))))) *visited-nodes*)) (defun draw-known-city () (ugraph->png (known-city-nodes) (known-city-edges) "known-city")) (defun draw-city () (ugraph->png *congestion-city-nodes* *congestion-city-edges* "city")) (defun handle-new-place (pos edge charging) (let* ((node (assoc pos *congestion-city-nodes*)) (attacked-by-worms (and (member 'glow-worm node) (not (member pos *visited-nodes*))))) (pushnew pos *visited-nodes*) (setf *player-pos* pos) (draw-known-city) (cond ((member 'cops edge) (princ "You ran into the cops. Game over.")) ((member 'wumpus node) (if charging (princ "You found the Wumpus!") (princ "You ran into the Wumpus!"))) (charging (princ "You wasted your last bullet. Game Over.")) (attacked-by-worms (let ((new-pos (random-node))) (princ "You ran into a Glow Worm Gang! You're now at ") (princ new-pos) (handle-new-place new-pos nil nil)))))) (defun handle-direction (pos charging) (let ((edge (assoc pos (cdr (assoc *player-pos* *congestion-city-edges*))))) (if edge (handle-new-place pos edge charging) (princ "There's no such location visible from here!")))) (defun walk (pos) (handle-direction pos nil)) (defun charge (pos) (handle-direction pos t)) (defun new-game () (setf *congestion-city-edges* (make-city-edges)) (setf *congestion-city-nodes* (make-city-nodes *congestion-city-edges*)) (setf *player-pos* (find-empty-node)) (setf *visited-nodes* (list *player-pos*)) (draw-city) (draw-known-city))
7,001
Common Lisp
.lisp
163
30.07362
100
0.516664
elevatorsimulator/grand-theft-wumpus
1
0
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
6e04e4af6f6665645190c128dd4d588193337c61506b8f74a458f66a98d66866
26,892
[ -1 ]
26,910
package.lisp
gschjetne_automata-tools/package.lisp
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; package.lisp (defpackage #:automata-tools (:use #:cl) (:import-from #:cl-dot #:graph-object-node #:graph-object-points-to #:node #:attributed #:generate-graph-from-roots #:dot-graph))
1,010
Common Lisp
.lisp
25
35.32
72
0.681587
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a74600ec640f476d5ecf077669618b608b1e29fe691f184f2a08fba199d7d0db
26,910
[ -1 ]
26,911
automata-tools.lisp
gschjetne_automata-tools/automata-tools.lisp
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; automata-tools.lisp (in-package #:automata-tools) (defclass automaton () ((current-states :accessor get-current-states) (states :reader get-states :initarg :states) (initial-state :reader get-initial-state :initarg :initial-state) (accepting-states :reader get-accepting-states :initarg :accepting-states) (alphabet :reader get-alphabet :initarg :alphabet) (delta :reader get-delta-function :initarg :delta))) (defmethod initialize-instance :after ((a automaton) &key) (reset-automaton a)) (defgeneric accepting-p (automaton)) (defmethod accepting-p ((a automaton)) (intersection (get-current-states a) (get-accepting-states a))) (defgeneric reset-automaton (automaton)) (defmethod reset-automaton ((a automaton)) (setf (get-current-states a) (list (get-initial-state a)))) (defgeneric deterministic-p (automaton-or-transitions)) (defmethod deterministic-p ((transitions list)) (labels ((det-p (state) (if state (and (= 2 (length (car state))) (det-p (cdr state))) t))) (if transitions (and (det-p (cdar transitions)) (deterministic-p (cdr transitions))) t))) (defun states-in-table (transition-table) (remove-if-not #'identity (remove-duplicates (loop for row in transition-table append (cons (car row) (reduce #'append (mapcar #'cdr (cdr row)))))))) (defun find-transitions (transitions state symbol) (reduce #'append (mapcar #'cdr (remove-if-not (lambda (c) (eql c symbol)) (cdr (find state transitions :key #'car)) :key #'car)))) (defun compile-transitions (states alphabet transitions) (eval `(lambda (state symbol) (case state ,@(loop for state in states collect `(,state (case symbol ,@(loop for symbol in alphabet collect `(,symbol (quote ,(find-transitions transitions state symbol)))) (otherwise nil)))) (otherwise nil))))) (defun make-automaton (type transitions initial-state accepting-states &key additional-states) (let ((alphabet (sort (remove-duplicates (mapcar #'car (reduce #'append (mapcar #'cdr transitions)))) #'multi-lessp)) (states (states-in-table transitions))) (make-instance type :states (sort (union states additional-states) #'multi-lessp) :initial-state initial-state :accepting-states accepting-states :alphabet alphabet :delta (compile-transitions states alphabet transitions)))) (defgeneric delta (automaton state symbol)) (defmethod delta ((a automaton) state symbol) (funcall (get-delta-function a) state symbol)) (defgeneric extended-delta (automaton state string)) (defmethod extended-delta ((a automaton) state (string sequence)) (extended-delta a state (coerce string 'list))) (defgeneric step-automaton (automaton string-or-symbol)) (defmethod step-automaton ((a automaton) s) (typecase s (sequence (setf (get-current-states a) (extended-delta a (get-current-states a) s))) (t (step-automaton a (list s)))))
4,566
Common Lisp
.lisp
104
32.384615
88
0.583521
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
9ab55d5346e6435c9675441b86c73cc77478d68bdc8acf0aa6b26dac9ba407b3
26,911
[ -1 ]
26,912
operations.lisp
gschjetne_automata-tools/operations.lisp
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; operations.lisp (in-package #:automata-tools) (defgeneric product-automaton (a1 a2 &key variation)) (defmethod product-automaton ((a1 dfa) (a2 dfa) &key variation) (flet ((combine-pairs (pairs) ;; Todo: Remove combine-states in favour of the more general combined-state (mapcar (lambda (p) (combine-states (car p) (cdr p))) pairs))) (let* ((new-states (cartesian-cons (get-states a1) (get-states a2))) (new-alphabet (intersection (get-alphabet a1) (get-alphabet a2))) (new-transitions (loop for pair in new-states collect (let ((s1 (car pair)) (s2 (cdr pair))) (cons (combine-states s1 s2) (loop for symbol in new-alphabet collect (list symbol (combine-states (car (delta a1 s1 symbol)) (car (delta a2 s2 symbol)))))))))) (make-automaton 'dfa new-transitions (combine-states (get-initial-state a1) (get-initial-state a2)) (if variation (remove-duplicates (combine-pairs (append (cartesian-cons (get-accepting-states a1) (get-states a2)) (cartesian-cons (get-states a1) (get-accepting-states a2))))) (combine-pairs (cartesian-cons (get-accepting-states a1) (get-accepting-states a2)))) :additional-states (combine-pairs new-states))))) (defgeneric complement-automaton (automaton)) (defmethod complement-automaton ((a dfa)) (make-automaton 'dfa (get-transition-table a) (get-initial-state a) (set-difference (get-states a) (get-accepting-states a)) :additional-states (get-states a))) (defgeneric to-dfa (automaton)) (defmethod to-dfa ((a nfa)) (let ((states (powerset (get-states a))) (alphabet (get-alphabet a))) (flet ((compute-transitions (state) (flet ((map-symbol (symbol) (and state (list symbol (combined-state (reduce #'union (mapcar (lambda (s) (delta a s symbol)) state))))))) (cons (combined-state state) (mapcar #'map-symbol alphabet))))) (make-automaton 'dfa (mapcar #'compute-transitions states) (get-initial-state a) (mapcar #'combined-state (remove-if-not (lambda (s) (intersection (get-accepting-states a) s)) states)))))) (defmethod to-dfa ((a nfa)) (let* ((states (powerset (get-states a))) (accepting-states (reduce #'union (loop for as in (get-accepting-states a) collect (mapcar #'combined-state (remove-if-not (lambda (f) (find as f)) states))))) (alphabet (get-alphabet a)) (dfa (make-instance 'dfa :accepting-states accepting-states :states (mapcar #'combined-state states) :initial-state (get-initial-state a) :alphabet alphabet))) (dolist (state states) (dolist (symbol alphabet) (eval `(defmethod delta ((a (eql ,dfa)) (state (eql (quote ,(combined-state state)))) (symbol (eql (quote ,symbol)))) (quote ,(list (combined-state (reduce #'union (loop for s in state collect (delta a s symbol)) :initial-value nil)))))))) dfa)) (defgeneric get-accessible-states (automaton state)) (defmethod get-accessible-states ((automaton automaton) state) (let ((alphabet (get-alphabet automaton))) (labels ((a (states tested accessible) (if states (let ((next-states (reduce #'union (loop for symbol in alphabet collect (delta automaton (car states) symbol))))) (a (set-difference (union next-states (cdr states)) tested) (union tested (list (car states))) (union accessible (union (list (car states)) next-states)))) accessible))) (sort (copy-list (a (list state) nil nil)) #'string-lessp)))) (defgeneric prune-automaton (automaton))
6,421
Common Lisp
.lisp
119
32.386555
97
0.458665
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
79d02641f3f6f081cf08da358193741ec289cdf8d6b77639abd83676fded03ed
26,912
[ -1 ]
26,913
deterministic.lisp
gschjetne_automata-tools/deterministic.lisp
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; deterministic.lisp (in-package #:automata-tools) (defclass dfa (automaton) ()) (defmethod deterministic-p ((a dfa)) t) (defmethod extended-delta ((a dfa) state (string list)) (typecase state (list (if string (extended-delta a (car (delta a (car state) (car string))) (cdr string)) state)) (t (extended-delta a (list state) string))))
1,101
Common Lisp
.lisp
25
41.32
86
0.723623
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fc44489f73bb6e04ed03e88ba44b13080944c68370052a5f428d2f8dd17d3cce
26,913
[ -1 ]
26,914
nondeterministic.lisp
gschjetne_automata-tools/nondeterministic.lisp
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; nondeterministic.lisp (in-package #:automata-tools) (defclass nfa (automaton) ()) (defmethod deterministic-p ((a nfa)) nil) (defmethod extended-delta ((a nfa) state (string list)) (typecase state (list (if string (extended-delta a (reduce #'union (mapcar (lambda (s) (delta a s (car string))) state)) (cdr string)) state)) (t (extended-delta a (list state) string))))
1,253
Common Lisp
.lisp
28
38
85
0.654918
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4ec873fb5a07fca200933b15311076ecf153bdca6bbe4b4b3e2a519b987353e7
26,914
[ -1 ]
26,915
automata-tools.asd
gschjetne_automata-tools/automata-tools.asd
;; Automata Tools for Common Lisp ;; Copyright (C) 2016 Grim Schjetne ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; automata-tools.asd (asdf:defsystem #:automata-tools :description "Learning about finite automata in Common Lisp." :author "Grim Schjetne" :license "GPLv3+" :serial t :depends-on (:cl-dot) :components ((:file "package") (:file "utils") (:file "automata-tools") (:file "deterministic") (:file "nondeterministic") (:file "operations") (:file "output")))
1,180
Common Lisp
.asd
29
36.068966
72
0.687282
gschjetne/automata-tools
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fa03fe214d2ddb4db43e781d4bdeb815b36ea22f24197f961668934cca82e011
26,915
[ -1 ]
26,937
digital.lisp
olewhalehunter_cl-digital/digital.lisp
;; Digital EDA Tooling with Common Lisp ;; (declaim (sb-ext:muffle-conditions cl:warning)) (declaim (optimize (debug 3))) (ql:quickload :jsown) (defmacro append! (x y) (list 'setq x (list 'append x y))) (defmacro remove! (x y) (list 'setq y (list 'remove x y))) (defun diff (x y) (set-difference x y)) (defun c+ (&rest strs) (apply 'concatenate (append '(string) (mapcar (lambda (x) (if (symbolp x) (symbol-name x) x)) strs)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (setq *label-counter* 1) (defun input-nodes (node) (mapcar (lambda (x) (car (get node x))) (get node 'inputs))) (defun output-nodes (node) (mapcar (lambda (x) (car (get node x))) (get node 'outputs))) (defun clear-node (node) (setf (symbol-plist node) '())) (defun node (name function inputs outputs) (set name (intern (symbol-name name))) (clear-node name) (setf (get name 'inputs) inputs (get name 'outputs) outputs (get name 'function) function (get name 'label-ids) '()) (loop for p in (append inputs outputs) do (setf (get name 'label-ids) (push (list p (incf *label-counter*)) (get name 'label-ids)))) name) (defun node-labels (node) (append (get node 'inputs) (get node 'outputs))) (defun co (from from-out-label to to-in-label) "connect output of node FROM to node TO" (setf (get from from-out-label) (cons to to-in-label) (get to to-in-label) (cons from from-out-label))) (defun bit-print (bits) (format nil "~B" bits)) '("Bitwise Operators" (setq a #*011 b #*101) (arrayp a) (aref a 0) (bit-not a) (bit-ior a b) (bit-nor a b) (bit-xor a b) (bit-and a b) (bit-nand a b) (bit-eqv a b) ) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defun label-value (label) (intern (c+ label "-" 'value))) (defun set-node-value (node label value) (setf (get node (label-value label)) value)) (defun get-node-value (node label) (get node (label-value label))) (defun node-inputs-signals (node) (mapcar (lambda (i) (list i (get-node-value node i))) (get node 'inputs))) (defun connected-output? (node) (setq connected nil) (loop for output in (get node 'outputs) do (if (get node output) (setq connected t))) connected) (defun get-node-outputs (node) (loop for out in (get node 'outputs) collect (list out (get node (label-value out))))) (defun display-outputs (nodes) (terpri) (mapcar (lambda (node) (print (list node (get-node-outputs node)))) nodes)) (defun function-node (node node-function) (loop for out-label in (get node 'outputs) collect (list out-label (set-node-value node out-label (apply node-function input-signals))))) (defun compute-node (node) (case (setq node-inputs (node-inputs-signals node) input-signals (mapcar 'cadr node-inputs) node-function (get node 'function)) ('wire (car input-signals)) ('bit-not (function-node node node-function)) ('bit-ior (function-node node node-function)) ('bit-and (function-node node node-function)) ('bit-xor (function-node node node-function)) ('bit-nor (function-node node node-function)) ('dff (function-node node 'bit-xor)) (t (error (c+ "Uknown node function : " node-function))) )) (defun clear-unknowns (unknowns) (loop for node in unknowns do (setf (get node 'unknown-inputs) (get node 'inputs)))) (defun assign-knowns (knowns) (loop for k in knowns do (setq node (car k) signals (cdr k)) (loop for s in signals do (set-node-value node (car s) (cadr s))))) (defun assign-signal (target-name target-input-label out-signal) (set-node-value target-name target-input-label out-signal) (setf (get target-name 'unknown-inputs) (remove target-input-label target-unknowns))) (defun solve (knowns unknowns) (clear-unknowns unknowns) (assign-knowns knowns) (do ((node-order '())) ((endp knowns) node-order) (setq node-cell (pop knowns) node (car node-cell) outputs (get node 'outputs)) (append! node-order (list node)) (loop for out-label in outputs do (setq out-signal (get-node-value node out-label) target-node (get node out-label) target-name (car target-node) target-input-label (cdr target-node) target-unknowns (get target-name 'unknown-inputs)) (if target-node (progn (assign-signal target-name target-input-label out-signal) (if (null (get target-name 'unknown-inputs)) (progn (setq new-outputs (compute-node target-name)) (if (connected-output? target-name) (append! knowns (list (append (list target-name) new-outputs)))))) ))))) ;;;;;;;;;;;;;;;;; (defun generate-diagram () (asdf:run-shell-command "node netlistsvg/bin/netlistsvg res/netlist.json -o circuit_out.svg --skin netlistsvg/lib/light_default.svg &")) (defun write-netlist-file (netlist) (with-open-file (str "res/netlist.json" :direction :output :if-exists :supersede :if-does-not-exist :create) (format str (netlist-json netlist)))) (defun netlist-json-ports (ports) (append '("ports" :obj) (loop for p in ports collect `(,(car p) :obj ("direction" . ,(cadr p)) ("bits" . (,(caddr p))))))) (defun netlist-json-cells (cells) (append '("cells" :obj) (loop for c in cells collect `(,(car c) :obj ("type" . ,(cadr c)) ,(append '("port_directions" :obj) (caddr c)) ,(append '("connections" :obj) (cadddr c)) )))) (defun netlist-bits-field (node io-label) (if (member io-label (get node 'inputs)) (destructuring-bind (input-node . input-label) (get node io-label) (cadr (assoc input-label (get input-node 'label-ids)))) (cadr (assoc io-label (get node 'label-ids))))) (defun netlist-cell-type (node) "values are derived from the yosys netlist json format for cells, inputs to each cell with logic types (and, or, etc) in the json netlist format require A,B,C... inputs and Y output" (case (get node 'function) ('bit-ior "$or") ('bit-not "$not") ('bit-and "$and") ('bit-xor "$xor") ('bit-nor "$nor") ('add "$add") ('sub "$sub") ('equal"$eq") ('dff "$dff") ('mux "$mux") ('pmux "$pmux") (t (symbol-name n)))) (defun build-netlist (nodes port-nodes) (setq ports '() cells '()) (loop for n in nodes do (if (member n port-nodes) (push `(,(symbol-name n) "input" ,(loop for i in (get n 'outputs) collect (netlist-bits-field n i))) ports) (push `(,(symbol-name n) ,(netlist-cell-type n) ,(append (loop for i in (get n 'inputs) collect `(,(symbol-name i) "input")) (loop for i in (get n 'outputs) collect `(,(symbol-name i) "output"))) ,(append (loop for i in (append (get n 'inputs) (get n 'outputs)) collect `(,(symbol-name i) (,(netlist-bits-field n i)))))) cells))) (list ports cells)) (defun netlist-json (netlist) (jsown:to-json `(:obj ("modules" :obj ("ModuleName" :obj ,(netlist-json-ports (car netlist)) ,(netlist-json-cells (cadr netlist)) ))))) ;; Sample Simulation (defun test-simulate () (break) (setq *label-counter* 1 nodes (list (node 'A 'wire '() '(X Y)) (node 'B 'wire '() '(X Y)) (node 'I0 'wire '() '(X Y)) (node 'I1 'wire '() '(X)) (node 'C 'bit-nor '(A B) '(Y)) (node 'D 'bit-ior '(A B C) '(Y)) (node 'E 'bit-not '(A) '(Y)) (node 'F 'bit-xor '(A B) '(Y)) (node 'G 'bit-and '(A B) '(Y)) )) (co A 'X C 'A) (co A 'Y D 'C) (co B 'X C 'B) (co B 'Y E 'A) (co I0 'X D 'A) (co I0 'Y G 'B) (co I1 'X G 'A) (co C 'Y D 'B) (co D 'Y F 'A) (co E 'Y F 'B) (setq knowns '((A (X #*0) (Y #*0)) (B (X #*0) (Y #*0)) (I0 (X #*1) (Y #*0)) (I1 (X #*1))) unknowns (diff nodes (mapcar 'car knowns))) (solve knowns unknowns) (display-outputs nodes) (write-netlist-file (build-netlist nodes '(A B I0 I1))) (generate-diagram) )
8,076
Common Lisp
.lisp
257
26.941634
184
0.615454
olewhalehunter/cl-digital
1
0
0
AGPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a20d7a6e785dd005c7195b297d413fd98e5a71d805b86572d9ffc42a754827fd
26,937
[ -1 ]
26,969
osc-package.lisp
zzkt_osc-devices/osc-package.lisp
(defpackage :osc (:use :cl) (:documentation "OSC, the 'Open Sound Control' protocol.") (:export #:make-message #:message #:make-bundle #:bundle #:format-osc-data #:command #:args #:timetag #:elements #:encode-message #:encode-bundle #:decode-message #:decode-bundle #:make-osc-tree #:dp-register #:dp-remove #:dp-match #:dispatch ;; osc-time #:get-current-timetag #:timetag+ #:get-unix-time #:unix-time->timetag #:timetag->unix-time #:print-as-double ;; osc-devices #:osc-transmitter #:osc-transmitter-udp #:osc-client #:osc-client-udp #:osc-client-tcp #:osc-server #:osc-server-udp #:osc-server-tcp #:protocol #:name #:buffer-size #:quit #:osc-device-cleanup ;; listening #:make-listening-thread ;; dispatching #:add-osc-responder #:remove-osc-responder ;; transmitters #:make-osc-transmitter #:connect #:send #:send-msg #:send-bundle #:send-to #:send-msg-to #:send-bundle-to #:send-all #:send-msg-all #:send-bundle-all ;; clients #:make-osc-client #:make-client-responders #:register ;; servers #:make-osc-server #:boot #:make-server-responders #:register-udp-client #:unregister-udp-client #:register-tcp-client #:unregister-tcp-client #:post-register-hook #:get-tcp-client #:print-clients #:send-to-client #:send-bundle-to-client ;; sockets #:*default-osc-buffer-size* #:make-name-string #:device-active-p #:device-socket-name #:address #:port #:peer-address #:peer-port #:run-tests))
1,620
Common Lisp
.lisp
87
14.965517
60
0.650359
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
1f662526557e05d10918383c0a622d46401d93f86f3b6e3d230b24ca7188b9be
26,969
[ -1 ]
26,970
package.lisp
zzkt_osc-devices/package.lisp
(defpackage :osc (:use :cl) (:documentation "OSC, the 'Open Sound Control' protocol.") (:export #:make-message #:message #:make-bundle #:bundle #:format-osc-data #:command #:args #:timetag #:elements #:encode-message #:encode-bundle #:decode-message #:decode-bundle #:make-osc-tree #:dp-register #:dp-remove #:dp-match #:dispatch #:get-current-timetag ; osc-time #:timetag+ #:get-unix-time #:unix-time->timetag #:timetag->unix-time #:print-as-double #:osc-transmitter ; osc-devices #:osc-transmitter-udp #:osc-client #:osc-client-udp #:osc-client-tcp #:osc-server #:osc-server-udp #:osc-server-tcp #:protocol #:name #:buffer-size #:quit #:osc-device-cleanup #:make-listening-thread ; listening #:add-osc-responder ; dispatching #:remove-osc-responder #:make-osc-transmitter ; transmitters #:connect #:send #:send-msg #:send-bundle #:send-to #:send-msg-to #:send-bundle-to #:send-all #:send-msg-all #:send-bundle-all #:make-osc-client ; clients #:make-client-responders #:register #:make-osc-server ; servers #:boot #:make-server-responders #:register-udp-client #:unregister-udp-client #:register-tcp-client #:unregister-tcp-client #:post-register-hook #:get-tcp-client #:print-clients #:send-to-client #:send-bundle-to-client #:*default-osc-buffer-size* ; sockets #:make-name-string #:device-active-p #:device-socket-name #:address #:port #:peer-address #:peer-port #:run-tests))
1,707
Common Lisp
.lisp
79
17.658228
60
0.613161
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
f661be4d364e83f86630ace3116dce88b5ff2cd04217518d42c30db62bd15078
26,970
[ -1 ]
26,971
osc-tests.lisp
zzkt_osc-devices/osc-tests.lisp
;; -*- mode: lisp -*- ;; ;; Quick and dirty tests for cl-osc ;; ;; You are granted the rights to distribute and use this software ;; as governed by the terms of GNU Public License (aka the GPL) ;; see the LICENCE file. ;; Authors ;; - nik gaffney <[email protected]> (in-package :osc) #+sbcl (require 'sb-bsd-sockets) #+sbcl (defun osc-write () "a basic test function which sends various osc stuff on port 5555" (let ((sock (sb-bsd-sockets::make-instance 'inet-socket :type :datagram :protocol :udp))) (sb-bsd-sockets::socket-connect sock #(127 0 0 1) 5555) (let ((stream (sb-bsd-sockets::socket-make-stream sock :input t :output t :element-type '(unsigned-byte 8) :buffering :full))) (prin1 "int? ") (write-sequence (oti) stream) (force-output stream) (prin1 "float? ") (write-sequence (otf) stream) (force-output stream) (prin1 "string?") (write-sequence (ots) stream) (force-output stream) (prin1 "mutliple args?") (write-sequence (otm) stream) (force-output stream) (sb-bsd-sockets::socket-close sock) ))) (defun oti () (osc:encode-message "/test/int" 3)) (defun otf () (osc:encode-message "/test/float" 4.337)) (defun ots () (osc:encode-message "/test/string" "wonky_stringpuk")) (defun otbl () (osc:encode-message "/test/blob" #(0 0 0 0 0 0 0 0 0 0 0 0 0 0))) (defun otm () (osc:encode-message "/test/multi 5.78 1" "five point seven eight" "and one")) (defun otbn () (osc-encode-bundle (osc-make-test-bundle))) ;; test todo ;; - negative floats ;; - bignums ;; - blobs, and long args ;; - byte aligning 0,1,2,3,4 mod ;; - error catching, junk data (defun osc-test () (format t "some osc tests: ~a" (list (osc-t2) (osc-t4) (osc-t5) (osc-t6) (osc-t7) (osc-t8) (osc-t9) (osc-t10) (osc-t11) (osc-t12) (osc-t13))) T) (defun osc-t2 () (equalp '("/dip/lop" 666) (osc:decode-message #(47 100 105 112 47 108 111 112 0 0 0 0 44 105 0 0 0 0 2 154)))) ;; (defun osc-t3 () ;; (equalp '#(0 0 0 3 116 101 115 116 0 0 0 0 0 0 0 2 0 0 0 1 64 159 92 41) ;; (osc::encode-data '(3 "test" 2 1 4.98)))) (defun osc-t4 () (equalp #(44 105 115 102 0 0 0 0) (osc::encode-typetags '(1 "terrr" 3.4)))) (defun osc-t5 () (equalp #(44 105 105 102 0 0 0 0) (osc::encode-typetags '(1 2 3.3)))) (defun osc-t6 () (equal '("/test/one" 1 2 3.3) (osc:decode-message #(47 116 101 115 116 47 111 110 101 0 0 0 44 105 105 102 0 0 0 0 0 0 0 1 0 0 0 2 64 83 51 51)))) ;; (defun osc-t7 () ;; (equalp '(#(0 0 0 0 0 0 0 1) ("/voices/0/tm/start" 0.0) ;; ("/foo/stringmessage" "a" "few" "strings") ("/documentation/all-messages")) ;; (osc:decode-bundle ;; #(#x23 #x62 #x75 #x6e ;; #x64 #x6c #x65 0 ;; 0 0 0 0 ;; 0 0 0 #x1 ;; 0 0 0 #x20 ;; #x2f #x64 #x6f #x63 ;; #x75 #x6d #x65 #x6e ;; #x74 #x61 #x74 #x69 ;; #x6f #x6e #x2f #x61 ;; #x6c #x6c #x2d #x6d ;; #x65 #x73 #x73 #x61 ;; #x67 #x65 #x73 0 ;; #x2c 0 0 0 ;; 0 0 0 #x2c ;; #x2f #x66 #x6f #x6f ;; #x2f #x73 #x74 #x72 ;; #x69 #x6e #x67 #x6d ;; #x65 #x73 #x73 #x61 ;; #x67 #x65 0 0 ;; #x2c #x73 #x73 #x73 ;; 0 0 0 0 ;; #x61 0 0 0 ;; #x66 #x65 #x77 0 ;; #x73 #x74 #x72 #x69 ;; #x6e #x67 #x73 0 ;; 0 0 0 #x1c ;; #x2f #x76 #x6f #x69 ;; #x63 #x65 #x73 #x2f ;; #x30 #x2f #x74 #x6d ;; #x2f #x73 #x74 #x61 ;; #x72 #x74 0 0 ;; #x2c #x66 0 0 ;; 0 0 0 0)))) (defun osc-t8 () (equalp (osc:encode-message "/blob/x" #(1 2 3 4 5 6 7 8 9)) #(47 98 108 111 98 47 120 0 44 98 0 0 0 0 0 9 1 2 3 4 5 6 7 8 9 0 0 0))) (defun osc-t9 () (equalp '("/blob/x" #(1 2 3 4 5 6 7 8 9)) (osc:decode-message #(47 98 108 111 98 47 120 0 44 98 0 0 0 0 0 9 1 2 3 4 5 6 7 8 9 0 0 0)))) (defun osc-t10 () (equalp '("/t/x" #(1 29 32 43 54 66 78 81) 2 "lop") (osc:decode-message #(47 116 47 120 0 0 0 0 44 98 105 115 0 0 0 0 0 0 0 8 1 29 32 43 54 66 78 81 0 0 0 2 108 111 112 0)))) (defun osc-t11 () (equalp '(#(0 0 0 0 0 0 0 1) ("/string/a/ling" "slink" "slonk" "slank") ("/we/wo/w" 1 2 3.4) ("/blob" #(1 29 32 43 54 66 78 81 90) "lop" -0.44)) (osc:decode-bundle #(35 98 117 110 100 108 101 0 0 0 0 0 0 0 0 1 0 0 0 40 47 98 108 111 98 0 0 0 44 98 115 102 0 0 0 0 0 0 0 9 1 29 32 43 54 66 78 81 90 0 0 0 108 111 112 0 190 225 71 174 0 0 0 32 47 119 101 47 119 111 47 119 0 0 0 0 44 105 105 102 0 0 0 0 0 0 0 1 0 0 0 2 64 89 153 154 0 0 0 48 47 115 116 114 105 110 103 47 97 47 108 105 110 103 0 0 44 115 115 115 0 0 0 0 115 108 105 110 107 0 0 0 115 108 111 110 107 0 0 0 115 108 97 110 107 0 0 0)))) #+sbcl (defun osc-read (port) "a basic test function which attempts to decode osc stuff on PORT." (let ((s (make-instance 'inet-socket :type :datagram :protocol (get-protocol-by-name "udp"))) (buffer (make-sequence '(vector (unsigned-byte 8)) 512))) (format t "Socket type is ~A on port ~A~%" (sockopt-type s) port) (socket-bind s #(127 0 0 1) port) (socket-receive s buffer nil :waitall t) (socket-close s) (osc:decode-message buffer) )) ;;(osc-decode-message data) (defun osc-ft () (and (eql (osc::DECODE-FLOAT32 #(63 84 32 93)) 0.8286188) (eql (osc::DECODE-FLOAT32 #(190 124 183 78)) -0.246793))) ;; equalp but not eql (defun osc-t12 () (equalp (osc:encode-message "/asdasd" 3.6 4.5) #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0))) ;; equal but not eql (defun osc-t13 () (equal (osc:decode-message #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)) (list "/asdasd" 3.6 4.5))) ;; not symmetrical? how much of a problem is this? (defun osc-asym-t1 () "this test will fail" (osc:decode-message (osc:encode-message (osc:decode-message #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0))))) (defun osc-asym-t2 () "testing the assumptions about representations of messages" (setf packed-msg #(47 97 115 100 97 115 100 0 44 102 102 0 64 102 102 102 64 144 0 0)) (setf cons-msg (osc:decode-message packed-msg)) (osc:encode-message (values-list cons-msg))) #| sc3 server 32 byte message: 2f (/) 6e (n) 5f (_) 73 (s) 65 (e) 74 (t) 0 () 0 () 2c (,) 69 (i) 73 (s) 66 (f) 0 () 0 () 0 () 0 () 0 () 0 () 1 () fffffff6 (?) 66 (f) 72 (r) 65 (e) 71 (q) 0 () 0 () 0 () 0 () 3f (?) ffffff80 (?) 0 () 0 () /n_set 502 "freq" 1.000000 |# (defun run-tests () (osc-test))
7,246
Common Lisp
.lisp
183
34.934426
125
0.528876
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
78b288274a3a4748b57a5571ef8c3ca02a487819bbc72b8117a6475d8de769d7
26,971
[ -1 ]
26,972
osc-time.lisp
zzkt_osc-devices/osc-time.lisp
(in-package #:osc) (defconstant +unix-epoch+ (encode-universal-time 0 0 0 1 1 1970 0)) (defconstant +2^32+ (expt 2 32)) (defconstant +2^32/million+ (/ +2^32+ (expt 10 6))) (defconstant +usecs+ (expt 10 6)) (deftype timetag () '(unsigned-byte 64)) (defun timetagp (object) (typep object 'timetag)) (defun unix-secs+usecs->timetag (secs usecs) (let ((sec-offset (+ secs +unix-epoch+))) ; Seconds from 1900. (setf sec-offset (ash sec-offset 32)) ; Make seconds the top 32 ; bits. (let ((usec-offset (round (* usecs +2^32/MILLION+)))) ; Fractional part. (the timetag (+ sec-offset usec-offset))))) (defun get-current-timetag () "Returns a fixed-point 64 bit NTP-style timetag, where the top 32 bits represent seconds since midnight 19000101, and the bottom 32 bits represent the fractional parts of a second." #+sbcl (multiple-value-bind (secs usecs) (sb-ext:get-time-of-day) (the timetag (unix-secs+usecs->timetag secs usecs))) #-sbcl (error "Can't encode timetags using this implementation.")) (defun timetag+ (original seconds-offset) (declare (type timetag original)) (let ((offset (round (* seconds-offset +2^32+)))) (the timetag (+ original offset)))) ;;;===================================================================== ;;; Functions for using double-float unix timestamps. ;;;===================================================================== (defun get-unix-time () "Returns a a double-float representing real-time now in seconds, with microsecond precision, relative to 19700101." #+sbcl (multiple-value-bind (secs usecs) (sb-ext:get-time-of-day) (the double-float (+ secs (microseconds->subsecs usecs)))) #-sbcl (error "Can't encode timetags using this implementation.")) (defun unix-time->timetag (unix-time) (multiple-value-bind (secs subsecs) (floor unix-time) (the timetag (unix-secs+usecs->timetag secs (subsecs->microseconds subsecs))))) (defun timetag->unix-time (timetag) (if (= timetag 1) 1 ; immediate timetag (let* ((secs (ash timetag -32)) (subsec-int32 (- timetag (ash secs 32)))) (the double-float (+ (- secs +unix-epoch+) (int32->subsecs subsec-int32)))))) (defun microseconds->subsecs (usecs) (declare (type (integer 0 1000000) usecs)) (coerce (/ usecs +usecs+) 'double-float)) (defun subsecs->microseconds (subsecs) (declare (type (float 0 1) subsecs)) (round (* subsecs +usecs+))) (defun int32->subsecs (int32) "This maps a 32 bit integer, representing subsecond time, to a double float in the range 0-1." (declare (type (unsigned-byte 32) int32)) (coerce (/ int32 +2^32+) 'double-float)) (defun print-as-double (time) (format t "~%~F" (coerce time 'double-float)) time)
2,932
Common Lisp
.lisp
64
40.21875
72
0.61409
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
e6590682396a3fe83bf5d0e0eecd87806a70a13ecbf9f0b2d85e9ca3e3f4e172
26,972
[ -1 ]
26,973
osc-dispatch.lisp
zzkt_osc-devices/osc-dispatch.lisp
;; -*- mode: lisp -*- ;; ;; patern matching and dispatching for OSC messages ;; ;; copyright (C) 2004 FoAM vzw ;; ;; You are granted the rights to distribute and use this software ;; under the terms of the Lisp Lesser GNU Public License, known ;; as the LLGPL. The LLGPL consists of a preamble and the LGPL. ;; Where these conflict, the preamble takes precedence. The LLGPL ;; is available online at http://opensource.franz.com/preamble.html ;; and is distributed with this code (see: LICENCE and LGPL files) ;; ;; authors ;; - nik gaffney <[email protected]> ;; requirements ;; - not too useful without osc ;; - probably cl-pcre for matching (when it happens). ;; commentary ;; an osc de-/re -mungulator which should deal with piping data ;; from incoming messages to the function/handler/method ;; designated by the osc-address. ;; ;; NOTE: only does direct matches for now, no pattern globs, ;; with single function per uri ;; changes ;; 2005-02-27 18:31:01 ;; - initial version (in-package :osc) ;; should probably be a clos object or an alist. ;; for now, a hash table is enuf. (defun make-osc-tree () (make-hash-table :test 'equalp)) ;;; ;; ;;;;;; ; ; ; ; ;; ;; register/delete and dispatch. .. ;; ;;;; ; ; ; ;; (defun dp-register (tree address function) "Registers a function to respond to incoming osc messages. Since only one function should be associated with an address, any previous registration will be overwritten." (setf (gethash address tree) function)) (defun dp-remove (tree address) "Removes the function associated with the given address." (remhash address tree)) (defun dp-match (tree pattern) "Returns a list of functions which are registered for dispatch for a given address pattern." (list (gethash pattern tree))) (defgeneric dispatch (tree data device address port &optional timetag parent-bundle)) (defmethod dispatch (tree (data message) device address port &optional timetag parent-bundle) "Calls the function(s) matching the address(pattern) in the osc message passing the message object, the recieving device, and optionally in the case where a message is part of a bundle, the timetag of the bundle and the enclosing bundle." (let ((pattern (command data))) (dolist (x (dp-match tree pattern)) (unless (eq x NIL) (funcall x (command data) (args data) device address port timetag parent-bundle))))) (defmethod dispatch (tree (data bundle) device address port &optional timetag parent-bundle) "Dispatches each bundle element in sequence." (declare (ignore timetag parent-bundle)) (dolist (element (elements data)) (dispatch tree element device address port (timetag data) data)))
3,027
Common Lisp
.lisp
72
35.541667
77
0.655102
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
45af2cd946cc0e3705c8688de34bf6027213142a2c743aec240dcbaae11f294d
26,973
[ -1 ]
26,974
osc.lisp
zzkt_osc-devices/osc.lisp
;;; -*- mode: lisp -*- ;;; ;;; an implementation of the OSC (Open Sound Control) protocol ;;; ;;; copyright (C) 2004, 2023 FoAM o√º ;;; ;;; You are granted the rights to distribute and use this software ;;; under the terms of the Lisp Lesser GNU Public License, known ;;; as the LLGPL. The LLGPL consists of a preamble and the LGPL. ;;; Where these conflict, the preamble takes precedence. The LLGPL ;;; is available online at http://opensource.franz.com/preamble.html ;;; and is distributed with this code (see: LICENCE and LGPL files) ;;; ;;; authors ;;; ;;; nik gaffney <[email protected]> ;;; ;;; requirements ;;; ;;; dependent on sbcl, cmucl or openmcl for float encoding, other suggestions ;;; welcome. ;;; ;;; commentary ;;; ;;; this is a partial implementation of the OSC protocol which is used ;;; for communication mostly amongst music programs and their attached ;;; musicians. eg. sc3, max/pd, reaktor/traktorska etc+. more details ;;; of the protocol can be found at the open sound control pages -=> ;;; http://www.cnmat.berkeley.edu/OpenSoundControl/ ;;; ;;; ;;; known BUGS/Issues ;;; - encoding an unbound :symbol (or without symbol-value) will cause an error ;;; - malformed input -> exception ;;; - unknown types are sent as 'blobs' which may or may not be an issue ;;; - see the README file for more details... (in-package :osc) ;;(declaim (optimize (speed 3) (safety 1) (debug 3))) (defparameter *debug* 0 "Set debug verbosity for core library functions. Currently levels are 0-3.") ;;;;;; ; ;; ; ; ; ; ; ; ; ;; ;; eNcoding OSC messages ;; ;;;; ;; ;; ; ; ;; ; ; ; ; (defgeneric encode-osc-data (data)) (defmethod encode-osc-data ((data message)) "Encode an osc message with the given address and args." (with-slots (command args) data (concatenate '(vector (unsigned-byte 8)) (encode-address command) (encode-typetags args) (encode-args args)))) (defmethod encode-osc-data ((data bundle)) "Encode an osc bundle. A bundle contains a timetag (symbol or 64bit int) and a list of message or nested bundle elements." (with-slots (timetag elements) data (cat '(35 98 117 110 100 108 101 0) ; #bundle (if timetag (encode-timetag timetag) (encode-timetag :now)) (apply #'cat (mapcar #'encode-bundle-elt elements))))) ;; for backwards compatibility (defun encode-message (data message) (encode-osc-data data message)) (defun encode-bundle (data bundle) (encode-osc-data data bundle)) (defgeneric encode-bundle-elt (data)) (defmethod encode-bundle-elt ((data message)) (let ((bytes (encode-osc-data data))) (cat (encode-int32 (length bytes)) bytes))) (defmethod encode-bundle-elt ((data bundle)) (let ((bytes (encode-osc-data data))) (cat (encode-int32 (length bytes)) bytes))) (defun encode-address (address) (cat (map 'vector #'char-code address) (string-padding address))) (defun encode-typetags (data) "Create a typetag string suitable for the given data. Valid typetags according to the osc spec are ,i ,f ,s and ,b other extensions include ,{h|t|d|S|c|r|m|T|F|N|I|[|]} see the spec for more details. .. NOTE: currently handles the following tags i => #(105) => int32 f => #(102) => float s => #(115) => string b => #(98) => blob h => #(104) => int64 and considers non int/float/string data to be a blob." (let ((lump (make-array 0 :adjustable t :fill-pointer t))) (macrolet ((write-to-vector (char) `(vector-push-extend (char-code ,char) lump))) (write-to-vector #\,) (dolist (x data) (typecase x (integer (if (>= x 4294967296) (write-to-vector #\h) (write-to-vector #\i))) (float (write-to-vector #\f)) (simple-string (write-to-vector #\s)) (keyword (write-to-vector #\s)) (t (write-to-vector #\b))))) (cat lump (pad (padding-length (length lump)))))) (defun encode-args (args) "encodes ARGS in a format suitable for an OSC message" (let ((lump (make-array 0 :adjustable t :fill-pointer t))) (macrolet ((enc (f) `(setf lump (cat lump (,f x))))) (dolist (x args) (typecase x (integer (if (>= x 4294967296) (enc encode-int64) (enc encode-int32))) (float (enc encode-float32)) (simple-string (enc encode-string)) (t (enc encode-blob)))) lump))) ;;;;;; ; ;; ; ; ; ; ; ; ; ;; ;; decoding OSC messages ;; ;;; ;; ;; ; ; ; ; ; ; (defun bundle-p (buffer &optional (start 0)) "A bundle begins with '#bundle' (8 bytes). The start argument should index the beginning of a bundle in the buffer." (= 35 (elt buffer start))) (defun get-timetag (buffer &optional (start 0)) "Bytes 8-15 are the bundle timestamp. The start argument should index the beginning of a bundle in the buffer." (decode-timetag (subseq buffer (+ 8 start) (+ 16 start)))) (defun get-bundle-element-length (buffer &optional (start 16)) "Bytes 16-19 are the size of the bundle element. The start argument should index the beginning of the bundle element (length, content) pair in the buffer." (decode-int32 (subseq buffer start (+ 4 start)))) (defun get-bundle-element (buffer &optional (start 16)) "Bytes 20 to the length of the content (as defined by the preceding 4 bytes) are the content of the bundle. The start argument should index the beginning of the bundle element pair in the buffer." (let ((length (get-bundle-element-length buffer start))) (subseq buffer (+ 4 start) (+ (+ 4 start) (+ length))))) (defun split-sequence-by-n (sequence n) (loop :with length := (length sequence) :for start :from 0 :by n :below length :collecting (coerce (subseq sequence start (min length (+ start n))) 'list))) (defun print-buffer (buffer &optional (n 8)) (format t "~%~{~{ ~5d~}~%~}Total: ~a bytes~2%" (split-sequence-by-n buffer n) (length buffer))) (defun decode-bundle (buffer &key (start 0) end) "Decode an osc bundle/message into a bundle/message object. Bundles comprise an osc-timetag and a list of elements, which may be messages or bundles recursively. An optional end argument can be supplied (i.e. the length value returned by socket-receive, or the element length in the case of nested bundles), otherwise the entire buffer is decoded. If you are reusing buffers, you are responsible for ensuring that the buffer does not contain stale data." (unless end (setf end (- (length buffer) start))) (when (>= *debug* 2) (format t "~%Buffer start: ~a end: ~a~%" start end) (print-buffer (subseq buffer start end))) (if (bundle-p buffer start) ;; Bundle (let ((timetag (get-timetag buffer start))) (incf start (+ 8 8)) ; #bundle, timetag bytes (loop while (< start end) for element-length = (get-bundle-element-length buffer start) do (incf start 4) ; length bytes when (>= *debug* 1) do (format t "~&Bundle element length: ~a~%" element-length) collect (decode-bundle buffer :start start :end (+ start element-length)) into elements do (incf start (+ element-length)) finally (return (values (make-bundle timetag elements) timetag)))) ;; Message (let ((message (decode-message (subseq buffer start (+ start end))))) (make-message (car message) (cdr message))))) (defun decode-message (message) "Decode an osc message to an (address . data) pair." (declare (type (vector *) message)) (let ((x (position (char-code #\,) message))) (if (eq x nil) (format t "Message contains no data.. ") (cons (decode-address (subseq message 0 x)) (decode-taged-data (subseq message x)))))) (defun decode-address (address) (coerce (map 'vector #'code-char (delete 0 address)) 'string)) (defun decode-taged-data (data) "Decode data encoded with typetags. NOTE: currently handles the following tags i => #(105) => int32 f => #(102) => float s => #(115) => string b => #(98) => blob h => #(104) => int64" (let ((div (position 0 data))) (let ((tags (subseq data 1 div)) (acc (subseq data (padded-length div))) (result '())) (map 'vector #'(lambda (x) (cond ((eq x (char-code #\i)) (push (decode-int32 (subseq acc 0 4)) result) (setf acc (subseq acc 4))) ((eq x (char-code #\h)) (push (decode-uint64 (subseq acc 0 8)) result) (setf acc (subseq acc 8))) ((eq x (char-code #\f)) (push (decode-float32 (subseq acc 0 4)) result) (setf acc (subseq acc 4))) ((eq x (char-code #\s)) (let ((pointer (padded-length (position 0 acc)))) (push (decode-string (subseq acc 0 pointer)) result) (setf acc (subseq acc pointer)))) ((eq x (char-code #\b)) (let* ((size (decode-int32 (subseq acc 0 4))) (bl (+ 4 size)) (end (+ bl (mod (- 4 bl) 4)))) ;; NOTE: cannot use (padded-length bl), as it is not the same algorithm. ;; Blobs of 4, 8, 12 etc bytes should not be padded! (push (decode-blob (subseq acc 0 end)) result) (setf acc (subseq acc end)))) (t (error "Unrecognised typetag ~a" x)))) tags) (nreverse result)))) ;;;;;; ;; ;; ; ; ; ; ; ;; ; ;; ;; timetags ;; ;; - timetags can be encoded using a value, or the :now and :time ;; keywords. the keywords enable either a tag indicating 'immediate' ;; execution, or a tag containing the current time (which will most ;; likely be in the past of any receiver) to be created. ;; ;; - see this c.l.l thread to sync universal-time and internal-time ;; http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/c207fef63a78d720/adc7442d2e4de5a0?lnk=gst&q=internal-real-time-sync&rnum=1#adc7442d2e4de5a0 ;; - In SBCL, using sb-ext:get-time-of-day to get accurate seconds and ;; microseconds from OS. ;; ;;;; ;; ; ; (defun encode-timetag (timetag) "From the spec: `Time tags are represented by a 64 bit fixed point number. The first 32 bits specify the number of seconds since midnight on January 1, 1900, and the last 32 bits specify fractional parts of a second to a precision of about 200 picoseconds. This is the representation used by Internet NTP timestamps'. For an 'instantaneous' timetag use (encode-timetag :now), and for a timetag with the current time use (encode-timetag :time)." (cond ((equalp timetag :now) ;; the 1 bit timetag will be interpreted as 'immediately' #(0 0 0 0 0 0 0 1)) ((equalp timetag :time) ;; encode timetag with current real time (encode-int64 (get-current-timetag))) ((timetagp timetag) ;; encode osc timetag (encode-int64 timetag)) (t (error "Argument given is not one of :now, :time, or timetagp.")))) (defun decode-timetag (timetag) "Return a 64 bit timetag from a vector of 8 bytes in network byte order." (if (equalp timetag #(0 0 0 0 0 0 0 1)) 1 ;; A timetag of 1 is defined as immediately. (decode-uint64 timetag))) ;;;;; ; ; ;; ;; ; ; ;; ;; dataformat en- de- cetera. ;; ;;; ;; ; ; ; ;; floats are encoded using implementation specific 'internals' which is not ;; particulaly portable, but 'works for now'. (defun encode-float32 (f) "Encode an ieee754 float as a 4 byte vector." #+sbcl (encode-int32 (sb-kernel:single-float-bits f)) #+cmucl (encode-int32 (kernel:single-float-bits f)) #+openmcl (encode-int32 (CCL::SINGLE-FLOAT-BITS f)) #+allegro (encode-int32 (multiple-value-bind (x y) (excl:single-float-to-shorts f) (+ (ash x 16) y))) #-(or sbcl cmucl openmcl allegro) (error "Can't encode floats using this implementation.")) (defun decode-float32 (s) "Decode an ieee754 float from a vector of 4 bytes in network byte order." #+sbcl (sb-kernel:make-single-float (decode-int32 s)) #+cmucl (kernel:make-single-float (decode-int32 s)) #+openmcl (CCL::HOST-SINGLE-FLOAT-FROM-UNSIGNED-BYTE-32 (decode-uint32 s)) #+allegro (excl:shorts-to-single-float (ldb (byte 16 16) (decode-int32 s)) (ldb (byte 16 0) (decode-int32 s))) #-(or sbcl cmucl openmcl allegro) (error "Can't decode floats using this implementation.")) (defmacro defint-decoder (num-of-octets &optional docstring) (let ((decoder-name (intern (format nil "~:@(decode-uint~)~D" (* 8 num-of-octets)))) (seq (gensym)) (int (gensym))) `(defun ,decoder-name (,seq) ,@(when docstring (list docstring)) (let* ((,int 0) ,@(loop for n below num-of-octets collect `(,int (dpb (aref ,seq ,n) (byte 8 (* 8 (- (1- ,num-of-octets) ,n))) ,int)))) ,int)))) (defun decode-uint32 (s) "4 byte -> 32 bit unsigned int" (let ((i (+ (ash (elt s 0) 24) (ash (elt s 1) 16) (ash (elt s 2) 8) (elt s 3)))) i)) (defmacro defint-encoder (num-of-octets &optional docstring) (let ((enc-name (intern (format nil "~:@(encode-int~)~D" (* 8 num-of-octets)))) (buf (gensym)) (int (gensym))) `(defun ,enc-name (,int) ,@(when docstring (list docstring)) (let ((,buf (make-array ,num-of-octets :element-type '(unsigned-byte 8)))) ,@(loop for n below num-of-octets collect `(setf (aref ,buf ,n) (ldb (byte 8 (* 8 (- (1- ,num-of-octets) ,n))) ,int))) ,buf)))) (defint-encoder 4 "Convert an integer into a sequence of 4 bytes in network byte order (32 bit).") (defint-encoder 8 "Convert an integer into a sequence of 8 bytes in network byte order (64 bit).") (defun decode-int32 (s) "4 byte -> 32 bit int -> two's complement (in network byte order)" (let ((i (decode-uint32 s))) (if (>= i #.(1- (expt 2 31))) (- (- #.(expt 2 32) i)) i))) (defun decode-int64 (s) "8 byte -> 64 bit int -> two's complement (in network byte order)" (let ((i (decode-uint64 s))) (if (>= i #.(1- (expt 2 63))) (- (- #.(expt 2 64) i)) i))) ;; osc-strings are unsigned bytes, padded to a 4 byte boundary (defun encode-string (string) "Encode a string as a vector of character-codes, padded to 4 byte boundary." (cat (map 'vector #'char-code string) (string-padding string))) (defun decode-string (data) "Convert a binary vector to a string and removes trailing #\nul characters." (string-trim '(#\nul) (coerce (map 'vector #'code-char data) 'string))) ;; blobs are binary data, consisting of a length (int32) and bytes which are ;; osc-padded to a 4 byte boundary. (defun encode-blob (blob) "Encode a blob from a given vector." (let ((bl (length blob))) (cat (encode-int32 bl) blob (pad (padding-length bl))))) (defun decode-blob (blob) "Decode a blob as a vector of unsigned bytes." (let ((size (decode-int32 (subseq blob 0 4)))) (subseq blob 4 (+ 4 size)))) ;; utility functions for osc-string/padding slonking (defun cat (&rest catatac) (apply #'concatenate '(vector (unsigned-byte 8)) catatac)) (defun padding-length (s) "Return the length of padding required for a given length of string." (declare (type fixnum s)) (- 4 (mod s 4))) (defun padded-length (s) "Return the length of an osc-string made from a given length of string." (declare (type fixnum s)) (+ s (- 4 (mod s 4)))) (defun string-padding (string) "Return the padding required for a given osc string." (declare (type simple-string string)) (pad (padding-length (length string)))) (defun pad (n) "Make a sequence of the required number of #\Nul characters." (declare (type fixnum n)) (make-array n :initial-element 0 :fill-pointer n)) (provide :osc) ;; end
16,964
Common Lisp
.lisp
398
35.507538
163
0.599418
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d32348ed642fdb03ed940b2e6cda55e0b888d5dbb5e58fac77817fe11df252a6
26,974
[ -1 ]
26,975
device.lisp
zzkt_osc-devices/devices/device.lisp
(cl:in-package #:osc) ;;;===================================================================== ;;; OSC device base class ;;;===================================================================== (defclass osc-device () ((socket :reader socket :writer set-socket :initform nil) (debug-mode :reader debug-mode :writer set-debug-mode :initarg :debug-mode) (cleanup-fun :reader cleanup-fun :initarg :cleanup-fun :initform nil))) ;;;===================================================================== ;;; OSC device mixin classes ;;;===================================================================== (defclass udp-device (osc-device) ()) (defclass tcp-device (osc-device) ()) (defclass listening-device (osc-device) ((listening-thread :reader listening-thread :writer set-listening-thread :initform nil))) (defclass receiving-device (listening-device) ((socket-buffer :reader socket-buffer :initarg :socket-buffer))) (defclass dispatching-device (listening-device) ((address-tree :reader address-tree :initarg :address-tree :initform (make-osc-tree)))) (defclass dispatching-device-udp (dispatching-device receiving-device udp-device) ()) ;;;===================================================================== ;;; OSC device abstract classes ;;;===================================================================== (defclass osc-transmitter (osc-device) ()) (defclass osc-client (dispatching-device receiving-device osc-transmitter) ()) (defclass osc-server (dispatching-device osc-transmitter) ((buffer-size :reader buffer-size :initarg :buffer-size) (clients :reader clients :initarg :clients :initform (make-clients-hash)))) (defclass osc-client-endpoint (osc-client) ((clients :reader clients :initarg :clients))) ;;;===================================================================== ;;; OSC device concrete classes ;;;===================================================================== (defclass osc-transmitter-udp (osc-transmitter udp-device) ()) (defclass osc-client-udp (osc-client dispatching-device-udp) ()) (defclass osc-client-tcp (osc-client tcp-device) ()) (defclass osc-server-udp (osc-server dispatching-device-udp osc-transmitter-udp) ()) (defclass osc-server-tcp (osc-server osc-transmitter tcp-device) ()) (defclass osc-client-endpoint-tcp (osc-client-endpoint osc-client-tcp) ()) ;;;===================================================================== ;;; Device generic functions ;;;===================================================================== (defgeneric protocol (osc-device) (:method ((osc-device udp-device)) :udp) (:method ((osc-device tcp-device)) :tcp)) (defgeneric name (osc-device) (:method ((osc-device osc-device)) (concatenate 'string (symbol-name (class-name (class-of osc-device))) "-" (make-name-string osc-device)))) (defmethod buffer-size ((osc-device dispatching-device)) (length (socket-buffer osc-device))) (defgeneric quit (osc-device)) (defgeneric osc-device-cleanup (device) (:method :before ((osc-device osc-device)) (when (cleanup-fun osc-device) (funcall (cleanup-fun osc-device) osc-device))) (:method ((osc-device osc-device)) (when (debug-mode osc-device) (format t "~%OSC device stopped: ~A~%" (name osc-device))) (when (socket osc-device) (handler-case (socket-close (socket osc-device) :abort t) (sb-int:simple-stream-error () (when (debug-mode osc-device) (warn "Device ~A gone away." (name osc-device))))) (set-socket nil osc-device))))
3,901
Common Lisp
.lisp
99
33.434343
72
0.528102
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
bddf42297177f481b1a0cbd4b790b89ae20dae44062d2512937a6a3448ed9ccb
26,975
[ -1 ]
26,976
server.lisp
zzkt_osc-devices/devices/server.lisp
(cl:in-package #:osc) (defun make-osc-server (&key (protocol :udp) debug-mode (buffer-size *default-osc-buffer-size*) cleanup-fun) (ecase protocol (:udp (make-instance 'osc-server-udp :debug-mode debug-mode :cleanup-fun cleanup-fun :buffer-size buffer-size :socket-buffer (make-socket-buffer buffer-size))) (:tcp (make-instance 'osc-server-tcp :debug-mode debug-mode :cleanup-fun cleanup-fun :buffer-size buffer-size)))) (defgeneric boot (osc-server port)) (defmethod boot :around ((server osc-server) port) (if (device-active-p server) (warn "~%Server ~A already running" (machine-instance))) (set-socket (make-socket (protocol server)) server) (socket-bind (socket server) #(0 0 0 0) port) (call-next-method) (format t "~%Server ~A listening on port ~A~%" (machine-instance) port)) (defmethod boot ((server osc-server-udp) port) (declare (ignore port)) "UDP server sockets are used for receiving and unconnected sending." (set-listening-thread (make-listening-thread server) server)) (defmethod boot ((server osc-server-tcp) port) (declare (ignore port)) (set-listening-thread (sb-thread:make-thread (lambda () (unwind-protect (progn (socket-listen (socket server) 10) (loop for socket = (socket-accept (socket server)) for endpoint = (make-osc-client-endpoint-tcp socket (debug-mode server) (buffer-size server) (address-tree server) (clients server) (make-unregister-self-fun server)) do (register-tcp-client server endpoint))) (osc-device-cleanup server))) :name (format nil "osc-server-tcp: ~A" (name server))) server) server) (defmethod osc-device-cleanup ((device osc-server-udp)) (loop for client-name being the hash-key in (clients device) using (hash-value addr+port) do (notify-quit device client-name) do (unregister-udp-client device (first addr+port) (second addr+port))) (call-next-method)) (defmethod osc-device-cleanup ((device osc-server-tcp)) (loop for client being the hash-value in (clients device) do (quit client)) (call-next-method)) (defun make-clients-hash () (make-hash-table :test 'equal)) ;;;===================================================================== ;;; UDP server functions ;;;===================================================================== (defmethod initialize-instance :after ((server osc-server-udp) &key) (make-server-responders server)) (defgeneric make-server-responders (server)) (defmethod make-server-responders ((server osc-server-udp)) (add-osc-responder server "/cl-osc/register" (cmd args device address port timetag bundle) (let ((listening-port (car args))) ; Optional port for sending ; return messages. (register-udp-client device address (if listening-port listening-port port)))) (add-osc-responder server "/cl-osc/quit" (cmd args device address port timetag bundle) (unregister-udp-client device address port))) (defun register-udp-client (server addr port) (let ((client-name (make-addr+port-string addr port))) (format t "Client registered: ~A~%" client-name) (setf (gethash client-name (clients server)) (list addr port)) (post-register-hook server client-name))) (defun unregister-udp-client (server addr port) (let ((client-name (make-addr+port-string addr port))) (format t "Client quit: ~A~%" client-name) (remhash client-name (clients server)))) (defgeneric post-register-hook (server client-name) (:method ((server osc-server-udp) client-name) (format t "Post-register hook for client: ~A~%" client-name) (notify-registered server client-name))) (defun notify-registered (server client-name) (send-msg-to-client server client-name "/cl-osc/server/registered")) (defun notify-quit (server client-name) (send-msg-to-client server client-name "/cl-osc/server/quit")) ;;;===================================================================== ;;; TCP server functions ;;;===================================================================== (defun register-tcp-client (server transmitter) (setf (gethash (make-peername-string transmitter) (clients server)) transmitter)) (defun unregister-tcp-client (server transmitter) (remhash (make-peername-string transmitter) (clients server))) (defun make-unregister-self-fun (server) #'(lambda (client) (unregister-tcp-client server client))) (defun get-tcp-client (server socket-peername) (gethash socket-peername (clients server))) (defgeneric print-clients (server)) (defmethod print-clients ((server osc-server-udp)) (loop for addr+port being the hash-value in (clients server) for i from 1 do (format t "~A. Connected to: ~A~%" i (make-addr+port-string (first addr+port) (second addr+port))))) (defmethod print-clients ((server osc-server-tcp)) (loop for endpoint being the hash-value in (clients server) for i from 1 do (format t "~A. Connected to: ~A~%" i (make-addr+port-string (peer-address endpoint) (peer-port endpoint))))) ;;;===================================================================== ;;; Server sending functions ;;;===================================================================== ;; Send to a client (defgeneric send-to-client (server client-name data) (:method :around ((server osc-server) client-name data) (let ((client (gethash client-name (clients server)))) (if client (call-next-method server client data) (warn "No client called ~A~%" client-name))))) (defmethod send-to-client ((server osc-server-udp) client-name data) (send-to server (first client-name) (second client-name) data)) (defmethod send-to-client ((server osc-server-tcp) client data) (send client data)) (defgeneric send-msg-to-client (server client-name command &rest args) (:method ((server osc-server) client-name command &rest args) (let ((message (make-message command args))) (send-to-client server client-name message)))) (defgeneric send-bundle-to-client (server client-name timetag command &rest args) (:method ((server osc-server) client-name timetag command &rest args) (let ((bundle (bundle timetag (make-message command args)))) (send-to-client server client-name bundle)))) ;; Send all (defgeneric send-all (server data)) (defmethod send-all ((server osc-server-udp) data) (loop for addr+port being the hash-value in (clients server) do (send-to server (first addr+port) (second addr+port) data))) (defmethod send-all ((server osc-server-tcp) data) (loop for endpoint being the hash-value in (clients server) do (send endpoint data))) (defmethod send-all ((client-endpoint osc-client-endpoint) data) (loop for endpoint being the hash-value in (clients client-endpoint) ;; FIXME: Don't not reply to the sender in this case so that the ;; behaviour of send-all is uniform for both UDP and TCP. But ;; could be useful to have a means of broadcasting messages to ;; all clients of a server except the client that generated the ;; message. ;; ;; unless (eq endpoint client-endpoint) ; don't send to sender do (send endpoint data))) (defgeneric send-msg-all (server command &rest args) (:method ((server osc-server) command &rest args) (let ((message (make-message command args))) (send-all server message))) (:method ((client-endpoint osc-client-endpoint) command &rest args) (let ((message (make-message command args))) (send-all client-endpoint message)))) (defgeneric send-bundle-all (server timetag command &rest args) (:method ((server osc-server) timetag command &rest args) (let ((bundle (bundle timetag (make-message command args)))) (send-all server bundle))) (:method ((client-endpoint osc-client-endpoint) timetag command &rest args) (let ((bundle (bundle timetag (make-message command args)))) (send-all client-endpoint bundle))))
8,953
Common Lisp
.lisp
183
39.814208
74
0.601673
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
778672412003f802c47f24d87e04146572ef8b4518ddc72fb4831ac55679b871
26,976
[ -1 ]
26,977
listening-device.lisp
zzkt_osc-devices/devices/listening-device.lisp
(cl:in-package #:osc) (defgeneric make-listening-thread (listening-device)) (defmethod connect progn ((listening-device listening-device) host-port &key host-address host-name port) (declare (ignore host-port host-address host-name port)) (set-listening-thread (make-listening-thread listening-device) listening-device)) (defmethod quit ((device listening-device)) (sb-thread:terminate-thread (listening-thread device))) (defmethod osc-device-cleanup ((device listening-device)) (set-listening-thread nil device) (call-next-method)) (defmethod osc-device-cleanup ((device receiving-device)) (fill (socket-buffer device) 0) (call-next-method)) (defun print-osc-debug-msg (receiver data length address port timetag &optional (stream t)) (format stream "~&~a~%bytes rx:~a~a~%from:~a~a~a ~a~%timetag:~a~a~%unix-time:~a~f~%data:~a~a" (name receiver) #\Tab length #\Tab #\Tab address port #\Tab timetag #\Tab (when timetag (timetag->unix-time timetag)) #\Tab #\Tab) (format-osc-data data :stream stream) (format stream "~%"))
1,174
Common Lisp
.lisp
25
39.8
88
0.664917
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
fdedb6a97deb89f763946ea3afc9e360c92fb65de51aaac8da4007df3eb294b8
26,977
[ -1 ]
26,978
client.lisp
zzkt_osc-devices/devices/client.lisp
(cl:in-package #:osc) (defun make-osc-client (&key (protocol :udp) debug-mode (buffer-size *default-osc-buffer-size*) address-tree cleanup-fun) (ecase protocol (:udp (make-instance 'osc-client-udp :debug-mode debug-mode :socket-buffer (make-socket-buffer buffer-size) :address-tree (if address-tree address-tree (make-osc-tree)) :cleanup-fun cleanup-fun)) (:tcp (make-instance 'osc-client-tcp :debug-mode debug-mode :socket-buffer (make-socket-buffer buffer-size) :address-tree (if address-tree address-tree (make-osc-tree)) :cleanup-fun cleanup-fun)))) (defmethod initialize-instance :after ((client osc-client-udp) &key) (make-client-responders client)) (defgeneric make-client-responders (server)) (defmethod make-client-responders ((client osc-client-udp)) (add-osc-responder client "/cl-osc/server/registered" (cmd args device address port timetag bundle) (format t "Registered with server at ~A~%" (make-addr+port-string address port))) (add-osc-responder client "/cl-osc/server/quit" (cmd args device address port timetag bundle) (format t "Server ~A has quit~%" (make-addr+port-string address port)))) (defgeneric register (client) (:method ((client osc-client-udp)) (send-msg client "/cl-osc/register" (port client)))) (defmethod osc-device-cleanup ((device osc-client-udp)) (send-msg device "/cl-osc/quit") (call-next-method)) (defun make-osc-client-endpoint-tcp (socket debug-mode buffer-size address-tree clients &optional cleanup-fun) (socket-make-stream socket :input nil :output t :element-type '(unsigned-byte 8) :buffering :full) (let ((client (make-instance 'osc-client-endpoint-tcp :debug-mode debug-mode :address-tree address-tree :socket-buffer (make-socket-buffer buffer-size) :clients clients :cleanup-fun cleanup-fun))) (set-socket socket client) (set-listening-thread (make-listening-thread client) client) client)) (defmethod make-listening-thread ((receiver osc-client-tcp)) "Creates a listening thread for tcp clients." (sb-thread:make-thread (lambda () (unwind-protect (loop do (multiple-value-bind (buffer length address port) (socket-receive (socket receiver) (socket-buffer receiver) nil) (when (eq length 0) ; Closed by remote (sb-thread:terminate-thread sb-thread:*current-thread*)) (multiple-value-bind (data timetag) (decode-bundle buffer :end length) (when (debug-mode receiver) (print-osc-debug-msg receiver data length (peer-address receiver) (peer-port receiver) timetag)) (dispatch (address-tree receiver) data receiver address port)))) (osc-device-cleanup receiver))) :name (format nil "osc-client-tcp-connection: ~A~%" (name receiver))))
3,916
Common Lisp
.lisp
79
31.696203
73
0.511361
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
c916fc3ccce0b10ecf174829e53a2a318dca098fd7f33fa4b1ac11dc520c97b0
26,978
[ -1 ]
26,979
transmitter.lisp
zzkt_osc-devices/devices/transmitter.lisp
(cl:in-package #:osc) ;; Only UDP devices can be transmitters. (defun make-osc-transmitter (&key debug-mode cleanup-fun) (make-instance 'osc-transmitter-udp :debug-mode debug-mode :cleanup-fun cleanup-fun)) (defgeneric connect (osc-transmitter host-port &key host-address host-name port) (:method-combination progn :most-specific-last)) (defmethod connect progn ((transmitter osc-transmitter) host-port &key (host-address nil addr) (host-name "localhost" name) port) (when (and addr name) (error "Supplied both :host-address and :host-name to connect")) (cond (addr (when (typep host-address 'string) (setf host-address (sb-bsd-sockets:make-inet-address host-address)))) (t (setf host-address (sb-bsd-sockets:host-ent-address (sb-bsd-sockets:get-host-by-name host-name))))) (if (not (device-active-p transmitter)) (progn (let ((socket (make-socket (protocol transmitter)))) (if port (socket-bind socket #(127 0 0 1) port) (socket-bind socket)) (socket-connect socket host-address host-port) (socket-make-stream socket :input nil :output t :element-type '(unsigned-byte 8) :buffering :full) (set-socket socket transmitter)) (when (debug-mode transmitter) (format t "~%Device connected: ~A~%~A -> ~A~%" (name transmitter) #\Tab (make-addr+port-string (peer-address transmitter) (peer-port transmitter))))) (warn "Already connected")) transmitter) (defmethod quit ((transmitter osc-transmitter-udp)) (if (device-active-p transmitter) (osc-device-cleanup transmitter) (warn "Not connected: ~A" (name transmitter)))) ;;;===================================================================== ;;; Sending functions ;;;===================================================================== (defmacro osc-write-to-stream (stream &body msg) `(progn (write-sequence ,@msg ,stream) (finish-output ,stream))) (defgeneric send (transmitter data) (:method ((transmitter osc-transmitter) data) (let ((bytes (encode-osc-data data))) (osc-write-to-stream (slot-value (socket transmitter) 'stream) bytes)))) (defgeneric send-msg (transmitter command &rest args) (:method ((transmitter osc-transmitter) command &rest args) (let ((message (make-message command args))) (send transmitter message)))) (defgeneric send-bundle (transmitter timetag command &rest args) (:method ((transmitter osc-transmitter) timetag command &rest args) (let ((bundle (bundle timetag (make-message command args)))) (send transmitter bundle)))) ;; Unconnected sending (UDP only) (defgeneric send-to (transmitter address port data) (:method ((transmitter osc-transmitter-udp) address port data) (socket-send (socket transmitter) (encode-osc-data data) nil :address (list address port)))) (defgeneric send-msg-to (transmitter address port command &rest args) (:method ((transmitter osc-transmitter-udp) address port command &rest args) (let ((message (make-message command args))) (send-to transmitter address port message)))) (defgeneric send-bundle-to (transmitter address port timetag command &rest args) (:method ((transmitter osc-transmitter-udp) address port timetag command &rest args) (let ((bundle (bundle timetag (make-message command args)))) (send-to transmitter address port bundle))))
3,934
Common Lisp
.lisp
84
36.511905
72
0.589048
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
16e3efec45146f224d5f2d9226586fb60c445289e1590dea57a1ce93fb401b57
26,979
[ -1 ]
26,980
dispatching-device.lisp
zzkt_osc-devices/devices/dispatching-device.lisp
(cl:in-package #:osc) (defmethod make-listening-thread ((receiver dispatching-device-udp)) "Creates a listening thread for udp devices (client and server)." (sb-thread:make-thread (lambda () (unwind-protect (loop do (multiple-value-bind (buffer length address port) (socket-receive (socket receiver) (socket-buffer receiver) nil) (multiple-value-bind (data timetag) (osc:decode-bundle buffer :end length) (when (debug-mode receiver) (print-osc-debug-msg receiver data length address port timetag)) (dispatch (address-tree receiver) data receiver address port)))) (osc-device-cleanup receiver))) :name (format nil "osc-receiver-udp: ~A~%" (name receiver)))) ;;;===================================================================== ;;; OSC Responders ;;;===================================================================== (defmacro add-osc-responder (dispatcher cmd-name (cmd args device address port timetag bundle) &body body) `(dp-register (address-tree ,dispatcher) ,cmd-name (lambda (,cmd ,args ,device ,address ,port ,timetag ,bundle) (declare (ignorable ,cmd ,args ,device ,address ,port ,timetag ,bundle)) ,@body))) (defgeneric remove-osc-responder (dispatcher address) (:method ((dispatcher dispatching-device) address) (dp-remove (address-tree dispatcher) address)))
1,739
Common Lisp
.lisp
34
36.558824
74
0.503529
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
a648f21abec71a9005f2cef43b855f189a13263340bf0cb6c7b7686b04b6677d
26,980
[ -1 ]
26,981
osc-device-examples.lisp
zzkt_osc-devices/devices/examples/osc-device-examples.lisp
(cl:in-package #:osc) (ql:quickload "osc") ;;;===================================================================== ;;; OSC UDP transmitter -> server ;;;===================================================================== (defparameter *osc-server* (make-osc-server :protocol :udp :debug-mode t)) (boot *osc-server* 57127) (defparameter *osc-transmitter* (make-osc-transmitter :debug-mode t)) (connect *osc-transmitter* 57127 :host-name "localhost") (device-active-p *osc-transmitter*) (device-socket-name *osc-transmitter*) (address *osc-transmitter*) (port *osc-transmitter*) (device-socket-peername *osc-transmitter*) (peer-address *osc-transmitter*) (peer-port *osc-transmitter*) (send-msg *osc-transmitter* "/bar" 1 2 9) (send-bundle *osc-transmitter* :time ; current real time "/foo" 1 2 3) (send-bundle *osc-transmitter* :now ; immediately "/foo" 1 2 3) (send-bundle *osc-transmitter* (unix-time->timetag 1234567890.1234567d0) "/foo" 1 2 3) ;; The lower-level send function can be used to send message and ;; bundle objects directly. This allows more complex (nested) bundles ;; to be created. (send *osc-transmitter* (message "/foo" 1 2 3)) (send *osc-transmitter* (bundle :now (message "/foo" 1 2 3))) (let ((bundle (bundle :now (message "/foo" '(1 2 3)) (bundle :now (bundle :now (message "/bar" '(10 20 30))))))) (send *osc-transmitter* bundle)) (quit *osc-transmitter*) (quit *osc-server*) ;;;===================================================================== ;;; OSC UDP client <-> server ;;;===================================================================== (defparameter *osc-server* (make-osc-server :protocol :udp :debug-mode t)) (boot *osc-server* 57127) (defparameter *osc-client* (make-osc-client :protocol :udp :debug-mode t)) (connect *osc-client* 57127 :host-name "localhost") ;; A UDP server can't know about a client unless it registers. (print-clients *osc-server*) (register *osc-client*) (print-clients *osc-server*) (quit *osc-client*) ; quit notifies the server (print-clients *osc-server*) (connect *osc-client* 57127 :host-name "localhost") (send-msg *osc-client* "/foo" 2 99) (send-bundle *osc-client* (unix-time->timetag 1234567890.1234567d0) "/foo" 1 2 3) (send-bundle *osc-client* :now "/foo" 1) (send-bundle *osc-client* :time "/foo" 1) ;; Using the server as a transmitter. (send-msg-to *osc-server* (address *osc-client*) (port *osc-client*) "/bar" 1 2 3) (send-bundle-to *osc-server* (address *osc-client*) (port *osc-client*) :now "/bar" 1 2 3) ;; If a client is registered... (send-msg-to-client *osc-server* (make-name-string *osc-client*) "/bar" 2 99) (register *osc-client*) (send-msg-to-client *osc-server* (make-name-string *osc-client*) "/bar" 2 99) (send-bundle-to-client *osc-server* (make-name-string *osc-client*) :time "/bar" 2 99) (add-osc-responder *osc-server* "/echo-sum" (cmd args dev addr port timetag bundle) (send-msg-to dev addr port "/echo-answer" (apply #'+ args))) (add-osc-responder *osc-client* "/echo-answer" (cmd args dev addr port timetag bundle) (format t "Sum is ~a~%" (car args))) (send-msg *osc-client* "/echo-sum" 1 2 3 4) (add-osc-responder *osc-server* "/timetag+1" (cmd args dev addr port timetag bundle) (send-bundle-to dev addr port (timetag+ timetag 1) "/the-future")) (send-bundle *osc-client* (get-current-timetag) "/timetag+1") ;; Send a messages to all registered clients. (send-msg-all *osc-server* "/foo" 1 2 3) (send-bundle-all *osc-server* :now "/foo" 1 2 3) (defparameter *osc-client2* (make-osc-client :protocol :udp :debug-mode t)) (connect *osc-client2* 57127) (register *osc-client2*) (add-osc-responder *osc-server* "/echo-sum" (cmd args dev addr port timetag bundle) (send-msg-all dev "/echo-answer" (apply #'+ args))) (send-msg *osc-client* "/echo-sum" 1 2 3 4) (quit *osc-client*) (quit *osc-client2*) (quit *osc-server*) ;;;===================================================================== ;;; OSC TCP client <-> server ;;;===================================================================== (defparameter *osc-server* (make-osc-server :protocol :tcp :debug-mode t)) (boot *osc-server* 57127) (defparameter *osc-client* (make-osc-client :protocol :tcp :debug-mode t)) (connect *osc-client* 57127 :host-name "localhost") (device-active-p *osc-client*) (device-socket-name *osc-client*) (device-socket-peername *osc-client*) (send-msg *osc-client* "/foo" 1 2 3) (send-msg-to-client *osc-server* (make-name-string *osc-client*) "/foo" 1 2 3) (defparameter *osc-client2* (make-osc-client :protocol :tcp :debug-mode t)) (connect *osc-client2* 57127 :host-address "127.0.0.1" :port 57666) ; choose local port (device-socket-name *osc-client2*) (send-msg *osc-client2* "/bar" 4 5 6 9) (print-clients *osc-server*) (add-osc-responder *osc-server* "/print-sum" (cmd args dev addr port timetag bundle) (format t "Sum = ~A~%" (apply #'+ args))) (send-msg *osc-client2* "/print-sum" 4 5 6 9) (add-osc-responder *osc-server* "/echo-sum" (cmd args dev addr port timetag bundle) (send-msg dev cmd (apply #'+ args))) (send-msg *osc-client2* "/echo-sum" 4 5 6 9) (send-msg-all *osc-server* "/bar" 1 2 3) ; send to all peers (add-osc-responder *osc-server* "/echo-sum-all" (cmd args dev addr port timetag bundle) (send-msg-all dev cmd (apply #'+ args))) ; Send to all peers (including self). (send-msg *osc-client2* "/echo-sum-all" 1 2 3) (quit *osc-client*) (quit *osc-client2*) (quit *osc-server*) ;;;===================================================================== ;;; OSC UDP client <-> sclang ;;;===================================================================== (defparameter *osc-client* (make-osc-client :protocol :udp :debug-mode t)) (connect *osc-client* 57120 :host-name "localhost" :port 57127) (address *osc-client*) (port *osc-client*) (peer-address *osc-client*) (peer-port *osc-client*) ;;--------------------------------------------------------------------- ;; run in sc c=OSCresponder(nil, '/foo', {|t,r,msg,addr| [t,r,msg,addr].postln}).add ;;--------------------------------------------------------------------- (send-msg *osc-client* "/foo" 1 2 3) (send-bundle *osc-client* (get-current-timetag) "/foo" 3) (add-osc-responder *osc-client* "/echo-sum" (cmd args dev addr port timetag bundle) (send-msg dev cmd (apply #'+ args))) ;;--------------------------------------------------------------------- ;; Send /echo-sum from sc, and lisp returns the sum. n=NetAddr("localhost", 57127) e=OSCresponder(nil, '/echo-sum', {|t,r,msg,addr| [t,r,msg,addr].postln; }).add n.sendMsg('/echo-sum', 1, 2, 3) // send numbers, lisp returns sum. ;;--------------------------------------------------------------------- (quit *osc-client*) ;;;===================================================================== ;;; OSC UDP client <-> scsynth ;;;===================================================================== (defparameter *osc-client* (make-osc-client :protocol :udp :debug-mode t)) (connect *osc-client* 57110 :host-name "localhost" :port 57127) (send-msg *osc-client* "/s_new" "default" 1001 0 0 "freq" 500) (send-msg *osc-client* "/n_free" 1001) (send-bundle *osc-client* (timetag+ (get-current-timetag) 2) ; 2 secs later "/s_new" "default" 1001 0 0 "freq" 500) (send-msg *osc-client* "/n_free" 1001) (quit *osc-client*) ; Sends default /quit notification which scsynth ; ignores. Ideally osc-client should be subclassed ; to allow scsynth specific behaviour to be ; implemented.
8,770
Common Lisp
.lisp
206
34.990291
72
0.521354
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d8dc8a5602a8db10d3aad5276ff9ee57e22bc831b4d892a5f31926084b81656a
26,981
[ -1 ]
26,982
osc.asd
zzkt_osc-devices/osc.asd
;; -*- mode: lisp -*- (defpackage osc-system (:use :common-lisp :asdf)) (in-package :osc-system) (defsystem "osc" :name "osc" :author "nik gaffney <[email protected]>" :licence "GPL v3" :description "The Open Sound Control protocol aka OSC" :version "0.7" :depends-on (:usocket) :components ((:file "osc" :depends-on ("osc-data" "osc-time")) (:file "osc-package") (:file "osc-data" :depends-on ("osc-package")) (:file "osc-time" :depends-on ("osc-package")) (:file "osc-dispatch" :depends-on ("osc")) (:file "osc-tests" :depends-on ("osc")) (:module "devices" :depends-on ("osc-package" "osc-data") :components ((:file "socket-functions") (:file "device") (:file "transmitter" :depends-on ("device" "socket-functions")) (:file "listening-device" :depends-on ("transmitter")) (:file "dispatching-device" :depends-on ("listening-device")) (:file "client" :depends-on ("dispatching-device")) (:file "server" :depends-on ("client"))))))
1,145
Common Lisp
.asd
33
27.030303
56
0.557259
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
ead9eeb0d22449dc66c412c13df97aa52c3e8060c1e3e585e1b1e9b4f6148190
26,982
[ -1 ]
26,990
ci.yaml
zzkt_osc-devices/.github/workflows/ci.yaml
name: CI # details & description at http://3bb.cc/blog/2020/09/11/github-ci/ # Controls when the action will run. Triggers the workflow on push for any branch, and # pull requests to master on: push: pull_request: branches: [ endless ] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: test: name: ${{ matrix.lisp }} on ${{ matrix.os }} strategy: matrix: # current ccl-bin has a flaky zip file, so roswell can't install it. # Specify a version that works for now. #- cmucl, allegro, ccl, ecl, clisp lisp: [sbcl-bin] os: [ubuntu-latest, macos-latest, windows-latest] # run the job on every combination of "lisp" and "os" above runs-on: ${{ matrix.os }} # default to msys2 shell on windows, since roswell install-for-ci.sh tries to install using pacman defaults: run: shell: ${{ fromJSON('[ "bash", "msys2 {0}" ]') [ matrix.os == 'windows-latest' ] }} steps: # use setup-msys2 - uses: msys2/setup-msys2@v2 if: matrix.os == 'windows-latest' with: path-type: inherit # list any extra packages we want installed # for example the following would be enough for us to build sbcl # from git: # install: 'git base-devel unzip mingw-w64-x86_64-gcc mingw64/mingw-w64-x86_64-zlib' # tell git not to convert line endings # change roswell install dir and add it to path - name: windows specific settings if: matrix.os == 'windows-latest' run: | git config --global core.autocrlf false echo "ROSWELL_INSTALL_DIR=$HOME/ros" >> $GITHUB_ENV echo "$HOME/ros/bin" >> $GITHUB_PATH # Check out your repository under $GITHUB_WORKSPACE, so your job can access it - uses: actions/checkout@v2 - name: cache .roswell id: cache-dot-roswell uses: actions/cache@v1 with: path: ~/.roswell key: ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}-${{ hashFiles('**/*.asd') }} restore-keys: | ${{ runner.os }}-dot-roswell-${{ matrix.lisp }}- ${{ runner.os }}-dot-roswell- - name: install roswell # always run install, since it does some global installs and setup that isn't cached env: LISP: ${{ matrix.lisp }} run: curl -L https://raw.githubusercontent.com/roswell/roswell/master/scripts/install-for-ci.sh | sh -x - name: run lisp continue-on-error: true run: | ros -e '(format t "~a:~a on ~a~%...~%~%" (lisp-implementation-type) (lisp-implementation-version) (machine-type))' ros -e '(format t " fixnum bits:~a~%" (integer-length most-positive-fixnum))' ros -e "(ql:quickload 'trivial-features)" -e '(format t "features = ~s~%" *features*)' - name: update ql dist if we have one cached run: ros -e "(ql:update-all-dists :prompt nil)" - name: load code and run tests run: | ros -e '(handler-bind (#+asdf3.2(asdf:bad-SYSTEM-NAME (function MUFFLE-WARNING))) (handler-case (ql:quickload :osc) (error (a) (format t "caught error ~s~%~a~%" a a) (uiop:quit 123))))' -e '(osc:run-tests)'
3,170
Common Lisp
.l
69
39.434783
214
0.634154
zzkt/osc-devices
1
0
4
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
af79083e8c3bd915acb996fb9991e08f2e637f0333fd008486649e289016b566
26,990
[ -1 ]
27,012
xeh.lisp
obsfx_xeh/xeh.lisp
;;; xeh ;;; A command-line Canonical HEX+ASCII display tool written in ~100 lines of Common Lisp. ;;; https://github.com/obsfx/xeh (defun dump (output) (format t "~A" output)) (defun dump-n (output n) ;; https://stackoverflow.com/a/24758778/13615958 (format t "~v@{~A~:*~}" n output)) (defun repeat-n (output n) ;; https://stackoverflow.com/a/24758778/13615958 (format nil "~v@{~A~:*~}" n output)) (defun newline () (format t "~%")) (defun slice (l start len) (if (< start (length l)) (let ((end (+ start len))) (subseq l start (if (< end (length l)) end (length l)))))) (defun fixed-slice (l start len) (let ((base-list (make-list len :initial-element " "))) (loop for i from 0 to (- len 1) do (let* ((hex (nth (+ start i) l)) (placed-val (if hex hex " "))) (setf (nth i base-list) placed-val))) (values base-list))) (defun join (str-list &optional char) (reduce #'(lambda (a b) (format nil "~A~A~A" a (if char char "") b)) str-list)) (defun format-single-char-hex-values (hex-list) (mapcar #'(lambda (hex) (format nil "~A~A" (repeat-n "0" (- 2 (length hex))) hex)) hex-list)) (defun get-row-address (byte-pos) (let ((hex-byte-pos (write-to-string byte-pos :base 16))) (format nil "~A~A" (repeat-n "0" (- 8 (length hex-byte-pos))) hex-byte-pos))) (defun hex-list-to-str-list (str-list) (mapcar #'(lambda (str) (let* ((ascii (parse-integer str :radix 16)) (c (code-char ascii))) (if (and c (> ascii 31) (< ascii 127)) c (format nil ".")))) str-list)) (defun dump-hex-row (buffer byte-pos) (let* ((row (fixed-slice buffer 0 16)) (left (subseq row 0 8)) (right (subseq row 8 16))) (progn (dump (string-downcase (get-row-address byte-pos))) (dump " ") (dump (string-downcase (join left " "))) (dump " ") (dump (string-downcase (join right " "))) (dump " ") (dump "|") (dump (join (hex-list-to-str-list buffer))) (dump "|") (newline)))) (defparameter byte-pos 0) (defparameter buffer nil) (defparameter file-path nil) (defun read-file-bytes (file-path) (with-open-file (stream file-path :element-type '(unsigned-byte 8) :if-does-not-exist nil) ;; https://stackoverflow.com/a/3814098/13615958 ;; https://lispcookbook.github.io/cl-cookbook/iteration.html (if stream (progn (loop named stream-loop for byte = (read-byte stream nil nil) while byte do (progn (setq buffer (append buffer (list (write-to-string byte :base 16)))) (if (= (length buffer) 16) (progn (setf buffer (format-single-char-hex-values buffer)) (dump-hex-row buffer byte-pos) (setf byte-pos (+ byte-pos 16)) (setf buffer nil))))) (if (> (length buffer) 0) (progn (setf buffer (format-single-char-hex-values buffer)) (dump-hex-row buffer byte-pos))) (dump (string-downcase (get-row-address (+ byte-pos (length buffer))))) (newline)) (progn (format t "xeh: ~A: File couldn't found" file-path) (newline) (quit))))) (defun main() (progn (setf file-path (second *posix-argv*)) (if file-path (read-file-bytes file-path))))
3,567
Common Lisp
.lisp
95
29.347368
89
0.551315
obsfx/xeh
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
d836295a5ff70ea2f373ca275446acecd2dec8dbcb2505e1a88f792fe4eb4f08
27,012
[ -1 ]
27,014
build.sh
obsfx_xeh/build.sh
#!/bin/bash # https://github.com/burtonsamograd/sxc/wiki/How-to-build-an-executable-with-SBCL sbcl --no-userinit --load xeh.lisp --eval "(sb-ext:save-lisp-and-die \"xeh\" :toplevel 'main :executable t)"
203
Common Lisp
.l
3
66.666667
108
0.73
obsfx/xeh
1
1
0
GPL-3.0
9/19/2024, 11:28:28 AM (Europe/Amsterdam)
4f5dabe3e8f794ab9115a2d84364c58a2a400d5ece9742f316eb060e19629ed2
27,014
[ -1 ]