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
listlengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4,825 | example-lisp.lisp | informatimago_lisp/rdp/example-lisp.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: example-lisp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; An example grammar for the recusive descent parser generator.
;;;; The actions are written in Lisp, to generate a lisp parser.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2011-07-19 <PJB> Updated regexps, now we use extended regexps.
;;;; 2011-07-19 <PJB> Added defpackage forms. Added parsing example sources.
;;;; 2006-09-10 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.RDP.EXAMPLE"
(:use
"COMMON-LISP"
;;"CL-STEPPER"
"COM.INFORMATIMAGO.RDP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")
(:export "PARSE-EXAMPLE"))
(in-package "COM.INFORMATIMAGO.RDP.EXAMPLE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Example Language
;;; taken from: http://en.wikipedia.org/wiki/Recursive_descent_parser
;;;
(defgrammar example
:terminals ((ident "[A-Za-z][A-Za-z0-9]*")
;; real must come first to match the longest first.
(real "[-+]?[0-9]+\\.[0-9]+([Ee][-+]?[0-9]+)?")
(integer "[-+]?[0-9]+"))
:start program
:rules ((--> factor
(alt ident
number
(seq "(" expression ")" :action $2))
:action $1)
(--> number (alt integer real) :action $1)
(--> term
factor (rep (alt "*" "/") factor)
:action `(,$1 . ,$2))
(--> expression
(opt (alt "+" "-"))
term
(rep (alt "+" "-") term :action `(,$1 ,$2))
:action `(+ ,(if $1 `(,$1 ,$2) $2) . ,$3))
(--> condition
(alt (seq "odd" expression
:action `(oddp ,$2))
(seq expression
(alt "=" "#" "<" "<=" ">" ">=")
expression
:action `(,$2 ,$1 ,$3)))
:action $1)
(--> statement
(opt (alt (seq ident ":=" expression
:action `(setf ,$1 ,$3))
(seq "call" ident
:action `(call ,$2))
(seq "begin" statement
(rep ";" statement
:action $2)
"end"
:action `(,$2 . ,$3))
(seq "if" condition "then" statement
:action `(if ,$2 ,$4))
(seq "while" condition "do" statement
:action `(while ,$2 ,$4))))
:action $1)
(--> block
(opt "const" ident "=" number
(rep "," ident "=" number
:action `(,$2 ,$4))
";"
:action `((,$2 ,$4) . ,$5))
(opt "var" ident
(rep "," ident :action $2)
";"
:action `(,$2 . ,$3))
(rep "procedure" ident ";" block ";"
:action `(procedure ,$2 ,$4))
statement
:action `(block ,$1 ,$2 ,$3 ,$4))
(--> program
block "." :action $1)))
(define-test test/rdp-example-lisp ()
(check equal (parse-example "
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
'(block (((ident "abc" 14) (integer "123" 20))
((ident "pi" 13) (real "3.141592e+0" 25)))
((ident "a" 10) (ident "b" 12) (ident "c" 14))
((procedure (ident "gcd" 18)
(block nil
nil
nil
((((while ((\# "#" 18) (+ ((ident "a" 16))) (+ ((ident "b" 20))))
((((if ((< "<" 19) (+ ((ident "a" 18))) (+ ((ident "b" 20))))
((setf (ident "b" 27)
(+ ((ident "b" 30)) ((- "-" 31) ((ident "a" 32))))))))
((if ((> ">" 19) (+ ((ident "a" 18))) (+ ((ident "b" 20))))
((setf (ident "a" 27)
(+ ((ident "a" 30))
((- "-" 31) ((ident "b" 32)))))))))))))))))
((((setf (ident "a" 6) (+ ((integer "42" 10)))))
((setf (ident "b" 6) (+ ((real "30.0" 12))))) ((call (ident "gcd" 13))))))
)
:success)
(defpackage "COM.INFORMATIMAGO.RDP.EXAMPLE-WITHOUT-ACTION"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.RDP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")
(:export "PARSE-EXAMPLE-WITHOUT-ACTION"))
(in-package "COM.INFORMATIMAGO.RDP.EXAMPLE-WITHOUT-ACTION")
(defgrammar example-without-action
:terminals ((ident "[A-Za-z][A-Za-z0-9]*")
;; real must come first to match the longest first.
(real "[-+]?[0-9]+\\.[0-9]+([Ee][-+]?[0-9]+)?")
(integer "[-+]?[0-9]+"))
:start program
:rules ((--> factor
(alt ident
number
(seq "(" expression ")")))
(--> number (alt integer real))
(--> term
factor (rep (alt "*" "/") factor))
(--> expression
(opt (alt "+" "-"))
term
(rep (alt "+" "-") term))
(--> condition
(alt (seq "odd" expression)
(seq expression
(alt "=" "#" "<" "<=" ">" ">=")
expression)))
(--> statement
(opt (alt (seq ident ":=" expression)
(seq "call" ident)
(seq "begin" statement
(rep ";" statement)
"end")
(seq "if" condition "then" statement)
(seq "while" condition "do" statement))))
(--> block
(opt "const" ident "=" number
(rep "," ident "=" number) ";")
(opt "var" ident (rep "," ident) ";")
(rep "procedure" ident ";" block ";")
statement)
(--> program
block ".")))
(define-test test/rdp-example-lisp-without-action ()
(check equal (parse-example-without-action "
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
'(program
(block ((|const| "const" 10) (ident "abc" 14) (= "=" 16)
(number (integer "123" 20))
(((\, "," 21) (ident "pi" 13) (= "=" 14)
(number (real "3.141592e+0" 25))))
(\; ";" 26))
((|var| "var" 8) (ident "a" 10)
(((\, "," 11) (ident "b" 12)) ((\, "," 13) (ident "c" 14))) (\; ";" 15))
(((|procedure| "procedure" 14) (ident "gcd" 18) (\; ";" 19)
(block nil
nil
nil
(statement
(((|begin| "begin" 10)
(statement
(((|while| "while" 14)
(condition
((expression nil (term (factor (ident "a" 16)) nil) nil)
(\# "#" 18)
(expression nil (term (factor (ident "b" 20)) nil) nil)))
(|do| "do" 23)
(statement
(((|begin| "begin" 14)
(statement
(((|if| "if" 16)
(condition
((expression nil (term (factor (ident "a" 18)) nil) nil)
(< "<" 19)
(expression nil (term (factor (ident "b" 20)) nil) nil)))
(|then| "then" 25)
(statement
(((ident "b" 27) (\:= ":=" 29)
(expression nil (term (factor (ident "b" 30)) nil)
(((- "-" 31) (term (factor (ident "a" 32)) nil))))))))))
(((\; ";" 34)
(statement
(((|if| "if" 16)
(condition
((expression nil (term (factor (ident "a" 18)) nil) nil)
(> ">" 19)
(expression nil (term (factor (ident "b" 20)) nil)
nil)))
(|then| "then" 25)
(statement
(((ident "a" 27) (\:= ":=" 29)
(expression nil (term (factor (ident "a" 30)) nil)
(((- "-" 31)
(term (factor (ident "b" 32)) nil))))))))))))
(|end| "end" 12)))))))
nil (|end| "end" 8)))))
(\; ";" 9)))
(statement
(((|begin| "begin" 6)
(statement
(((ident "a" 6) (\:= ":=" 8)
(expression nil (term (factor (number (integer "42" 10))) nil) nil))))
(((\; ";" 11)
(statement
(((ident "b" 6) (\:= ":=" 8)
(expression nil (term (factor (number (real "30.0" 12))) nil)
nil)))))
((\; ";" 13) (statement (((|call| "call" 9) (ident "gcd" 13))))))
(|end| "end" 4)))))
(|.| "." 5)))
:success)
(in-package "COM.INFORMATIMAGO.RDP.EXAMPLE")
(defun test/all ()
(com.informatimago.rdp.example::test/rdp-example-lisp)
(com.informatimago.rdp.example-without-action::test/rdp-example-lisp-without-action))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
| 11,941 | Common Lisp | .lisp | 279 | 27.172043 | 115 | 0.37881 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b26bc9553d974126e3e977b63684dc0b3adc10078f43736b8e50d5cb74b386f4 | 4,825 | [
-1
] |
4,826 | rdp-macro.lisp | informatimago_lisp/rdp/rdp-macro.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: rdp-macro.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; The defgrammar macro.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-02-24 <PJB> Extracted from rdp.lisp.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.RDP")
(defmacro defgrammar (name &key
terminals
start
rules
(scanner t)
(skip-spaces t)
(eof-symbol *eof-symbol*)
(target-language :lisp)
(trace nil))
"
DO: This macro generates a simple scanner and recursive decent parser
for the language described by this grammar.
For each <non-terminal> in the grammar, a function named
<name>/PARSE-<non-terminal> is generated, in addition to
functions SCAN-<name> and PARSE-<name>.
The grammar structure is also generated for run-time
in the global special variable <name>.
TERMINALS:
A list describing the terminal, of form either:
(terminal-name match-regexp)
(terminal-name match-regexp / exclude-regexp)
In the first form, if the match-regexp matches, left-anchored
to the current position, then the corresponding terminal is
recognized.
In the second form, if the match-regexp matches, left-anchored
to the current position, and the exclude-regexp DOES NOT
match, left-anchored to the first position following the
match, then the corresponding terminal is recognized.
Note that terminals don't necessarily have a name since they
may be written directly in the grammar rules as strings.
SCANNER:
Can be either:
- T A scanner is generated.
- NIL No scanner is generated.
- a class-name subclass of COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER
which is used to get tokens.
SKIP-SPACES:
When false, the spaces are not eaten between token. It's up
to the grammar or the scanner to deal with them. (Only when a
scanner is generated with :scanner t).
START:
The start symbol (non-terminal).
RULES:
A list of grammar rules.
EOF-SYMBOL:
The end-of-file symbol (terminal). Default is the value bound
to *EOF-SYMBOL* at macroexpansion-time.
TARGET-LANGUAGE:
Specifies the language into which the code is generated, as a
keyword. The actions must still be written as lisp
expressions, but to generate the language specified. There
must be a set of methods specialized on this target-language
keyword.
TRACE:
When true, the parser functions are traced..
SYNTAX:
(defgrammar <name>
:terminals (( <terminal> \"regexp\" [ / \"regexp\" ]) ...)
:start <non-terminal>
:rules ((--> <non-terminal> <items> ) ...))
<items> ::= | <item> <items>
<item> ::= <seq> | <rep> | <alt> | <opt>
| <non-terminal> | <literal-terminal> | <terminal>
<seq> ::= (SEQ <items> <action>) ; <items> may be empty.
<rep> ::= (REP <item> <items> <action>)
<opt> ::= (OPT <item> <items> <action>)
<alt> ::= (ALT <item> <items>)
<action> ::= | :ACTION <forms>
<forms> ::= | <form> <forms>
<form> ::= form -- any lisp form.
<non-terminal> ::= symbol -- any lisp symbol (keywords reserved).
<terminal> ::= symbol -- any lisp symbol (keywords reserved).
<literal-terminal> ::= string -- any lisp string.
SEMANTICS:
The terminals are either named terminals listed in the :TERMINALS
clause, or literal terminals written directly in the productions as
lisp strings. They are matched as-is.
An extended regular expression regex(7) may be given that
will be matched by the scanner to infer the given terminal.
The literal terminals are matched first, the longest first,
and with ([A-Za-z0-9]|$) appended to terminals ending in a
letter or digit (so that they don't match when part of a
longer identifier).
Then the regular expressions are matched in the order given.
A second regexp can be given for a terminal, which must not be
matched, after the first regexp, for the terminal to be
recognized. (:terminals ((alpha \"[A-Za-z]+\" / \"[0-9]\")))
will recognize \"abcd, efgh\" as the ALPHA \"abcd\", but
won't recognize \"abcd42, efgh\" as an ALPHA.
:START specifies the start non-terminal symbol.
The non-terminal symbols are infered implicitely from the grammar rules.
If there are more than one subforms, or an action,
the REP and OPT forms take an implicit SEQ:
(REP a b c :ACTION f) --> (REP (SEQ a b c :ACTION f))
(OPT a b c :ACTION f) --> (OPT (SEQ a b c :ACTION f))
(REP a :ACTION f) --> (REP (SEQ a :ACTION f))
(OPT a :ACTION f) --> (OPT (SEQ a :ACTION f))
(REP a) --> (REP a)
(OPT a) --> (OPT a)
Embedded ALT are flattened:
(ALT a b (ALT c d) e f) --> (ALT a b c d e f)
Actions are executed in a lexical environment where the
symbols $1, $2, etc are bound to the results of the
subforms. $0 is bound to the list of the results of the
subforms. In addition, for each non-terminal the non-terminal
symbol is bound to the result of the corresponding subform.
When the non-terminal is present several times in the
production, a dot and an index number is appended.
(--> example
(seq thing item \",\" item (opt \",\" item
:action (list item))
:action (list thing item.1 item.2 $5)))
would build a list with the results of parsing thing, the
two items, and the optional part.
The action for REP is to return a possibly empty list of the
results of its single subform repeated. (REP is 0 or more).
The action for OPT is to return either NIL, or the result of
its single subform unchanged.
The action for an ALT is to return the result of the selected
alternative unchanged.
The default action for an internal SEQ is to return the list of the
results of its subforms.
The default action for an implicit SEQ for a given <non-terminal> lhs
is to return the list of the results of its subforms prefixed by the
<non-terminal> symbol.
TODO: We could also flatten sequences without action, or even sequences with
actions with renumbering.
"
(dolist (terminal terminals)
(assert (or (and (= 2 (length terminal))
(symbolp (first terminal))
(stringp (second terminal)))
(and (= 4 (length terminal))
(symbolp (first terminal))
(stringp (second terminal))
(symbolp (third terminal))
(string= "/" (third terminal))
(stringp (fourth terminal))))
(terminal)
"Invalid terminal clause ~S.~%Should be (terminal \"regexp\") or (terminal \"regexp\" / \"regexp\")."
terminal))
(generate-grammar name
:terminals terminals
:scanner scanner
:skip-spaces skip-spaces
:start start
:rules rules
:eof-symbol eof-symbol
:target-language target-language
:trace trace))
;;;; THE END ;;;;
| 9,238 | Common Lisp | .lisp | 187 | 40.010695 | 113 | 0.579614 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7f025546d0a58394d24a0a09d230a0fd733a71d181ad89df39859bce510cb397 | 4,826 | [
-1
] |
4,827 | rdp-lisp-boilerplate.lisp | informatimago_lisp/rdp/rdp-lisp-boilerplate.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: rdp-lisp-boilerplate.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; The lisp parser boilerplate.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-05-06 <PJB> Extracted from rdp.lisp.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.RDP")
(declaim (declaration stepper))
(defvar *non-terminal-stack* '()
"For error reporting.")
(define-condition parser-error (error)
((file :initarg :file :initform nil :reader parser-error-file)
(line :initarg :line :initform 1 :reader parser-error-line)
(column :initarg :column :initform 0 :reader parser-error-column)
(grammar :initarg :grammar :initform nil :reader parser-error-grammar)
(scanner :initarg :scanner :initform nil :reader parser-error-scanner)
(non-terminal-stack :initarg :non-terminal-stack :initform '() :reader parser-error-non-terminal-stack)
(format-control :initarg :format-control :initform "" :reader parser-error-format-control)
(format-arguments :initarg :format-arguments :initform '() :reader parser-error-format-arguments))
(:report print-parser-error))
(defmethod print-parser-error ((err parser-error) stream)
(declare (stepper disable))
(let ((*print-circle* nil)
(*print-pretty* nil))
(format stream
"~&~@[~A:~]~D:~D: ~?~%"
(let ((source (scanner-source (parser-error-scanner err))))
(typecase source
((or string file-stream) (or (ignore-errors (pathname source))
(parser-error-file err)))
(t (parser-error-file err))))
(parser-error-line err)
(parser-error-column err)
(parser-error-format-control err)
(parser-error-format-arguments err))
err))
(define-condition parser-end-of-source-not-reached (parser-error)
()
(:default-initargs
:format-control "Parsing finished before end-of-source."))
(define-condition unexpected-token-error (scanner-error)
((expected-tokens :initarg :expected-tokens
:initform '()
:reader unexpected-token-error-expected-tokens)
(non-terminal-stack :initarg :non-terminal-stack
:initform '()
:reader unexpected-token-error-non-terminal-stack))
(:report print-scanner-error))
(defmethod print-scanner-error ((err unexpected-token-error) stream)
(declare (stepper disable))
(when (next-method-p) (call-next-method))
(let ((*print-circle* nil)
(*print-pretty* nil))
(format stream "~&Expected token: ~S~%Non-terminal stack: ~S~%"
(unexpected-token-error-expected-tokens err)
(unexpected-token-error-non-terminal-stack err)))
err)
(defclass rdp-scanner (buffered-scanner)
()
(:default-initargs :line 0))
(defmethod scanner-current-token ((scanner rdp-scanner))
(token-kind (call-next-method)))
(defmethod scanner-end-of-line-p ((scanner rdp-scanner))
(or (null (scanner-buffer scanner))
;; column is 1-based:
(< (length (scanner-buffer scanner))
(scanner-column scanner))))
(defmethod scanner-end-of-source-p ((scanner rdp-scanner))
(and (scanner-end-of-line-p scanner)
(let ((ps (slot-value scanner 'stream)))
(not (ungetchar ps (getchar ps))))))
(defmethod advance-line ((scanner rdp-scanner))
"RETURN: The new current token = old next token"
(cond
((scanner-end-of-source-p scanner)
#|End of File -- don't move.|#
(scanner-current-token scanner))
((setf (scanner-buffer scanner) (readline (slot-value scanner 'stream)))
;; We must skip the empty lines.
(incf (scanner-line scanner))
(setf (scanner-column scanner) 1
(scanner-current-text scanner) ""
(scanner-current-token scanner) nil)
;; (loop :do (incf (scanner-line scanner))
;; :while (and (zerop (length (scanner-buffer scanner)))
;; (setf (scanner-buffer scanner) (readline (slot-value scanner 'stream)))))
;; got a line -- advance a token.
(scan-next-token scanner))
(t
;; Just got EOF
(setf (scanner-current-text scanner) "<END OF FILE>"
(scanner-current-token scanner) '|<END OF FILE>|))))
(defmethod accept ((scanner rdp-scanner) token)
(unless (word-equal token (scanner-current-token scanner))
(error-unexpected-token scanner token nil))
(prog1 (list (token-kind (scanner-current-token scanner))
(scanner-current-text scanner)
(scanner-column scanner))
(scan-next-token scanner)))
;;;; THE END ;;;;
| 5,999 | Common Lisp | .lisp | 129 | 41.093023 | 107 | 0.617094 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e2d95b753e4809c3301d8eb47589ddb4342e9789e274047cd337065ac3605b78 | 4,827 | [
-1
] |
4,828 | scratch.lisp | informatimago_lisp/rdp/scratch.lisp | (com.informatimago.rdp.example:parse-example
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
(com.informatimago.rdp.example-without-action:parse-example-without-action
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
| 662 | Common Lisp | .lisp | 36 | 12.055556 | 74 | 0.515298 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 51755b4bcb9e1bfa40de7c65963b970563e6eb955caaa71e46e166d6700ecd12 | 4,828 | [
-1
] |
4,829 | example-basic.lisp | informatimago_lisp/rdp/example-basic.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: example-basic.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; An example grammar for the recusive descent parser generator.
;;;; The actions are written in a pseudo basic
;;;; to generate a pseudo basic parser.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2011-07-19 <PJB> Updated regexps, now we use extended regexps.
;;;; 2006-09-10 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.RDP.BASIC.EXAMPLE"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.RDP")
(:export "PARSE-EXAMPLE"))
(in-package "COM.INFORMATIMAGO.RDP.BASIC.EXAMPLE")
(defgrammar example
:target-language :basic
:terminals ((ident "[A-Za-z][A-Za-z0-9]*")
;; real must come first to match the longest first.
(real "[-+]?[0-9]+.[0-9]+([Ee][-+]?[0-9]+)?")
(integer "[-+]?[0-9]+"))
:start program
:rules ((--> factor
(alt ident
number
(seq "(" expression ")" :action "RES=A2"))
:action "RES=A1")
(--> number (alt integer real) :action "RES=A1")
(--> term
factor (rep (alt "*" "/") factor)
:action "NCAR=A1:NCDR=A2:CALL CONS")
(--> expression
(opt (alt "+" "-"))
term
(rep (alt "+" "-") term
:action
"NCAR=A2:NCDR=NIL:CALL CONS"
"NCAR=A1:NCDR=RES:CALL CONS")
:action
"IF A1<>0 THEN"
" NCAR=A2:NCDR=NIL:CALL CONS"
" NCAR=A1:NCDR=RES:CALL CONS"
" NCAR=RES"
"ELSE"
" NCAR=A2"
"ENDIF"
"NCDR=A3:CALL CONS"
"TMP=RES"
"NSTRING$=\"+\":CALL MKSTR:NCAR=RES:NCDR=TMP:CALL CONS")
(--> condition
(alt (seq "odd" expression
:action
"NCAR=A2:NCDR=NIL:CALL CONS:TMP=RES"
"NSTRING$=\"ODD\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
(seq expression
(alt "=" "#" "<" "<=" ">" ">=")
expression
:action
"NCAR=A3:NCDR=NIL:CALL CONS"
"NCAR=A1:NCDR=RES:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"))
:action "RES=A1")
(--> statement
(opt (alt (seq ident ":=" expression
:action
"NCAR=A3:NCDR=NIL:CALL CONS"
"NCAR=A1:NCDR=RES:CALL CONS"
"TMP=RES:NSTRING$=\"LET\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
(seq "call" ident
:action
"NCAR=A2:NCDR=NIL:CALL CONS"
"TMP=RES:NSTRING$=\"CALL\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
(seq "begin" statement
(rep ";" statement :action "RES=A2")
"end"
:action "NCAR=A2:NCDR=A3:CALL CONS")
(seq "if" condition "then" statement
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"
"TMP=RES:NSTRING$=\"IF\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
(seq "while" condition "do" statement
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"
"TMP=RES:NSTRING$=\"WHILE\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")))
:action "RES=A1")
(--> block
(opt "const" ident "=" number
(rep "," ident "=" number
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS")
";"
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"
"NCAR=RES:NCDR=A5:CALL CONS")
(opt "var" ident
(rep "," ident :action "RES=A2")
";"
:action
"NCAR=A3:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS")
(rep "procedure" ident ";" block ";"
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"
"TMP=RES:NSTRING$=\"PROCEDURE\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
statement
:action
"NCAR=A4:NCDR=NIL:CALL CONS"
"NCAR=A3:NCDR=RES:CALL CONS"
"NCAR=A2:NCDR=RES:CALL CONS"
"NCAR=A1:NCDR=RES:CALL CONS"
"TMP=RES:NSTRING$=\"BLOCK\":CALL MKSTR"
"NCAR=RES:NCDR=TMP:CALL CONS")
(--> program
block "." :action "RES=A1")))
;;;; THE END ;;;;
| 6,907 | Common Lisp | .lisp | 154 | 28.305195 | 83 | 0.4244 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 1b488c754e60b97c852872c086f15089fa783303ac37158981b9190219e675b1 | 4,829 | [
-1
] |
4,830 | packages.lisp | informatimago_lisp/rdp/packages.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: packages.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Define the rdp package.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-06-16 <PJB> Extracted defpackage form.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2013 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COMMON-LISP-USER")
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.RDP"
(:use "COMMON-LISP"
;; "CL-STEPPER"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CONSTRAINTS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.PEEK-STREAM"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.REGEXP.REGEXP"
"COM.INFORMATIMAGO.COMMON-LISP.PARSER.SCANNER"
"COM.INFORMATIMAGO.COMMON-LISP.PARSER.PARSER")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL" "SCAT")
(:export "DEFGRAMMAR" "-->" "SEQ" "REP" "OPT" "ALT" "GRAMMAR-NAMED"
"GENERATE-GRAMMAR"
"GRAMMAR" "MAKE-GRAMMAR" "COPY-GRAMMAR"
"REGISTER-GRAMMAR"
"GRAMMAR-NAME" "GRAMMAR-TERMINALS" "GRAMMAR-START" "GRAMMAR-RULES"
"GRAMMAR-ALL-TERMINALS" "GRAMMAR-ALL-NON-TERMINALS"
"GRAMMAR-SKIP-SPACES"
"FIND-RHSES" "FIND-RHS" "TERMINALP" "NON-TERMINAL-P"
"FIRSTS-SET" "FOLLOW-SET" "NULLABLEP"
"SENTENCE-FIRST-SET"
"CLEAN-RULES"
"NORMALIZE-GRAMMAR" "COMPUTE-FIRST-SETS" "COMPUTE-FOLLOW-SETS"
"*NON-TERMINAL-STACK*"
;; Re-export form com.informatimago.common-lisp.parser.scanner:
"TOKEN" "TOKEN-KIND" "TOKEN-TEXT" "TOKEN-LINE" "TOKEN-COLUMN"
"*SPACE*" "WORD-EQUAL"
"RDP-SCANNER"
"SCANNER-LINE" "SCANNER-COLUMN" "SCANNER-STATE" "SCANNER-CURRENT-TOKEN"
"SCANNER-SPACES" "SCANNER-TAB-WIDTH"
"SKIP-SPACES" "SCAN-NEXT-TOKEN"
"SCANNER-BUFFER" "SCANNER-CURRENT-TEXT"
"SCANNER-END-OF-SOURCE-P" "ADVANCE-LINE" "ACCEPT"
"PARSER-ERROR"
"PARSER-ERROR-LINE"
"PARSER-ERROR-COLUMN"
"PARSER-ERROR-GRAMMAR"
"PARSER-ERROR-SCANNER"
"PARSER-ERROR-NON-TERMINAL-STACK"
"PARSER-ERROR-FORMAT-CONTROL"
"PARSER-ERROR-FORMAT-ARGUMENTS"
"PARSER-END-OF-SOURCE-NOT-REACHED"
;; "PARSER-ERROR-UNEXPECTED-TOKEN"
;; "PARSER-ERROR-EXPECTED-TOKEN"
"UNEXPECTED-TOKEN-ERROR"
"UNEXPECTED-TOKEN-ERROR-EXPECTED-TOKENS"
"UNEXPECTED-TOKEN-ERROR-NON-TERMINAL-STACK"
)
(:documentation "
This package implements a simple recursive descent parser.
Copyright Pascal J. Bourguignon 2006 - 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
"))
;;;; THE END ;;;;
| 4,132 | Common Lisp | .lisp | 93 | 38.27957 | 83 | 0.625062 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7d35b5c7b9be614d81726092ef6fce0b12c3a6d5367fb529cd641bee0ed2d22b | 4,830 | [
-1
] |
4,831 | rdp.lisp | informatimago_lisp/rdp/rdp.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: rdp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a simple recursive descent parser.
;;;;
;;;; http://en.wikipedia.org/wiki/Formal_grammar
;;;; http://en.wikipedia.org/wiki/Recursive_descent_parser
;;;; http://en.wikipedia.org/wiki/Parsing_expression_grammar
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-02-24 <PJB> Upgraded for use in com.informatimago.lse;
;;;; Changed to AGPL3 license.
;;;; 2011-01-12 <PJB> Added grammar parameter to functions
;;;; generating function names so that different
;;;; grammars with non-terminals named the same
;;;; don't collide.
;;;; 2006-09-09 <PJB> Created
;;;;BUGS
;;;;
;;;; The First set of a non-terminal that can reduce to the empty string
;;;; should include the Follow set of this non-terminal, but for this,
;;;; we'd have to normalize the grammar rules, and then generate parsing
;;;; functions that don't correspond directly to the source rules.
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.RDP")
(defstruct (grammar
(:print-function
(cl:lambda (object stream depth)
(declare (ignore depth))
(print-unreadable-object (object stream :type t :identity t)
(format stream "~A" (grammar-name object))))))
name
terminals ;
start ; non-terminal
rules ; list of (--> non-terminal [ rhs [:action . body])
all-terminals ; union of the terminals found in the rules and declared in terminals
all-non-terminals
%synthesized-non-terminals
;; ---
(scanner t)
(skip-spaces t)
;; --- computed lazily:
%normalized-grammar
%firsts-sets
%follow-sets)
(defstruct (normalized-grammar
(:include grammar)
(:constructor %make-normalized-grammar))
%original-grammar)
(defgeneric grammar-constructor (grammar)
(:method ((grammar grammar)) 'make-grammar)
(:method ((grammar normalized-grammar)) 'make-normalized-grammar))
(defgeneric grammar-normalized-grammar (grammar)
(:method ((grammar grammar))
(or (grammar-%normalized-grammar grammar)
(setf (grammar-%normalized-grammar grammar) (normalize-grammar grammar))))
(:method ((grammar normalized-grammar))
grammar))
(defgeneric grammar-original-grammar (grammar)
(:method ((grammar grammar)) grammar)
(:method ((grammar normalized-grammar)) (normalized-grammar-%original-grammar grammar)))
(defun compute-first-follow (grammar)
(setf (grammar-%firsts-sets grammar) (compute-firsts-sets grammar)
(grammar-%follow-sets grammar) (compute-follow-sets grammar)))
(defgeneric grammar-firsts-sets (grammar)
(:method ((grammar grammar))
(grammar-firsts-sets (grammar-normalized-grammar grammar)))
(:method ((grammar normalized-grammar))
(unless (grammar-%firsts-sets grammar)
(compute-first-follow grammar))
(grammar-%firsts-sets grammar)))
(defgeneric grammar-follow-sets (grammar)
(:method ((grammar grammar))
(grammar-follow-sets (grammar-normalized-grammar grammar)))
(:method ((grammar normalized-grammar))
(unless (grammar-%follow-sets grammar)
(compute-first-follow grammar))
(grammar-%follow-sets grammar)))
(defgeneric dump-grammar (grammar)
(:method ((grammar grammar))
(format t "(~A~%" (grammar-constructor grammar))
(format t " :name ~S~%" (grammar-name grammar))
(format t " :terminals ~S~%" (grammar-terminals grammar))
(format t " :start ~S~%" (grammar-start grammar))
(format t " :rules ~S~%" (grammar-rules grammar))
(format t " :all-terminals ~S~%" (grammar-all-terminals grammar))
(format t " :all-non-terminals ~S~%" (grammar-all-non-terminals grammar))
(format t " :scanner ~S~%" (grammar-scanner grammar))
(format t " :skip-spaces ~S~%" (grammar-skip-spaces grammar))
(format t " :firsts-sets ~S~%" (grammar-firsts-sets grammar))
(format t " :follow-sets ~S~%" (grammar-follow-sets grammar))
(format t ")~%")
grammar))
(defvar *grammars* (make-hash-table)
"Records the variables defined with DEFGRAMMAR.
Use (GRAMMAR-NAMED name) to look up a grammar.")
(defun grammar-named (name)
"Returns the grammar named NAME, or NIL if none."
(gethash name *grammars*))
(defun register-grammar (grammar)
(setf (gethash (grammar-name grammar) *grammars*) grammar))
#-sbcl
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (documentation 'seq t) "
Grammar rule syntax:
(SEQ term... [:action form...])
Parses if each of the term parse in sequence, once.
In the scope of the action, the terms are bound to variables named $1
$2 to $n, and for non-terminals, to variables named by the
non-terminal (suffixed by .1, .2, etc) if several occurence of the
same non-terminal are present in the sequence.
The default action returns all the parsed terms in a list.
"
(documentation 'req t) "
Grammar rule syntax:
(REQ term... [:action form...])
is equivalent to:
(REQ (SEQ term... [:action form...]))
Parses if each of the term parse in sequence, 0 or more times.
Returns a list of the parsed sequences.
"
(documentation 'opt t) "
Grammar rule syntax:
(OPT term... [:action form...])
is equivalent to:
(OPT (SEQ term... [:action form...]))
Parses if each of the term parse in sequence, 0 or 1 time.
Returns NIL or the result of the parsed sequence.
"
(documentation 'alt t) "
Grammar rule syntax:
(ALT term...)
Parses one of the terms (the first set of all the terms must be disjoint).
Returns parsed term.
"))
(defgeneric generate-boilerplate (target-language grammar &key trace)
(:documentation "Generate the boilerplate code needed by the scanner and parser.
This code must be a single lisp form. In the case of the :lisp
target-language, this form is the code of the boilerplate itself. For
another language, this form is lisp code used to generate that other
language boilerplate.")
(:method (target-language grammar &key trace)
(declare (ignore target-language grammar trace))
nil))
(defgeneric generate-scanner-for-grammar (target-language grammar &key trace)
(:documentation "Generate the scanner code,
when (grammar-scanner grammar) is T. (grammar-scanner grammar) may
be the class-name of a scanner to use.
This code must be a single lisp form. In the case of the :lisp
target-language, this form is the code of the boilerplate itself. For
another language, this form is lisp code used to generate that other
language boilerplate."))
(defgeneric generate-parser (target-language grammar &key trace)
(:documentation "Generate the toplevel parser code.
This code must be a single lisp form. In the case of the :lisp
target-language, this form is the code of the boilerplate itself. For
another language, this form is lisp code used to generate that other
language boilerplate."))
(defgeneric generate-non-terminal-parser-function (target-language grammar non-terminal &key trace)
(:documentation "Generate the parser code for the given non-terminal.
This code must be a single lisp form. In the case of the :lisp
target-language, this form is the code of the boilerplate itself. For
another language, this form is lisp code used to generate that other
language boilerplate."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generate the defgrammar expansion:
;;;
(defvar *linenum* 0)
(defun generate-grammar (name &key
terminals (scanner t) (skip-spaces t)
start rules
((:eof-symbol *eof-symbol*) *eof-symbol*)
(target-language :lisp) (trace nil))
"
SEE ALSO: The docstring of DEFGRAMMAR.
RETURN: A form that defines the grammar object and its parser functions.
"
(let* ((clean-rules (clean-rules rules))
(grammar (make-normalized-grammar
:name name
:terminals terminals
:start start
:rules clean-rules
:scanner scanner
:skip-spaces skip-spaces))
(*linenum* 0))
(register-grammar grammar)
`(let ((*eof-symbol* ',*eof-symbol*))
(register-grammar
(make-normalized-grammar
:name ',name
:terminals ',terminals
:start ',start
:rules ',clean-rules
:scanner ',scanner
:skip-spaces ',skip-spaces))
,(generate-boilerplate target-language grammar :trace trace)
,(generate-scanner-for-grammar target-language grammar :trace trace)
,@(mapcar (lambda (non-terminal)
(generate-non-terminal-parser-function target-language grammar non-terminal :trace trace))
(grammar-all-non-terminals grammar))
,(generate-parser target-language grammar :trace trace)
',name)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Utilities
;;;
(defun dollar (n)
"Interns a $-symbol number N."
(scat "$" (prin1-to-string n)))
(defstruct (rhs (:type list))
operator body actions)
(defparameter *empty-rhs* '(seq () ('()))
"Represents ε.")
(defun empty-rhs-p (rhs)
"Predicate for ε.
NOTE: we may have different empty RHS with actions."
(and (listp rhs)
(eql 'seq (rhs-operator rhs))
(null (rhs-body rhs))))
(defun singleton-sequence-rhs-p (rhs)
;; (seq (postfix-expression-item) (action…))
(and (listp rhs)
(eql 'seq (rhs-operator rhs))
(listp (rhs-body rhs))
(= 1 (length (rhs-body rhs)))))
(defun right-recursive-rhs-p (non-terminal rhs)
(and (listp rhs)
(eql 'seq (rhs-operator rhs))
(eql non-terminal (first (last (rhs-body rhs))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Cleaning the grammar rules:
;;;
;;;
;;; When stored inside the grammar structure, rules must be of this
;;; cleaned form:
;;;
;;; rule := (<lhs> <rhs>) .
;;; lhs := <non-terminal> .
;;; rhs := (seq <items> <actions>)
;;; | (rep <items>)
;;; | (opt <items>)
;;; | (alt <items>) .
;;; items := ( <word>* ) .
;;; word := <rhs> | <terminal> | <non-terminal> .
;;; actions := ( <form>* ) .
;;;
;;; - a SEQ rhs may have 0 or more items in its <items> list.
;;; - a REP rhs should have exactly 1 SEQ item in its <items> list.
;;; - a OPT rhs should have exactly 1 SEQ item in its <items> list.
;;; - a ALT rhs should have 1 or more items in its <items> list.
;;;
;;; ε is represented as (seq () ('nil))
;;; ε is not expected from the user rules, but is generated in
;;; normalized grammars.
;;;
;;;
;;; FIND-RHSES returns a list of <rhs>s.
;;; FIND-RHS returns a <rhs>.
;;; Notice: if there are several rules for the same non-terminal,
;;; find-RHS returns a single ALT rhs with all the rhs of the rules of
;;; that non-terminal.
;;;
(defun split-action (rhs)
"
RHS: A rule right-hand-side, of the form: item* [:action action*].
RETURN: The sentence; the action forms.
"
(declare (inline))
(let ((separator (position :action rhs)))
(if separator
(values (subseq rhs 0 separator) (subseq rhs (1+ separator)))
(values rhs nil))))
(defun clean-seq (expr)
"RETURN: A cleaned version of the SEQ EXPR."
(multiple-value-bind (rhs actions) (split-action (cdr expr))
(let ((actions (or actions `(,(dollar 0))))
(items (mapcar (lambda (item) (clean item)) rhs)))
(if (and (null actions) (or (null items) (null (cdr items))))
(car items)
(make-rhs :operator 'seq :body items :actions actions)))))
(defun clean-with-action (expr)
"RETURN: A cleaned version of the the EXPR which must be either an OPT or a REP expression."
(multiple-value-bind (rhs actions) (split-action (cdr expr))
(if (null actions)
(if (null rhs)
*empty-rhs*
(list (car expr) (list (clean-seq `(seq ,@rhs)))))
(list (car expr) (list (clean-seq `(seq ,@rhs :action ,@actions)))))))
(defun clean-rep (expr) (clean-with-action expr))
(defun clean-opt (expr) (clean-with-action expr))
(defun clean-alt (expr)
"RETURN: A cleaned version of the ALT EXPR."
(assert (not (find :action expr))
() "An ALT rule cannot have :ACTION~%Erroneous rule: ~S" expr)
(let ((items (mapcar (function clean) (cdr expr))))
(if (null (cdr items))
(car items)
`(alt ,(mapcan (lambda (item)
(if (and (consp item) (eql 'alt (car item)))
(second item)
(list item)))
items)))))
(defun clean (expr)
"RETURN: A cleanred version of the expression EXPR,
which can be a terminal, a non-terminal or a SEQ, a REP, a OPT or an ALT expression."
(if (atom expr)
expr
(ecase (car expr)
((seq) (clean-seq expr))
((rep) (clean-rep expr))
((alt) (clean-alt expr))
((opt) (clean-opt expr)))))
(defun clean-rules (rules)
"
RULES: a list of (--> non-terminal . rhs) rules.
RETURN: an equivalent, cleaned list of rules.
"
(mapcar (lambda (rule)
(destructuring-bind (--> non-terminal &rest items) rule
(assert (string= --> '-->)
() "Rules should be written as (--> <non-terminal> <rhs> [:action <form>...])~%~
Invalid rule: ~S" rule)
(handler-case
`(,non-terminal ,(clean
(cond
((find :action items)
`(seq ,@items))
((and (= 1 (length items))
(listp (first items)))
(first items))
(t
`(seq ,@items :action `(,',non-terminal ,@,(dollar 0)))))))
(error (err)
(error "While cleaning rule ~S~%~A" rule err)))))
rules))
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defgeneric compute-all-terminals (grammar))
(defmethod compute-all-terminals ((grammar grammar))
(labels ((find-strings (items)
(cond
((stringp items) (list items))
((atom items) '())
(t (mapcan (function find-strings) (second items))))))
(setf (grammar-all-terminals grammar)
(delete-duplicates
(nconc
(mapcar (function first) (grammar-terminals grammar))
(mapcan (function find-strings)
(mapcar (function second) (grammar-rules grammar))))
:test (function word-equal)))))
(defgeneric compute-all-non-terminals (grammar))
(defmethod compute-all-non-terminals ((grammar grammar))
(labels ((find-symbols (items)
(cond
((symbolp items) (list items))
((atom items) '())
(t (mapcan (function find-symbols) (second items))))))
(setf (grammar-all-non-terminals grammar)
(nset-difference
(delete-duplicates
(nconc
(list (grammar-start grammar))
(mapcar (function first) (grammar-rules grammar))
(mapcan (function find-symbols)
(mapcar (function second) (grammar-rules grammar)))))
(grammar-all-terminals grammar)))))
(defgeneric terminalp (grammar item))
(defmethod terminalp (grammar item)
"
RETURN: whether ITEM is a terminal in the GRAMMAR.
"
(member item (grammar-all-terminals grammar)
:test (function word-equal)))
(defgeneric non-terminal-p (grammar item))
(defmethod non-terminal-p (grammar item)
"
RETURN: whether ITEM is a non-terminal symbol in the GRAMMAR.
" (member item (grammar-all-non-terminals grammar)))
(defgeneric find-rhses (grammar non-terminal))
(defmethod find-rhses (grammar non-terminal)
"
RETURN: all the right-and-sides of rules with NON-TERMINAL as left-hand-side.
PRE: (non-terminal-p non-terminal)
"
(let ((rhses (mapcar (function second)
(remove-if-not (lambda (rule) (eql non-terminal (first rule)))
(grammar-rules grammar)))))
(if (null rhses)
(error "~s is not a non-terminal in the grammar ~A"
non-terminal (grammar-name grammar))
rhses)))
(defgeneric find-rhs (grammar non-terminal))
(defmethod find-rhs (grammar non-terminal)
"
RETURN: the right-hand-sides with NON-TERMINAL as left-hand-side as a
single ALT expression (or just the right-hand-side if there's
only one).
PRE: (non-terminal-p non-terminal)
"
(let ((rhses (find-rhses grammar non-terminal)))
(if (null (cdr rhses))
(car rhses)
`(alt ,rhses))))
;;; To implement the follow-set function we need to put the grammar
;;; into a normal form.
(defgeneric nullablep (grammar rhs))
(defgeneric compute-firsts-sets (grammar))
(defgeneric compute-follow-sets (grammar))
(defmethod compute-firsts-sets ((grammar normalized-grammar))
"
DO: Signals an error if there are duplicates in the first set of a non-terminal.
RETURN: A hash-table containing the firsts-set for each symbol of the
grammar. (terminals and non terminals).
"
(let ((firsts-sets (make-hash-table :test (function equal))))
(labels ((firsts-set (symbol)
(let ((entry (gethash symbol firsts-sets)))
(cond (entry
(if (eq :error entry)
(error "There's a left recursion involving the symbol ~S in the grammar ~A"
symbol (grammar-name grammar))
entry))
((terminalp grammar symbol)
(setf (gethash symbol firsts-sets)
(list symbol)))
((compute-firsts-set symbol)))))
(compute-firsts-set (non-terminal)
(setf (gethash non-terminal firsts-sets) :error)
(let ((firsts-set '()))
(dolist (rhs (find-rhses grammar non-terminal))
(destructuring-bind (seq body &optional action) rhs
(declare (ignore seq action))
(if (null body)
(push nil firsts-set)
(loop
:with all-firsts := '()
:for item :in body
:for firsts := (firsts-set item)
:do (setf all-firsts (union firsts (delete nil all-firsts)))
:while (member nil firsts)
:finally (prependf firsts-set all-firsts)))))
(let ((unique-firsts-set (remove-duplicates firsts-set :test (function equal))))
(assert (= (length firsts-set) (length unique-firsts-set))
() "There are duplicates in the first sets of the rules for the non-terminal ~S: ~S"
non-terminal (duplicates firsts-set))
(setf (gethash non-terminal firsts-sets) unique-firsts-set)))))
(map nil (lambda (terminal)
(handler-case
(firsts-set terminal)
(error (err)
(error "While computing the firsts set of terminal ~S~%~A"
terminal err))))
(grammar-all-terminals grammar))
(map nil (lambda (non-terminal)
(handler-case
(firsts-set non-terminal)
(error (err)
(error "While computing the firsts set of non-terminal ~S~%~A"
non-terminal err))))
(grammar-all-non-terminals grammar)))
firsts-sets))
(defmethod nullablep ((grammar grammar) rhs)
"
RHS: A terminal or a non-terminal of the GRAMMAR, or a list thereof.
RETURN: Whether ε can be derived from rhs according to the GRAMMAR.
"
(cond
((null rhs)
t)
((listp rhs)
(every (lambda (word) (nullablep grammar word)) rhs))
((terminalp grammar rhs)
nil)
((non-terminal-p grammar rhs)
(labels ((nullable-rhs-p (rhs)
(if (atom rhs)
(nullablep grammar rhs)
(ecase (rhs-operator rhs)
((seq) (every (lambda (item) (nullable-rhs-p item)) (rhs-body rhs)))
((alt) (some (lambda (item) (nullable-rhs-p item)) (rhs-body rhs)))
((opt rep) t)))))
(nullable-rhs-p (find-rhs grammar rhs))))))
(defvar *eof-symbol* (make-symbol "EOF")
"The symbol used to denote the End-Of-Source in the follow-sets.")
(defmethod compute-follow-sets ((grammar normalized-grammar))
"
RETURN: A hash-table containing the follow-set for each non-terminal
of the grammar.
"
(let ((base-constraints '())
(recursive-constraints '()))
(flet ((firsts-set (item) (firsts-set grammar item)))
;; {$EOF$} ⊂ (follow-set start)
(push `(subset (set ,*eof-symbol*) (follow-set ,(grammar-start grammar)))
base-constraints)
(dolist (rule (grammar-rules grammar))
(destructuring-bind (non-terminal (seq symbols action)) rule
(declare (ignore seq action))
(when symbols
(loop
:for current :on symbols
:for n = (car current)
:for beta = (cdr current)
:do (when (non-terminal-p grammar n)
(let ((m (firsts-set beta)))
(when beta
;; (firsts-set beta)∖{ε} ⊂ (follow-set n)
(push `(subset (set ,@m) (follow-set ,n)) base-constraints))
(when (and (not (eql n non-terminal)) (nullablep grammar beta))
;; (follow-set non-terminal) ⊂ (follow-set n)
(push (list non-terminal n) recursive-constraints)))))))))
(let ((follow-sets (make-hash-table)))
;; initialize the follow-sets:
(dolist (non-terminal (grammar-all-non-terminals grammar))
(setf (gethash non-terminal follow-sets) '()))
;; apply the base-constraints:
(loop
:for constraint :in base-constraints
:do (destructuring-bind (subset (set &rest elements) (follow-set non-terminal)) constraint
(declare (ignore subset set follow-set))
(setf (gethash non-terminal follow-sets)
(union (gethash non-terminal follow-sets)
(remove nil elements)))))
;; resolve the recursive constraints:
(solve-constraints recursive-constraints
(lambda (subset superset)
(let ((old-cardinal (length (gethash superset follow-sets))))
(setf (gethash superset follow-sets)
(union (gethash subset follow-sets)
(gethash superset follow-sets)))
(/= (length (gethash superset follow-sets)) old-cardinal))))
follow-sets)))
(defgeneric firsts-set (grammar non-terminal-or-sentence)
(:documentation "RETURN: the firsts-set of the NON-TERMINAL-OR-SENTENCE in the GRAMMAR.")
(:method ((grammar grammar) non-terminal-or-sentence)
(firsts-set (grammar-normalized-grammar grammar) non-terminal-or-sentence))
(:method ((grammar normalized-grammar) non-terminal-or-sentence)
(let ((firsts-sets (grammar-firsts-sets grammar)))
(labels ((firsts-set (item)
(cond
((null item) nil)
((atom item)
(multiple-value-bind (firsts-set presentp) (gethash item firsts-sets)
(if presentp
firsts-set
(error "~S is not a symbol of the grammar ~A"
item (grammar-name grammar)))))
(t (loop
:with result = '()
:for itemus :in item
:for firsts-set = (firsts-set itemus)
:do (prependf result firsts-set)
:while (member nil firsts-set)
:finally (return (delete-duplicates result :test (function equal))))))))
(firsts-set non-terminal-or-sentence)))))
(defgeneric follow-set (grammar non-terminal)
(:documentation "RETURN: the follow-set of the NON-TERMINAL in the GRAMMAR.")
(:method ((grammar grammar) non-terminal)
(follow-set (grammar-normalized-grammar grammar) non-terminal))
(:method ((grammar normalized-grammar) non-terminal)
(multiple-value-bind (follow-set presentp)
(gethash non-terminal (grammar-follow-sets grammar))
(if presentp
follow-set
(error "~S is not a non-terminal of the grammar ~A"
non-terminal (grammar-name grammar))))))
(defgeneric rhs-firsts-set (grammar non-terminal rhs)
(:method (grammar non-terminal rhs)
(let ((fs (firsts-set grammar rhs)))
(if (member nil fs)
(remove-duplicates (union fs (follow-set grammar non-terminal)))
fs))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Normalization of the grammar.
;;;
;;;
;;; Each rule is put under the form: a --> ε or a --> e a
;;;
;;; Normalized grammar rules:
;;;
;;; rule := (<lhs> <rhs>) .
;;; lhs := <non-terminal> .
;;; rhs := (seq <items> <actions>) .
;;; items := ( <word>* ) .
;;; word := <rhs> | <terminal> | <non-terminal> .
;;; actions := ( <form>* ) .
;;; ε is represented as (seq () ('nil))
;;;
(defun make-new-non-terminal (base-nt non-terminals)
(loop
:for i :from 1
:for new-nt = (scat base-nt '- (prin1-to-string i))
:while (member new-nt non-terminals)
:finally (return new-nt)))
(defun simplify-normalized-grammar-rules (rules non-terminals &key verbose)
(flet ((used (nt rules)
(loop :for (nil (nil rhs nil)) :in rules
:thereis (member nt rhs))))
(loop
:with $1action := (list (dollar 1))
:for rule1 :in (remove-if-not (lambda (rule)
(let ((rhs (second rule)))
(and (singleton-sequence-rhs-p rhs)
(member (first (rhs-body rhs)) non-terminals)
(equalp $1action (rhs-actions rhs)))))
rules)
:for (nt1 (nil (nt2) nil)) := rule1
:for prods := (remove nt2 rules :key (function first) :test-not (function eql))
:for other-rules := (remove rule1 rules)
:do (when verbose
(format t "~&Considering rule ~S~%" rule1)
(format t "~& Non terminal ~S has ~D productions and is ~:[not ~;~]used elsewhere.~%" nt2 (length prods) (used nt2 other-rules)))
:when (and (= 1 (length prods))
(not (used nt2 other-rules)))
:do (let ((rule2 (first prods)))
(setf rules (cons `(,nt1 ,(second rule2))
(remove rule2 other-rules))
non-terminals (remove nt2 non-terminals)))
(when verbose
(format t "~& subtituted new rule ~S~%" (first rules)))
:finally (return (values rules non-terminals)))))
(defun normalize-grammar-rules (rules non-terminals)
"
DO: Substitute any sub-expressions in the rhs with a new
non-terminal and a new production. Then replace the REP, OPT,
and ALT rules with SEQ rules and new produtions.
RETURN: the new production set; the new non-terminal set
"
(simplify-normalized-grammar-rules
(loop
:while rules
:collect (let ((rule (pop rules)))
(destructuring-bind (nt rhs) rule
(assert rhs (rule) "Invalid rule, missing right-hand-side: ~S" rule)
(labels ((new-rule (nt rhs)
(push nt non-terminals)
(push (list nt rhs) rules))
(process-item (item)
(if (listp item)
(let ((new-nt (make-new-non-terminal nt non-terminals)))
(new-rule new-nt item)
new-nt)
item)))
(let ((op (rhs-operator rhs)))
(ecase op
((seq)
(destructuring-bind (op items actions) rhs
(list nt (list* op (mapcar (function process-item) items)
(when actions (list actions))))))
((rep)
;; a --> (rep e)
;; -------------
;; a --> ε :action '()
;; a --> e a :action (cons $1 $2)
(destructuring-bind (op items) rhs
(declare (ignore op))
(assert (null (rest items)))
(let ((item (first items)))
(new-rule nt (if (singleton-sequence-rhs-p item)
`(seq (,(process-item (first (second item))) ,nt)
((cons (progn ,@(third item)) ,(dollar 2))))
`(seq (,(process-item item) ,nt)
((cons ,(dollar 1) ,(dollar 2)))))))
(list nt *empty-rhs*)))
((opt)
;; a --> (opt e)
;; -------------
;; a --> ε :action '()
;; a --> e :action $1
(destructuring-bind (op items) rhs
(declare (ignore op))
(assert (null (rest items)))
(let ((item (first items)))
(new-rule nt (if (singleton-sequence-rhs-p item)
`(seq (,(process-item (first (second item))))
(,@(third item)))
`(seq (,(process-item item))
(,(dollar 1))))))
(list nt *empty-rhs*)))
((alt)
;; a --> (alt e₁ ... eν)
;; -------------
;; a --> e₁ :action $1
;; ...
;; a --> eν :action $1
(destructuring-bind (op items) rhs
(declare (ignore op))
(let ((new-items (mapcar (function process-item) items)))
(dolist (new-item (rest new-items))
(new-rule nt (if (singleton-sequence-rhs-p new-item)
`(seq (,(process-item (first (second new-item))))
((progn ,@(third new-item))))
`(seq (,new-item) (,(dollar 1))))))
(list nt (if (singleton-sequence-rhs-p (first new-items))
`(seq (,(first (second (first new-items))))
((progn ,@(third (first new-items)))))
`(seq (,(first new-items)) (,(dollar 1))))))))
(otherwise (error "Invalid operator ~S in rule ~S" op rule))))))))
non-terminals))
(defun normalized-rule-p (rule)
(and (listp rule)
(= 3 (length rule))
(eq 'seq (first rule))
(listp (second rule))
(listp (third rule))))
(defun normalized-rules-p (rules)
(every (function normalized-rule-p) rules))
(defun make-normalized-grammar (&key name terminals start rules (scanner t) (skip-spaces t))
"Return a new normalized grammar."
(let ((new-grammar (%make-normalized-grammar
:name name
:terminals terminals
:start start
:rules rules
:scanner scanner
:skip-spaces skip-spaces)))
(compute-all-terminals new-grammar)
(compute-all-non-terminals new-grammar)
(let ((original-non-terminals (grammar-all-non-terminals new-grammar)))
(setf (grammar-rules new-grammar) (if (normalized-rules-p rules)
rules
(normalize-grammar-rules rules (grammar-all-non-terminals new-grammar))))
(compute-all-non-terminals new-grammar)
(setf (normalized-grammar-%synthesized-non-terminals new-grammar)
(set-difference (grammar-all-non-terminals new-grammar)
original-non-terminals)))
(compute-first-follow new-grammar)
new-grammar))
(defgeneric normalize-grammar (grammar)
(:documentation "Return a new normalized grammar parsing the same language as GRAMMAR.")
(:method ((grammar grammar))
(let ((normalized-grammar (make-normalized-grammar
:name (scat 'normalized- (grammar-name grammar))
:terminals (grammar-terminals grammar)
:start (grammar-start grammar)
:rules (grammar-rules grammar)
:scanner (grammar-scanner grammar)
:skip-spaces (grammar-skip-spaces grammar))))
(register-grammar normalized-grammar)
(setf (normalized-grammar-%original-grammar normalized-grammar) grammar)
normalized-grammar))
(:method ((grammar normalized-grammar))
grammar))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Elimination of left recursion.
;;;
;;; rule := (<lhs> <rhs>) .
;;; lhs := <non-terminal> .
;;; rhs := (seq <items> <actions>) .
;;; items := ( <word>* ) .
;;; word := <rhs> | <terminal> | <non-terminal> .
;;; actions := ( <form>* ) .
;;; ε is represented as (seq () ('nil))
(defgeneric add-production (grammar non-terminal rhs))
(defgeneric remove-production (grammar non-terminal rhs))
(defgeneric eliminate-left-recursion (grammar))
(defgeneric eliminate-left-recursive-p (grammar))
(defmethod add-production ((grammar grammar) non-terminal rhs)
(assert (not (terminalp grammar non-terminal)))
(push (list non-terminal rhs) (grammar-rules grammar))
(pushnew non-terminal (grammar-all-non-terminals grammar)))
(defmethod remove-production ((grammar grammar) non-terminal rhs)
(setf (grammar-rules grammar) (remove-if (lambda (rule)
(and (eql non-terminal (first rule))
(eql rhs (second rule))))
(grammar-rules grammar))))
(defmethod eliminate-left-recursion ((grammar normalized-grammar))
(loop
:with non-terminals := (grammar-all-non-terminals grammar)
:with nts := (coerce non-terminals 'vector)
:for i :below (length nts)
:for nt1 := (aref nts i)
:for prods := (find-rhses grammar nt1)
:do (loop :for j :below i
:for nt2 := (aref nts j)
:do (loop :for prod1 :in (remove nt2 prods
:key (lambda (rhs) (first (rhs-body rhs)))
:test-not (function eq))
:for gamma := (rest (rhs-body prod1))
:do (remove-production grammar nt1 prod1)
(loop :for prod2 :in (find-rhses grammar nt2)
:do (add-production grammar nt1 `(seq (,prod2 ,@gamma) ,(rhs-actions prod1))))))
(loop
:with nt1* := (make-new-non-terminal nt1 non-terminals)
:for prod1 :in (find-rhses grammar nt1)
:do (push nt1* non-terminals)
(remove-production grammar nt1 prod1)
(add-production grammar nt1* *empty-rhs*)
(if (eq nt1 (first (rhs-body prod1)))
(add-production grammar nt1* `(seq ,(append (rest (rhs-body prod1)) (list nt1*))
(#:TODO-action???)))
(add-production grammar nt1 `(seq ,(append (rhs-body prod1) (list nt1*))
(#:TODO-action???)))))
:finally (compute-all-non-terminals grammar))
grammar)
(defmethod eliminate-left-recursive-p ((grammar normalized-grammar))
(error "Not implemented yet."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Generator -- LISP
;;;
(defgeneric gen-in-firsts (target firsts))
(defgeneric gen-scanner-function-name (target grammar))
(defgeneric gen-scanner-class-name (target grammar))
(defgeneric gen-parse-function-name (target grammar non-terminal))
(defgeneric generate-parsing-expression (target grammar non-terminal item))
(defgeneric generate-parsing-sequence (target grammar non-terminal rhs))
(defgeneric generate-non-terminal-parsing-expression (target grammar non-terminal))
;;;------------------------------------------------------------
;;; Scanner generator
;;;------------------------------------------------------------
(defmethod gen-scanner-function-name ((target (eql :lisp)) (grammar grammar))
(scat "SCAN-" (grammar-name grammar)))
(defmethod gen-scanner-class-name ((target (eql :lisp)) (grammar grammar))
(scat (grammar-name grammar) "-SCANNER"))
(defun gen-trace (fname form trace)
(if trace
`(progn
,form
(trace ,fname))
form))
(defun tracep (keyword trace)
(or (eql keyword trace)
(and (listp trace) (member keyword trace))))
(defparameter *spaces*
(coerce '(#\space #\newline #\tab) 'string))
(defparameter *alphanumerics*
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
(defmethod generate-scanner-for-grammar ((target (eql :lisp)) grammar &key (trace nil))
(case (grammar-scanner grammar)
((t)
(let* ((scanner-class-name (gen-scanner-class-name target grammar))
(terminals (mapcar (lambda (terminal)
(etypecase terminal
(string terminal)
(symbol (let ((entry (find terminal (grammar-terminals grammar)
:key (function first))))
(if entry
entry
(error "Undefined terminal ~S" terminal))))))
(grammar-all-terminals grammar)))
(form (generate-scanner scanner-class-name
'buffered-scanner
terminals
(grammar-skip-spaces grammar)
*alphanumerics*
*spaces*)))
(setf (grammar-scanner grammar) scanner-class-name)
`(progn
,form
(setf (grammar-scanner (grammar-named ',(grammar-name grammar))) ',scanner-class-name)
,@(when trace
`((trace scan-next-token)))
',scanner-class-name)))
(otherwise
;; Don't do anything
`',(grammar-scanner grammar))))
;;;------------------------------------------------------------
;;; RDP Parser Generator
;;;------------------------------------------------------------
(defvar *non-terminal-stack* '()
"For error reporting.")
(defmacro with-non-terminal ((non-terminal scanner) &body body)
(declare (ignorable scanner))
`(let ((*non-terminal-stack* (cons ',non-terminal *non-terminal-stack*)))
;; (print (list :token (scanner-current-token ,scanner)
;; :non-terminals *non-terminal-stack*))
,@body))
(defun error-unexpected-token (scanner expected-tokens production)
(restart-case
(let ((err (make-condition 'unexpected-token-error
:file (scanner-file scanner)
:line (scanner-line scanner)
:column (scanner-column scanner)
:state (scanner-state scanner)
;; :grammar (grammar-named ',(grammar-name grammar))
:scanner scanner
:non-terminal-stack (copy-list *non-terminal-stack*)
:expected-tokens expected-tokens
;; TODO: optionally remove debugging data:
:format-control "Unexpected token ~A [~S] (~S)~:[~@[~%Expected ~{~A~}~]~;~%Expected one of ~{~A~^, ~}~]~%~S~@[~%~S~]"
:format-arguments (list
(scanner-current-token scanner)
(class-of (scanner-current-token scanner))
(scanner-current-text scanner)
(cdr expected-tokens)
expected-tokens
*non-terminal-stack*
production))))
(error err))
(skip-token-and-continue ()
:report (lambda (stream)
(format stream "Skip token ~:[~A ~A~;~*<~A>~], and continue"
(word-equal (scanner-current-token scanner)
(scanner-current-text scanner))
(scanner-current-token scanner)
(scanner-current-text scanner)))
(scan-next-token scanner)
(return-from error-unexpected-token :continue))
(skip-tokens-until-expected-and-retry ()
:report (lambda (stream)
(format stream "Skip tokens until one expected ~A is found, and retry"
expected-tokens))
(loop
:for token := (scan-next-token scanner)
:while (and token (if (listp expected-tokens)
(member token expected-tokens
:test (function word-equal))
(word-equal token expected-tokens))))
(return-from error-unexpected-token :retry))))
(defmethod gen-parse-function-name ((target (eql :lisp)) (grammar grammar) non-terminal)
(scat (grammar-name grammar) "/PARSE-" non-terminal))
(defmethod gen-in-firsts ((target (eql :lisp)) firsts)
(if (null (cdr firsts))
`(word-equal (scanner-current-token scanner) ',(car firsts))
`(member (scanner-current-token scanner) ',firsts
:test (function word-equal))))
(defmacro retrying-until (until result expected-tokens production)
`(loop
:until ,until
:do (ecase (error-unexpected-token scanner ',expected-tokens ',production)
(:retry)
(:continue (loop-finish)))
:finally (return ,result)))
(defmethod generate-non-terminal-parser-function ((target (eql :lisp)) (grammar grammar) non-terminal &key (trace nil))
(let* ((fname (gen-parse-function-name target grammar non-terminal))
(form `(defun ,fname (scanner)
,(format nil "~S" `(--> ,non-terminal ,(find-rhs grammar non-terminal)))
;; ,(format nil "~S" (assoc non-terminal (grammar-rules grammar)))
(with-non-terminal (,non-terminal scanner)
,(generate-parsing-expression target grammar non-terminal (find-rhs grammar non-terminal))))))
(gen-trace fname `(progn (fmakunbound ',fname) ,form) trace)))
(defmethod generate-parser ((target (eql :lisp)) (grammar grammar) &key (trace nil))
(let* ((fname (scat "PARSE-" (grammar-name grammar)))
(form `(defun ,fname (source)
"
SOURCE: When the grammar has a scanner generated, or a scanner class
name, SOURCE can be either a string, or a stream that will be
scanned with the generated scanner. Otherwise, it should be a
SCANNER instance.
"
(let ((scanner ,(if (grammar-scanner grammar)
`(make-instance ',(grammar-scanner grammar) :source source)
'source)))
(advance-line scanner)
(with-non-terminal (,(grammar-name grammar) scanner)
(prog1 (,(gen-parse-function-name target grammar (grammar-start grammar))
scanner)
(unless (scanner-end-of-source-p scanner)
(cerror "Continue"
'parser-end-of-source-not-reached
:file (scanner-file scanner)
:line (scanner-line scanner)
:column (scanner-column scanner)
:grammar (grammar-named ',(grammar-name grammar))
:scanner scanner
:non-terminal-stack (copy-list *non-terminal-stack*)))))))))
(gen-trace fname `(progn (fmakunbound ',fname) ,form) trace)))
;;;------------------------------------------------------------
;;; RDP Parser Generator for non-normalized grammars
;;;------------------------------------------------------------
(defgeneric named-item-p (grammar item)
(:documentation "
Whether ITEM is a terminal or non-terminal symbol of the grammar that
should be bound for actions.
")
(:method ((grammar grammar) item)
(and (symbolp item)
(or (non-terminal-p grammar item)
(terminalp grammar item))))
(:method ((grammar normalized-grammar) item)
(and (symbolp item)
(or (and (non-terminal-p grammar item)
(not (member item (normalized-grammar-%synthesized-non-terminals grammar))))
(terminalp grammar item)))))
(defmethod generate-parsing-sequence ((target (eql :lisp)) (grammar grammar) non-terminal rhs)
(destructuring-bind (seq items actions) rhs
(declare (ignore seq))
(let* ((dollars (loop :for i :from 1 :to (length items)
:collect (dollar i)))
(ignorables dollars))
`(let* (,@(let ((increments (make-hash-table)))
(mapcan (lambda (dollar item)
(cons
;; $n variables are bound to
;; synthesized parsed elements:
;; let* is used, so $2 action
;; can use $1 non-terminal.1 etc.
`(,dollar ,(generate-parsing-expression target grammar non-terminal item))
;; additionally, non-terminal
;; and non-terminal.n names are
;; defined:
(when (named-item-p grammar item)
(let* ((index (incf (gethash item increments 0)))
(igno (scat item "." (prin1-to-string index))))
(pushnew item ignorables)
(push igno ignorables)
(append (when (= 1 index)
(list (list item dollar)))
(list (list igno dollar)))))))
dollars items))
;; $0 collects all the parsed elements in a list as a default synthesized value.
(,(dollar 0) (list ,@dollars)))
(declare (ignorable ,(dollar 0) ,@ignorables))
,@actions))))
(defmethod generate-parsing-expression ((target (eql :lisp)) (grammar grammar) non-terminal rhs)
;; If we want to generate the parser directly from the grammar with
;; seq/rep/opt/alt, then we need to replicate the algorithm for the
;; firsts-set of sentences here. :-(
;; Unfortunately, the follow-set is not implemented here.
(labels ((es-firsts-set (extended-rhs)
;; EXTENDED-RHS: a RHS that can contain any grammar operator: SEQ, REP, OPT, or ALT.
;; RETURN: the firsts set of the given extended-rhs
(if (atom extended-rhs)
(firsts-set grammar extended-rhs)
(ecase (rhs-operator extended-rhs)
((seq) (if (null (rhs-body extended-rhs))
'(nil)
(loop
:with all-firsts = '()
:for item :in (rhs-body extended-rhs)
:for firsts = (es-firsts-set item)
:do (setf all-firsts (union firsts (delete nil all-firsts)))
:while (member nil firsts)
:finally (return all-firsts))))
((rep) (es-firsts-set (first (rhs-body extended-rhs))))
((opt) (adjoin nil (es-firsts-set (first (rhs-body extended-rhs)))))
((alt) (remove-duplicates (reduce (function append) (rhs-body rhs)
:key (function es-firsts-set))))))))
(if (atom rhs)
(cond
((terminalp grammar rhs)
`(accept scanner ',rhs))
((non-terminal-p grammar rhs)
`(,(gen-parse-function-name target grammar rhs) scanner))
(t
(error "Invalid item ~S found in rule for ~S" rhs non-terminal)))
(ecase (rhs-operator rhs)
((seq)
(generate-parsing-sequence target grammar non-terminal rhs))
((rep)
`(loop
:while ,(gen-in-firsts target (es-firsts-set (first (rhs-body rhs))))
:collect ,(generate-parsing-expression target grammar non-terminal (first (rhs-body rhs)))))
((opt)
`(when ,(gen-in-firsts target (remove nil (es-firsts-set (first (rhs-body rhs)))))
,(generate-parsing-expression target grammar non-terminal (first (rhs-body rhs)))))
((alt)
(let* ((follows '(#:follows))
(count-empty 0)
(empty-item nil)
(empty-firsts-set nil)
(firsts-sets (mapcar (lambda (item)
(let ((firsts-set (es-firsts-set item)))
`(item ,item firsts ,firsts-set)
(when (member nil firsts-set)
(when (plusp count-empty)
(error "More than one alternative has an empty derivation: ~S" rhs))
(incf count-empty)
(setf empty-item item
empty-firsts-set firsts-set))
firsts-set))
(rhs-body rhs))))
(flet ((gen-clause (firsts-set next-sets item)
(declare (ignore next-sets))
`(,(gen-in-firsts target (remove nil firsts-set))
,(generate-parsing-expression target grammar non-terminal item))))
`(cond
,@(let ((firsts-sets (remove empty-firsts-set firsts-sets)))
(mapcar (function gen-clause)
firsts-sets
(append (rest firsts-sets) follows)
(remove empty-item (rhs-body rhs))))
,@(when (and empty-item (< 1 (length empty-firsts-set)))
`(,(gen-clause empty-firsts-set follows empty-item)))
,(if empty-item
`(t (let ((,(dollar 0) '()))
(declare (ignorable ,(dollar 0)))
,@(if (null (rhs-body empty-item))
(rhs-actions empty-item)
`(,(dollar 0)))))
`(t (error-unexpected-token scanner
',(mapcan (lambda (item)
(copy-list (es-firsts-set item)))
(rhs-body rhs))
nil
;; ',(assoc rhs (grammar-rules grammar))
)))))))))))
;;;------------------------------------------------------------
;;; RDP Parser Generator for normalized grammars
;;;------------------------------------------------------------
(defmethod generate-parsing-expression ((target (eql :lisp)) (grammar normalized-grammar) non-terminal rhs)
(cond
((terminalp grammar rhs)
`(accept scanner ',rhs))
((non-terminal-p grammar rhs)
`(,(gen-parse-function-name target grammar rhs) scanner))
((eql 'seq (rhs-operator rhs))
(generate-parsing-sequence target grammar non-terminal rhs))
(t (error "Invalid item ~S found in rule for ~S" rhs non-terminal))))
(defmethod generate-non-terminal-parsing-expression ((target (eql :lisp)) (grammar normalized-grammar) non-terminal)
(let* ((rhses (find-rhses grammar non-terminal))
;; (firsts (firsts-set grammar non-terminal))
;; (follows (follow-set grammar non-terminal))
(rule `(--> ,non-terminal (alt ,@rhses))))
;; #|DEBUG|#(format t "(--> ~A ~{~% ~A~})~%" non-terminal rhses)
(labels ((firsts-set (rhs)
(rhs-firsts-set grammar non-terminal (rhs-body rhs)))
(generic ()
(let* ((empty (find-if (function empty-rhs-p) rhses))
(rhses (remove-if (function empty-rhs-p) rhses))
(firsts (mapcar (function firsts-set) rhses)))
;; #|DEBUG|#(when empty (format t " empty~%"))
`(cond ,@(mapcar (lambda (firsts rhs)
(assert (eq 'seq (rhs-operator rhs)))
`(,(gen-in-firsts target firsts)
,(generate-parsing-expression target grammar non-terminal rhs)))
firsts rhses)
,@(unless empty
`((t (error-unexpected-token
scanner
',(remove-duplicates (reduce (function append) firsts))
',rule)))))))
(check-disjoint (sets)
(loop
:for ((aset . arhs) . rest) :on sets
:while rest
:do (loop
:for (bset . brhs) :in rest
:for inter := (intersection aset bset)
:do (when inter
(error "Non-disjoint rhses: ~% ~A --> ~S~% ~A --> ~S~% Intersection: ~S~%"
non-terminal arhs non-terminal brhs
(intersection aset bset))))))
(check-empties (empty base-firsts base-cases)
(when (rest empty)
(error "More than one empty rule: ~%~{ ~A --> ~S~%~}"
(mapcar (lambda (rhs) (list non-terminal rhs)) empty)))
(let ((empty-base-cases (loop
:for firsts :in base-firsts
:for rhs :in base-cases
:when (member nil firsts)
:collect rhs)))
(when (< (if empty 0 1) (length empty-base-cases))
(error "More than ~R rule reduces to empty: ~%~{ ~A --> ~S~%~}"
(if empty 0 1)
(mapcar (lambda (rhs) (list non-terminal rhs)) empty-base-cases)))))
(gen-cond-clause (firsts rhs finish)
`(,(gen-in-firsts target (remove nil firsts))
(push ,(generate-parsing-expression target grammar non-terminal
(if finish
rhs
`(seq ,(append (butlast (rhs-body rhs))
(list *empty-rhs*))
,(rhs-actions rhs))))
$items)
,@(when finish
`((loop-finish)))))
(generate-parse-loop (empty base-cases recursives)
(assert recursives)
(unless (or empty base-cases)
(error "Recursive rules without base case: ~%~{ ~A --> ~S~%~}"
(mapcar (lambda (rhs) (list non-terminal rhs)) rhses)))
(let ((base-firsts (mapcar (function firsts-set) base-cases))
(recu-firsts (mapcar (function firsts-set) recursives)))
(check-empties empty base-firsts base-cases)
(check-disjoint (mapcar (function cons)
(append base-firsts recu-firsts)
(append base-cases recursives)))
`(loop
:with $items := '()
:do (cond
,@(mapcar (lambda (firsts rhs) (gen-cond-clause firsts rhs nil))
recu-firsts recursives)
,@(mapcar (lambda (firsts rhs) (gen-cond-clause firsts rhs t))
base-firsts base-cases)
,@(if (or empty (find-if (lambda (firsts) (member nil firsts)) base-firsts))
`((t (loop-finish)))
`((t (error-unexpected-token scanner
',(remove-duplicates
(reduce (function append)
(append base-firsts recu-firsts)))
',rule)))))
:finally (return (reduce (function append)
(nreverse $items)
:initial-value nil))))))
(if rhses
(loop
:for rhs :in rhses
:if (empty-rhs-p rhs)
:collect rhs :into empties
:else :if (right-recursive-rhs-p non-terminal rhs)
:collect rhs :into recursives
:else
:collect rhs :into base-cases
:finally
(return (if recursives
(generate-parse-loop empties base-cases recursives)
(generic))))
(error "Non-terminal ~S has no rule in grammar ~S"
non-terminal (grammar-name grammar))))))
(defmethod generate-non-terminal-parser-function ((target (eql :lisp)) (grammar normalized-grammar) non-terminal &key (trace nil))
(let* ((fname (gen-parse-function-name target grammar non-terminal))
(form `(defun ,fname (scanner)
,(format nil "~S" `(--> ,non-terminal ,(find-rhs grammar non-terminal)))
(with-non-terminal (,non-terminal scanner)
,(generate-non-terminal-parsing-expression target grammar non-terminal)))))
(gen-trace fname `(progn (fmakunbound ',fname) ,form) trace)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
| 62,799 | Common Lisp | .lisp | 1,243 | 36.441673 | 150 | 0.51597 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 4c81b220017483c66c8d4160f8c1af0f91be68790e356d947341b4c80d80f39e | 4,831 | [
-1
] |
4,832 | guess-the-cat.lisp | informatimago_lisp/small-cl-pgms/guess-the-cat.lisp | (defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.GUESS-THE-CAT"
(:use "COMMON-LISP")
(:nicknames "GUESS-THE-CAT")
(:export "MAIN")
(:documentation "
https://www.youtube.com/watch?v=yZyx9gHhRXM
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.GUESS-THE-CAT")
(defparameter *box-count* 5)
(defvar *debug* nil)
(defun explanations ()
(format t "
Catch the Cat
A cat is hiding in one of ~:R boxes a that are lined up in a row.
The boxes are numbered from 1 to ~:*~:R.
Each night the cat hides in an adjacent box, exactly one number away.
Each morning, you can open a single box to try to find the cat.
Can you win this game of hide and seek?
What is your strategy to find the cat?
"
*box-count*)
(force-output))
(defun initial-cat-position ()
(1+ (random *box-count*)))
(defun new-cat-position (old-position)
(cond
((= 1 old-position) 2)
((= *box-count* old-position) (- *box-count* 1))
(t (if (zerop (random 2))
(- old-position 1)
(+ old-position 1)))))
(defun catch-the-cat ()
(let ((cat (initial-cat-position)))
(loop
:for guesses :from 1
:do (format *query-io* "~%The cat is hidden in one of the boxes from 1 to ~A.~%" *box-count*)
(when *debug*
(format *query-io* "~V@{~A~:*~}~*&~V@{~A~:*~}~&" (- cat 1) #\. (- *box-count* cat) #\.))
(format *query-io* "Your guess: ")
(finish-output *query-io*)
(let ((guess (let ((line (read-line *query-io*)))
(ignore-errors (parse-integer line :junk-allowed t)))))
(if (and (integerp guess) (<= 1 guess *box-count*))
(if (= guess cat)
(progn
(format *query-io* "~&You found the cat!~%")
(loop-finish))
(progn
(format *query-io* "~&You missed the cat!~%")
(setf cat (new-cat-position cat))))
(format *query-io* "~&Invalid input: type an integer from 1 to ~A.~%" *box-count*)))
:finally (format *query-io* "~&You guessed ~A times.~%" guesses))))
(defun main ()
(let ((*random-state* (make-random-state t)))
(explanations)
(catch-the-cat)))
| 2,237 | Common Lisp | .lisp | 56 | 32.625 | 101 | 0.568664 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 827f006ea84bdcfc73044f1eaacd67b7b182d1fc3ba0619bc08b039b751fa158 | 4,832 | [
-1
] |
4,833 | author-signature.lisp | informatimago_lisp/small-cl-pgms/author-signature.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: author-signature.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: Common-Lisp
;;;;DESCRIPTION
;;;;
;;;; This program compute an "author signature" from a text.
;;;; See: http://unix.dsu.edu/~johnsone/comp.html
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2003-03-13 <PJB> Creation.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2003 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.AUTHOR-SIGNATURE"
(:documentation
"This program compute an \"author signature\" from a text.
See: <http://unix.dsu.edu/~johnsone/comp.html>
Copyright Pascal J. Bourguignon 2003 - 2003
This package is provided under the GNU General Public License.
See the source file for details.")
(:use "COMMON-LISP")
(:export compare-texts tally-compare
tally-word-lengths tally-small-words
tally-percent split-words )
);;COM.INFORMATIMAGO.COMMON-LISP.AUTHOR-SIGNATURE
(in-package "COM.INFORMATIMAGO.COMMON-LISP.AUTHOR-SIGNATURE")
(defun stream-as-string (stream)
"
RETURN: A string containing all the character read from the stream.
"
(loop with result = ""
with eoln = (format nil "~%")
for line = (read-line stream nil nil)
while line
do (setq result (concatenate 'string result line eoln))
finally (return result))
);;STREAM-AS-STRING
(defun remove-ponctuation (text)
"
RETURN: A copy of the text string where all character not alphanumeric is
replaced by a space.
"
(setq text (copy-seq text))
(loop for i from 0 below (length text)
for ch = (char text i)
do (unless (alphanumericp ch) (setf (char text i) #\SPACE)))
text
);;REMOVE-PONCTUATION
(defun split-words (text)
"
RETURN: A list of words read from the text.
"
(with-input-from-string
(in (remove-ponctuation text))
(let ((result ())
(ch (read-char in nil nil)))
(loop while ch do
(loop while (and ch (eql #\SPACE ch)) ;;skip spaces
do (setq ch (read-char in nil nil)))
(loop while (and ch (not (eql #\SPACE ch)))
collect ch into word
do (setq ch (read-char in nil nil))
finally (when (< 0 (length word))
(push (make-array (list (length word))
:element-type 'character
:initial-contents word) result)))
)
(nreverse result)))
) ;;SPLIT-WORDS
(defun tally-word-lengths (word-list)
"
RETURN: An array containing the number of words of each length (in
slot 0 is stored the number of words greater than (length result),
and (length word-list).
"
;; max word length in French: 36.
(let* ((max-len 36)
(tally (make-array (list (1+ max-len))
:element-type 'fixnum
:initial-element 0))
)
(loop for word in word-list
for len = (length word)
for count = 0 then (1+ count)
do
(if (< max-len len)
(incf (aref tally 0))
(incf (aref tally len)))
finally (return (values tally count))))
);;TALLY-WORD-LENGTHS
(defun tally-small-words (word-list)
"
RETURN: An array containing the number of occurences of a list of
small words returned as third value.
The second value is (length word-list).
"
(let* ((small-words '("A" "BUT" "IN" "NO" "OUR" "THE" "US"
"WE" "WHICH" "WITH"))
(max-len (length small-words))
(tally (make-array (list (1+ max-len))
:element-type 'fixnum
:initial-element 0))
)
(loop for word in word-list
for count = 0 then (1+ count)
for pos = (position word small-words :test (function string-equal))
do
(if pos
(incf (aref tally (1+ pos)))
(incf (aref tally 0)))
finally (return (values tally count small-words))))
);;TALLY-SMALL-WORDS
;; (TALLY-SMALL-WORDS (SPLIT-WORDS (WITH-OPEN-FILE (IN "~/tmp/misc/test.txt" :DIRECTION :INPUT) (STREAM-AS-STRING IN))))
(defun tally-percent (tally count)
(let ((result (make-array (list (length tally))
:element-type 'float
:initial-element 0.0)))
(do ((i 0 (1+ i)))
((<= (length tally) i) result)
(setf (aref result i) (coerce (/ (aref tally i) count) 'float))))
);;TALLY-PERCENT
(defun module (vector)
"
RETURN: The module of the vector. [ sqrt(x^2+y^2+z^2) ]
"
(sqrt (apply (function +)
(map 'list (function (lambda (x) (* x x))) vector)))
);;MODULE
(defun tally-compare (tally-1 tally-2)
"
RETURN: The module and the vector of percentages of differences
between vectors tally-1 and tally-2.
"
(assert (= (length tally-1) (length tally-2)))
(let ((differences (make-array (list (length tally-1))
:element-type 'float
:initial-element 0.0)))
(do* ((i 0 (1+ i))
(d) (m))
((<= (length differences) i))
(setq d (abs (- (aref tally-1 i) (aref tally-2 i)))
m (max (aref tally-1 i) (aref tally-2 i)))
(setf (aref differences i) (if (= 0.0 m) m (coerce (/ d m) 'float))) )
(values (module differences) differences))
);;TALLY-COMPARE
(defun compare-texts (path-list tally-function)
(let ((tallies ()))
(mapc
(lambda (path)
(with-open-file (input path :direction :input)
(push (cons (namestring path)
(multiple-value-bind (tally c)
(funcall tally-function
(split-words (stream-as-string input)))
(tally-percent tally c))) tallies)))
path-list)
(do* ((t1 tallies (cdr t1))
(n-tally-1 (car t1) (car t1))
(tally-1 (cdr n-tally-1) (cdr n-tally-1)) )
((null t1))
(do* ((t2 (cdr t1) (cdr t2))
(n-tally-2 (car t2) (car t2))
(tally-2 (cdr n-tally-2) (cdr n-tally-2)) )
((null t2))
(multiple-value-bind
(m d) (tally-compare tally-1 tally-2)
(format t "~20A ~20A ~8A~% ~A~%~%"
(car n-tally-1) (car n-tally-2) m d))
))
tallies)
);;COMPARE-TEXTS
;; (COMPARE-TEXTS (DIRECTORY "i-*.txt") (FUNCTION TALLY-WORD-LENGTHS))
;; (COMPARE-TEXTS (DIRECTORY "i-*.txt") (FUNCTION TALLY-SMALL-WORDS))
;; (TALLY-COMPARE
;; (MULTIPLE-VALUE-BIND (TALLY C)
;; (TALLY-WORD-LENGTHS (SPLIT-WORDS STR))
;; (TALLY-PERCENT TALLY C))
;; (MULTIPLE-VALUE-BIND (TALLY C)
;; (TALLY-WORD-LENGTHS (SPLIT-WORDS STR2))
;; (TALLY-PERCENT TALLY C)))
;;;; author-signature.lisp -- 2004-03-14 01:32:40 -- pascal ;;;;
| 8,026 | Common Lisp | .lisp | 204 | 32.019608 | 120 | 0.570255 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 85e912f4cb87173630f8df17f4d0091ecb97c7c0b121c767b27710b74de336c4 | 4,833 | [
-1
] |
4,834 | le-compte-est-bon.lisp | informatimago_lisp/small-cl-pgms/le-compte-est-bon.lisp | ;; http://www.enseignement.polytechnique.fr/informatique/profs/Georges.Gonthier/pi98/compte.html
;;
;; Le compte est bon
;;
;; Sujet proposé par Jean-Eric Pin
;;
;; [email protected]
;;
;; Préambule
;;
;; ``Le compte est bon'' est l'une des composantes du jeu télévisé ``les
;; chiffres et les lettres'' qui a connu ses heures de gloire il y a
;; quelques années. Le but de ce projet est de réaliser un logiciel qui
;; donne la meilleure réponse à ce jeu dans un délai de quelques
;; secondes. Les règles du jeu
;;
;; Le joueur tire au hasard, sans remplacement, six plaques portant des
;; numéros parmi un ensemble de 28 plaques ainsi constitué
;;
;; 1. 20 plaques numérotées de 1 à 10 (2 par nombre)
;; 2. 2 plaques de 25
;; 3. 2 plaques de 50
;; 4. 2 plaques de 75
;; 5. 2 plaques de 100
;;
;; On tire également au hasard un nombre N entre 100 et 999. Le but du
;; jeu est de trouver une valeur aussi proche que possible de N, en
;; utilisant les nombres inscrits sur les plaques, en respectant les
;; règles suivantes :
;;
;; 1. Chaque plaque doit être utilisée au plus une fois (mais il n'est
;; pas nécessaire d'utiliser toutes les plaques)
;;
;; 2. Les seules opérations autorisées sont les quatre opérations
;; arithmétiques, +, -, $\times$ et /, restreintes aux entiers naturels
;; positifs : ainsi, les divisions ne sont autorisées que si leur reste
;; est nul et les nombres négatifs sont proscrits du calcul. Dans le cas
;; où N ne peut être obtenu, on cherche à obtenir une valeur N-k ou N+k
;; avec k minimal. Lorsque plusieurs calculs sont possibles, on préfèrera
;; ceux qui utilisent le moins de plaques possibles.
;;
;;
;;
;; Exemple 1. Si le nombre à trouver est 140 et si le tirage est 3 6 6 7 50
;; 50, on peut obtenir le bon compte en 5 plaques de la façon suivante :
;;
;; Exemple 2. Si le nombre à trouver est 532 et si le tirage est 1 25 75 75
;; 100 100, on peut obtenir le bon compte en 5 plaques de la façon suivante :
;;
;; Exemple 3. Si le nombre à trouver est 660 et si le tirage est 2 2 7 50
;; 75 100, on ne peut pas obtenir 660, mais on peut obtenir 661 de la façon suivante :
;;
;; Détail du sujet
;;
;; On suivra à la lettre les instructions données ci-dessous. On pourra,
;; si on le souhaite, tester d'autres heuristiques, mais uniquement une
;; fois que l'algorithme décrit ci-dessous aura été correctement
;; implanté.
;;
;; La première partie consistera à réaliser le tirage aléatoire des six
;; plaques P[1], ..., P[6] (sans remplacement) et du nombre N. Aucun
;; algorithme spécifique n'est donné pour cette partie du travail, mais
;; on veillera à ce que les tirages soient équiprobables.
;;
;; La deuxième partie consistera à rechercher la solution optimale. Pour
;; cela, on partira du résultat à trouver, N (ou en cas d'échec, N-1,
;; N+1, N-2, N+2, etc.), et on cherchera à obtenir en utilisant les six
;; plaques. Par exemple, dans l'exemple précédent, on aurait, en
;; remontant les calculs à partir de 661 , 661-50 = 611, 611-100 = 511,
;; 511/7 =73, 73+2 = 75, 75-75 = 0. Pour celà, on construira un tableau T
;; indexé par les 26 sous-ensembles de $\{1, \dots, 6\}$. Si $I = \{i_1,
;; \ldots, i_k\}$ est une partie de $\{1, \dots, 6\}$, T[I] contiendra
;; l'ensemble des nombres que l'on peut obtenir à partir de N en
;; utilisant les plaques P[i1], ..., P[ik]. Sur notre exemple, on devrait
;; trouver $P[\emptyset] = \{661\}$,$P[\{1\}] = P[\{2\}] = \{661, 661-2,
;; 661+2, 661\times 2\}$, etc. Pour le calcul du tableau, on écrira une
;; procédure qui prend pour paramètres deux ensembles d'entiers E et F,
;; et qui retourne l'ensemble $\langle E, F\rangle$ des entiers obtenus
;; en une seule opération arithmétique portant sur un élément de E et un
;; élément de F. Le calcul du tableau se fait ensuite en s'appuyant sur
;; la formule
;;
;; \begin{displaymath}
;; T[I] = \bigcup_{(I_1, I_2)\hbox{ partition de $I$}}\langle T[I_1],
;; T[I_2]\rangle\end{displaymath}
;;
;; Il faut donc coder les sous-ensembles de $\{1, \dots, 6\}$. La
;; solution la plus simple consiste à coder une partie I par la position
;; des 1 dans la représentation binaire d'un entier compris entre et
;; 63. Ainsi l'entier 43, dont la représentation binaire est 101011, code
;; le sous-ensemble $\{1,3,5,6\}$. Autrement dit, la partie I est codée
;; par l'entier $\sum_{i\in I}2^{6-i}$. La seconde difficulté est de
;; choisir une bonne représentation pour les ensembles d'entiers. On
;; choisira la (ou les) représentation(s) qui permettent le calcul le
;; plus rapide. Le rapport devra être très explicite sur le choix de
;; cette représentation (tableaux, listes, listes ordonnées, listes
;; doublement chaînées, arbres binaires, arbres équilibrés, etc.) et sur
;; les arguments qui ont justifié ce choix.
;;
;; Enfin, on pourra réfléchir sur la nécessité de calculer tous les
;; nombres accessibles à partir de N. Pour prendre un exemple, est-il
;; vraiment utile de savoir que $661 \times 50 \times 75 \times 100$ est
;; dans $T[\{4, 5, 6\}]$ ? La question est plus délicate qu'il n'y paraît
;; ...
;;
;; Interface
;;
;; On fera une interface propre, mais sans fioritures, car ce n'est pas
;; l'objectif du projet. Elle devra proposer à l'utilisateur le choix
;; entre un tirage aléatoire ou manuel (essentiel pour la mise au point
;; !) puis afficher le résultat du calcul dans une mise en page
;; correcte. On évitera donc simplement les sorties du type
;;
;; 7 x 3 = 21
;; 7 x 3=21
;; 7 x 3 = 21
;; Voici un modèle simple, mais parfaitement suffisant, de ce qui est attendu.
;; Tirage manuel ou aleatoire ? (m ou a) a
;;
;; Nombre a trouver : 140 Voici le tirage : 7 6 6 50 50 3
;; Le compte est bon ! (en 5 plaques)
;; 7 x 3 = 21
;; 21 - 6 = 15
;; 15 x 6 = 90
;; 90 + 50 = 140
;; Voulez-vous continuer ? (o ou n) o
;;
;; Tirage manuel ou aleatoire ? (m ou a) m
;; Donnez votre tirage :
;;
;; Premiere plaque : 2
;;
;; Deuxieme plaque : 2
;;
;; Troisieme plaque : 7
;;
;; Quatrieme plaque : 50
;;
;; Cinquieme plaque : 75
;;
;; Sixieme plaque : 100
;;
;; Donnez le nombre a trouver : 660
;;
;; Nombre a trouver : 660 Voici le tirage : 2 2 7 50 75 100
;; J'ai trouve 661
;; 75 - 2 = 73
;; 73 x 7 = 511
;; 511 + 50 = 561
;; 561 + 100 = 661
;; Voulez-vous continuer ? (o ou n)
;;
;;
;; 1/6/1998
(defparameter *numbers*
#(1 2 3 4 5 6 7 8 9 10 25 50 75 100
1 2 3 4 5 6 7 8 9 10 25 50 75 100))
(defun select-numbers ()
(loop
:with remaining := (copy-seq *numbers*)
:repeat 6
:for l := (length remaining) :then (1- l)
:for r := (random l)
:collect (loop :for n := (prog1
(aref remaining r)
(setf (aref remaining r) nil))
:then (prog2 (setf r (mod (1+ r) (length remaining)))
(aref remaining r)
(setf (aref remaining r) nil))
:until n
:finally (return n))
:into numbers
:finally (return (values numbers remaining))))
(defun random-number ()
(+ 100 (random (- 999 100))))
(defun le-compte-est-bon-problem ()
(list (select-numbers)
(random-number)))
(defun problem-numbers (problem) (first problem))
(defun problem-target (problem) (second problem))
(defun sexp-replace-nth (new old sexp n)
(loop
:for current :on sexp
:if (eql old (car current))
:do (if (zerop n)
(progn
(setf (car current) new)
(return-from sexp-replace-nth (values sexp -1)))
(progn
(decf n)))
:else :if (consp (car current))
:do (when (minusp (setf n (nth-value 1 (sexp-replace-nth new old (car current) n))))
(return-from sexp-replace-nth (values sexp -1))))
(values sexp n))
(defun enumerate-trees (new old trees)
(let ((leaves (count old (flatten (first trees)))))
(remove-duplicates
(loop
:for tree :in trees
:append (loop :for i :below leaves
:collect (sexp-replace-nth (copy-tree new) old (copy-tree tree) i)))
:test (function equalp))))
;; (let ((*print-right-margin* 40))
;; (pprint (enumerate-trees '(op n n) 'n '((op (op (op (op n n) n) n) n)
;; (op (op (op n (op n n)) n) n)
;; (op (op (op n n) (op n n)) n)
;; (op (op n (op (op n n) n)) n)
;; (op (op n (op n (op n n))) n)
;; (op (op (op n n) n) (op n n))
;; (op (op n (op n n)) (op n n))
;; (op (op n n) (op (op n n) n))
;; (op n (op (op (op n n) n) n))
;; (op n (op (op n (op n n)) n))
;; (op (op n n) (op n (op n n)))
;; (op n (op (op n n) (op n n)))
;; (op n (op n (op (op n n) n)))
;; (op n (op n (op n (op n n)))))
;; )))
(defparameter *trees* '(((op n n))
((op (op n n) n)
(op n (op n n)))
((op (op (op n n) n) n)
(op (op n (op n n)) n)
(op (op n n) (op n n))
(op n (op (op n n) n))
(op n (op n (op n n))))
((op (op (op (op n n) n) n) n)
(op (op (op n (op n n)) n) n)
(op (op (op n n) (op n n)) n)
(op (op n (op (op n n) n)) n)
(op (op n (op n (op n n))) n)
(op (op (op n n) n) (op n n))
(op (op n (op n n)) (op n n))
(op (op n n) (op (op n n) n))
(op n (op (op (op n n) n) n))
(op n (op (op n (op n n)) n))
(op (op n n) (op n (op n n)))
(op n (op (op n n) (op n n)))
(op n (op n (op (op n n) n)))
(op n (op n (op n (op n n)))))
((op (op (op (op (op n n) n) n) n) n)
(op (op (op (op n (op n n)) n) n) n)
(op (op (op (op n n) (op n n)) n) n)
(op (op (op n (op (op n n) n)) n) n)
(op (op (op n (op n (op n n))) n) n)
(op (op (op (op n n) n) (op n n)) n)
(op (op (op n (op n n)) (op n n)) n)
(op (op (op n n) (op (op n n) n)) n)
(op (op n (op (op (op n n) n) n)) n)
(op (op n (op (op n (op n n)) n)) n)
(op (op (op n n) (op n (op n n))) n)
(op (op n (op (op n n) (op n n))) n)
(op (op n (op n (op (op n n) n))) n)
(op (op n (op n (op n (op n n)))) n)
(op (op (op (op n n) n) n) (op n n))
(op (op (op n (op n n)) n) (op n n))
(op (op (op n n) (op n n)) (op n n))
(op (op n (op (op n n) n)) (op n n))
(op (op n (op n (op n n))) (op n n))
(op (op (op n n) n) (op (op n n) n))
(op (op n (op n n)) (op (op n n) n))
(op (op n n) (op (op (op n n) n) n))
(op n (op (op (op (op n n) n) n) n))
(op n (op (op (op n (op n n)) n) n))
(op (op n n) (op (op n (op n n)) n))
(op n (op (op (op n n) (op n n)) n))
(op n (op (op n (op (op n n) n)) n))
(op n (op (op n (op n (op n n))) n))
(op (op (op n n) n) (op n (op n n)))
(op (op n (op n n)) (op n (op n n)))
(op (op n n) (op (op n n) (op n n)))
(op n (op (op (op n n) n) (op n n)))
(op n (op (op n (op n n)) (op n n)))
(op (op n n) (op n (op (op n n) n)))
(op n (op (op n n) (op (op n n) n)))
(op n (op n (op (op (op n n) n) n)))
(op n (op n (op (op n (op n n)) n)))
(op (op n n) (op n (op n (op n n))))
(op n (op (op n n) (op n (op n n))))
(op n (op n (op (op n n) (op n n))))
(op n (op n (op n (op (op n n) n))))
(op n (op n (op n (op n (op n n))))))))
(defun number-free-variables (tree result next-op next-value)
(if (atom tree)
(ecase tree
((nil) (values result next-op next-value))
((op) (number-free-variables nil (intern (format nil "OP~A" (incf next-op))) next-op next-value))
((n) (number-free-variables nil (intern (format nil "N~A" (incf next-value))) next-op next-value)))
(multiple-value-bind (left next-op next-value) (number-free-variables (car tree) nil next-op next-value)
(multiple-value-bind (right next-op next-value) (number-free-variables (cdr tree) nil next-op next-value)
(values (cons left right) next-op next-value)))))
(defparameter *numbered-trees*
(mapcan (lambda (trees)
(mapcar (lambda (tree) (number-free-variables tree nil 0 0))
trees))
*trees*))
(defun substitute-expression (op1 op2 op3 op4 op5
n1 n2 n3 n4 n5 n6
expression)
(loop :for (new old) :in (list (list op1 'op1)
(list op2 'op2)
(list op3 'op3)
(list op4 'op4)
(list op5 'op5)
(list n1 'n1)
(list n2 'n2)
(list n3 'n3)
(list n4 'n4)
(list n5 'n5)
(list n6 'n6))
:for e := (subst new old expression)
:then (subst new old e)
:finally (return e)))
(defun op-or-dbz (op a b)
(if (eq op '/)
`(if (zerop ,b)
(return-from :bad-division)
(let ((quotient (,op ,a ,b)))
(if (integerp quotient)
quotient
(return-from :bad-division))))
`(,op ,a ,b)))
(defun infix (expression)
(if (atom expression)
expression
(destructuring-bind (op a b) expression
`(,(infix a) ,op ,(infix b)))))
(defun le-compte-est-bon (problem &key verbose)
(let ((target (problem-target problem))
(*closest* nil))
(declare (special *closest*))
(when verbose
(format t "Nombres: ~{~A~^, ~}~%" (problem-numbers problem))
(format t "Cible: ~A~%" (problem-target problem)))
(dolist (expression *numbered-trees*)
(dolist (numbers (com.informatimago.clext.association::permutations
(problem-numbers problem)))
(dolist (op1 '(+ - * /))
(dolist (op2 '(+ - * /))
(dolist (op3 '(+ - * /))
(dolist (op4 '(+ - * /))
(dolist (op5 '(+ - * /))
(let ((try `(block
:bad-division
(labels ((op1 (a b) ,(op-or-dbz op1 'a 'b))
(op2 (a b) ,(op-or-dbz op2 'a 'b))
(op3 (a b) ,(op-or-dbz op3 'a 'b))
(op4 (a b) ,(op-or-dbz op4 'a 'b))
(op5 (a b) ,(op-or-dbz op5 'a 'b))
(expression (n1 n2 n3 n4 n5 n6)
(declare (ignorable n1 n2 n3 n4 n5 n6))
,expression))
(let ((target ,target)
(result (expression ,@numbers)))
(declare (special *closest*))
(when (or (null *closest*)
(= target result)
(< (abs (- target result))
(abs (- target (first *closest*)))))
(setf *closest* (list result (substitute-expression
',op1 ',op2 ',op3 ',op4 ',op5
,@numbers ',expression)))
,(when verbose
`(format t "J'ai ~A = ~S~%" (first *closest*) (infix (second *closest*))))))))))
(eval try)
(when (= (first *closest*) target)
;; early exit.
(return-from le-compte-est-bon *closest*))))))))))
*closest*))
;; This brute force algorithm is to slow, the solution must be found in less than 40 seconds.
| 17,781 | Common Lisp | .lisp | 370 | 36.456757 | 121 | 0.481627 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 628235a4229d26a8e4048623ba995e29516e40a0e88ad98105b1dc9759da7e95 | 4,834 | [
-1
] |
4,835 | moon.lisp | informatimago_lisp/small-cl-pgms/moon.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: pom.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This package computes and ascii-draw the phase of the Moon.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-11-10 <PJB> Created (converted from newmoon.c)
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2013 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.MOON"
(:use "COMMON-LISP")
(:export "PHASE-OF-THE-MOON" "DRAW-PHASE"
"DRAW-PHASE-OF-THE-MOON")
(:documentation "
This package computes and ascii-draw the phase of the Moon.
Copyright Pascal J. Bourguignon 2013 - 2013
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.MOON")
(defun phase-of-the-moon (time)
"
DO: Compute the phase of the moon.
RETURN: fraction; day; hour; minute; name.
"
;; This is most certainly wrong. Converted from a function written
;; in C that had been massaged to work first in seconds, then in
;; minutes using assumedly originally a base time 13:23 10/1/78,
;; then 15:19 GMT 2/5/85 but using actually the values coded here.
(let* ((base (encode-universal-time 0 59 11 21 3 1985 0))
(difference (truncate (- time base) 60))
(phase-length (+ 44 (* 60 (+ 12 (* 24 29)))))
(phase (mod difference phase-length))
(fraction (/ phase phase-length))
(phase-length (truncate phase-length 4))
(phase (truncate phase phase-length))
(difference (truncate difference phase-length)))
(multiple-value-bind (hour-diff minute) (truncate difference 60)
(multiple-value-bind (day hour) (truncate hour-diff 24)
(values fraction day hour minute (aref #("New Moon "
"First Quarter "
"Full Moon "
"Last Quarter ")
phase))))))
#-(and) #("New Moon"
"Waxing Crescent"
"First Quarter"
"Waxing Gibbous"
"Full Moon"
"Waning Gibbous"
"Last Quarter"
"Waning Crescent")
(defvar *default-screen-aspect* 0.5)
(defvar *default-screen-height* 25)
(defvar *default-screen-width* 80)
(defvar *default-fill-pattern* "*")
(defun draw-phase (phase name &key
(height *default-screen-height*)
(width *default-screen-width*)
(screen-aspect *default-screen-aspect*))
"
Draws in ASCII art (over HEIGHT lines of WIDTH characters), a circle
with the phase highlighed with characters from the NAME string.
SCREEN-ASPECT: the ratio of the height of a character over the width of a
character.
"
(let* ((full-moon 0.5) ; the new moon is 0.0
(fuzz 0.03) ; how far off we must be from an even 0.0
(1-fuzz (- 1.0 fuzz))
(xmin 0) ; x position of leftmost edge of moon (not line)
(xoffset (truncate width 2))
(vdiameter (min (* width screen-aspect) height))
(cheight (/ 2 vdiameter)) ; character height in a circle of radius 1.0
(xscale (/ (* cheight screen-aspect))) ; x stretch factor
(beforep (< phase full-moon))
(squisher (if beforep
(cos (* 2 pi phase))
(cos (* 2 pi (- phase full-moon))))))
(flet ((charpos (x xscale xoffset) (max 1 (+ xoffset (round (* x xscale)))))
(pixel (i) (aref name (mod (- i xmin) (length name))))
(draw (buffer i p) (when (< -1 i (length buffer))
(setf (aref buffer i) p))))
(loop
:for y = (- 1.0 (/ cheight 2.0)) :then (- y cheight)
:while (and (< -1.0 y) (< (abs (- y cheight)) y))
:finally (let ((horizon (sqrt (- 1.0 (* y y)))))
(setf xmin (charpos (- horizon) xscale xoffset))))
(loop
:for y = (- 1.0 (/ cheight 2))
:then (- y cheight)
:while (< -1.0 y)
:do (let* ((buffer (make-string width :initial-element #\space))
(horizon (sqrt (- 1.0 (* y y))))
(terminator (* squisher horizon))
(left (if beforep terminator (- horizon)))
(right (if beforep horizon terminator)))
(let ((i (charpos horizon xscale xoffset))) (draw buffer i (pixel i)))
(let ((i (charpos (- horizon) xscale xoffset))) (draw buffer i (pixel i)))
(when (< fuzz phase 1-fuzz)
(loop
:for i :from (charpos left xscale xoffset) :to (charpos right xscale xoffset)
:do (draw buffer i (pixel i))))
(write-line buffer))))))
(defun draw-phase-of-the-moon (&key
(name *default-fill-pattern*)
(height *default-screen-height*)
(width *default-screen-width*)
(screen-aspect *default-screen-aspect*))
(multiple-value-bind (fraction day hour minute phase-name) (phase-of-the-moon (get-universal-time))
(draw-phase fraction
(cond
((vectorp name) name)
((eq name :time) (format nil "~2D ~2,'0D:~2,'0D" day hour minute))
(t phase-name))
:height height :width width :screen-aspect screen-aspect)))
(defun pdraw/test ()
(multiple-value-bind (fraction day hour minute name) (phase-of-the-moon (get-universal-time))
(format t "~2D ~2,'0D:~2,'0D~%" day hour minute)
(draw-phase fraction name)
(draw-phase fraction "*"))
(loop
:for fraction :from 0.0 to 1.0 by (/ 1.0 29)
:do (draw-phase fraction "#") (terpri) (terpri)))
;;;; THE END ;;;;
| 7,741 | Common Lisp | .lisp | 158 | 40.126582 | 101 | 0.566592 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 943e9e93c3e080b8a5c31def6b3d6faeaac7483f9caab5b41573851fee593a94 | 4,835 | [
-1
] |
4,836 | what-implementation.lisp | informatimago_lisp/small-cl-pgms/what-implementation.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: what-implementation.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Helps a newbie choose a CL implementations by selecting criteria.
;;;;
;;;; Please contribute to the selection criteria and other
;;;; implementation attributes.
;;;;
;;;; See also: http://common-lisp.net/~dlw/LispSurvey.html
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-04-30 <PJB> Added advertizements.
;;;; 2012-04-15 <PJB> Created
;;;;BUGS
;;;;
;;;; <quotemstr> pjb: It's unclear whether "choice of
;;;; platforms" is a conjunctive or disjunctive choice
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.WHAT-IMPLEMENTATION"
(:use "COMMON-LISP")
(:export "CHOOSE-AN-IMPLEMENTATION" "SELECTION-LOOP"
"GENERATE-SERVER-EXECUTABLE")
(:documentation "
Helps a newbie choose a CL implementations by selecting criteria.
Please contribute to the selection criteria and other implementation
attributes.
Evaluate:
(com.informatimago.what-implementation:choose-an-implementation)
(com.informatimago.what-implementation:selection-loop)
and answer the questions.
(com.informatimago.what-implementation:generate-server-executable \"what-cl\")
Copyright Pascal J. Bourguignon 2012 - 2012
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.WHAT-IMPLEMENTATION")
(defparameter *version* "1.0.1")
(defparameter *not-selection-fields*
'(:name :nickname :homepage :documentation)
"List of fields not used as selection criteria.")
(defparameter *implementations*
'((:name "GNU CLISP"
:nickname "CLISP"
:license "GPL"
:homepage "http://www.clisp.org/"
:documentation "http://www.clisp.org/impnotes/"
:platforms ("Linux"
"Mac OS X"
"MS-Windows"
"Solaris"
"FreeBSD" "NetBSD" "OpenBSD" "Dragonfly BSD")
:compiler ("clisp virtual machine")
:threads ("native")
:features ("small image"
"efficient bignum"
"callbacks"
"modules"
"best debugger on interpreted code"
"readline")
:mostly-written-in ("C"))
(:name "Carnegie Mellon University Common Lisp"
:nickname "CMUCL"
:license "public domain + BSD"
:homepage "http://www.cons.org/cmucl/"
:documentation "http://common-lisp.net/project/cmucl/doc/cmu-user/"
:platforms ("Linux"
"Mac OS X"
"Solaris"
"FreeBSD" "NetBSD" "OpenBSD"
"IRIS" "HPUX")
:compiler ("cmucl virtual machine" "native")
:threads ("no")
:features ("high quality native compiler"
"callbacks")
:mostly-written-in ("Common Lisp"))
(:name "Embeddable Common-Lisp"
:nickname "ECL"
:license "LGPL"
:homepage "http://ecls.sourceforge.net/"
:documentation "http://ecls.sourceforge.net/new-manual/index.html"
:platforms ("Linux"
"Mac OS X" "iOS" "Android"
"Solaris"
"FreeBSD" "OpenBSD"
"IRIS" "HPUX")
:compiler ("ecl virtual machine" "native thru gcc")
:threads ("native")
:features ("embeddable"
"integrates well with C programs"
"deployable as a shared library"
"native powerful FFI"
"executable delivery"
"callbacks")
:mostly-written-in ("C"))
(:name "GNU Common Lisp"
:nickname "gcl"
:license "LGPL"
:homepage "http://www.gnu.org/software/gcl/"
:documentation "http://www.gnu.org/software/gcl/"
:platforms ("Linux"
"Mac OS X"
"Solaris"
"FreeBSD" "OpenBSD"
"IRIS" "HPUX" "cygwin")
:processors ("x86" "arm64" "ppc64" "ppc64le" "solaris")
:compiler ("native thru gcc")
:threads ("native")
:features ("integrates well with C programs"
"executable delivery")
:mostly-written-in ("Common Lisp"))
(:name "Clozure Common Lisp"
:nickname "CCL"
:license "LLGPL"
:homepage "http://ccl.clozure.com/"
:documentation "http://ccl.clozure.com/ccl-documentation.html"
:platforms ("Linux"
"Mac OS X" "iOS"
"MS-Windows"
"Heroku"
"Solaris" "Android"
"FreeBSD" "OpenBSD"
"IRIS" "HPUX")
:compiler ("native")
:threads ("native")
:features ("small image" "fast compiler"
"convenient and powerful FFI"
"executable delivery"
"callbacks"
"precise GC")
:mostly-written-in ("Common Lisp"))
(:name "Steel Bank Common Lisp"
:nickname "SBCL"
:license "public domain + BSD"
:homepage "http://www.sbcl.org/"
:documentation "http://www.sbcl.org/manual/index.html"
:platforms ("Linux"
"Mac OS X"
"MS-Windows"
"FreeBSD" "OpenBSD")
:compiler ("native")
:threads ("native")
:features ("high quality native compiler"
"executable delivery"
"callbacks")
:mostly-written-in ("Common Lisp"))
(:name "CLforJava"
:nickname "CLforJava"
:license "Apache 2.0"
:homepage "http://www.clforjava.org/"
:documentation "http://www.clforjava.org/?page=documents"
:platforms ("JVM")
:compiler ("JVM virtual machine")
:threads ()
:features ("FFI to Java"
"platform independence")
:mostly-written-in ("Java"))
(:name "Armed Bear Common Lisp"
:nickname "ABCL"
:license "GPL"
:homepage "http://common-lisp.net/project/armedbear/"
:documentation "http://common-lisp.net/project/armedbear/doc/abcl-user.html"
:platforms ("JVM" "Google App Engine")
:compiler ("JVM virtual machine")
:threads ("native")
:features ("FFI to Java"
"platform independence")
:mostly-written-in ("Java"))
(:name "Un-Armed Bear Common Lisp for Java - LispSharp"
:nickname "UABCL"
:license "GPL3"
:homepage "http://code.google.com/p/uabcl/"
:documentation "http://code.google.com/p/uabcl/"
:platforms (".NET")
:compiler ()
:threads ("native")
:features ("platform independence")
:mostly-written-in ("Java"))
(:name "ManKai Common Lisp"
:nickname "MKCL"
:license "LGPL"
:homepage "http://common-lisp.net/project/mkcl/"
:documentation "http://common-lisp.net/project/mkcl/"
:platforms ("Linux" "MS-Windows")
:compiler ("native" "mkcl virtual machine")
:threads ("native")
:features ("POSIX compliant runtime on Linux"
"embeddable" "callbacks" "unicode"
"object finalization")
#- (and) "
From: Jean-Claude Beaudoin <[email protected]>
Subject: [ANN] MKCL 1.1.0 RC1
Newsgroups: comp.lang.lisp
Date: Mon, 30 Apr 2012 06:10:23 -0400
Organization: A noiseless patient Spider
Message-ID: <[email protected]>
The latest beta version of ManKai Common Lisp, MKCL 1.1.0 RC1,
is now available for general use at <http://common-lisp.net/project/mkcl/>.
Its key new features are:
1. Standard Unicode support: Unicode is now a standard feature of MKCL
and can be used anywhere in it. Code can use symbols with Unicode
names as well as strings, in compiled or interpreted format.
File names can also use any legal Unicode character if the surrounding
OS allows it. This is also valid for the whole of file paths used for
source code to be processed by #'compile-file.
2. MKCL is now truly embeddable for the first time! This is so thanks
to the following new characteristics:
a) The whole of MKCL has been purged of calls to exit() or abort().
Thus MKCL never arbitrarily terminates the process it runs in
through any of them. MKCL will always properly return control
to its embedding outer context.
b) Every externally visible C symbol of MKCL is prefixed by one of
the character sequences \"mk\", \"_mk\", \"MK\" or \"_MK\" in order to
minimize potential clashes with embedding C code.
c) Careful attention as been devoted to assure that MKCL shares
common process-wide resources with the rest of its process
neighbors as fairly as possible and with little or no unilateral
demands on them, waiving any pretense of monopoly.
This concerns mainly environment variables, general memory
management (including GC) and signal/exception handling.
(In a Unix context, MKCL's code is ready to support chaining
of signal handlers).
3. Finalization of objects is now done in a separate dedicated thread.
This implements the finalization architecture strongly recommended
by Hans Boehm, author of the conservative GC used by MKCL.
Cheers,
Jean-Claude Beaudoin
"
:mostly-written-in ("C"))
(:name "The Common Lisp to C Compiler"
:nickname "CLiCC"
:license "GPL"
:homepage "http://www.informatik.uni-kiel.de/~wg/clicc.html"
:documentation "http://www.informatik.uni-kiel.de/~wg/clicc.html#information"
:platforms ("Common Lisp + C")
:compiler ("translator to C")
:threads ("no")
:features ("Translator of a subset of CL to maintainable, human-readable C")
:mostly-written-in ("Common Lisp"))
(:name "Emacs Common Lisp"
:nickname "emacs-cl"
:license "GPL2"
:homepage "http://www.lisp.se/emacs-cl/"
:documentation "http://www.emacswiki.org/cgi-bin/wiki?EmacsCommonLisp"
:platforms ("GNU emacs")
:compiler ("emacs virtual machine")
:threads ("no")
:features ("emacs integration")
:mostly-written-in ("emacs lisp"))
(:name "Macintosh Common Lisp"
:nickname "MCL"
:license "LGPL"
:homepage "http://code.google.com/p/mcl/"
:documentation "http://code.google.com/p/mcl/w/list"
:platforms ("Mac OS" "Mac OS X Rosetta")
:compiler ("native")
:threads ("native")
:features ()
:mostly-written-in ("Common Lisp"))
(:name "Movitz"
:nickname "Movitz"
:license "LGPL"
:homepage "http://common-lisp.net/project/movitz/"
:documentation "http://common-lisp.net/project/movitz/movitz.html"
:platforms ("ix86")
:compiler ("native")
:threads ("no")
:features ("targets bare ix86 hardware"
"embedded systems"
"OS writing")
:mostly-written-in ("Common Lisp"))
(:name "Poplog"
:nickname "Poplog"
:license "MIT/XFREE86"
:homepage "http://www.cs.bham.ac.uk/research/projects/poplog/freepoplog.html"
:documentation "http://en.wikipedia.org/wiki/Poplog"
:platforms ("PDP-11" "VAX/VMS" "Solaris" "HP-UX" "Digital Unix" "MS-Windows"
"Linux")
:compiler ("Poplog virtual machine")
:threads ()
:features ("incremental compiler"
"integration with Pop-11, prolog and ML")
:mostly-written-in ("Pop-11"))
(:name "Sacla"
:nickname "Sacla"
:license "BSD"
:homepage "http://homepage1.nifty.com/bmonkey/lisp/sacla/index-en.html"
:documentation "http://homepage1.nifty.com/bmonkey/lisp/sacla/index-en.html"
:platforms ("Common Lisp")
:compiler ()
:threads ("no")
:features ("Partical CL implemented in CL")
:mostly-written-in ("Common Lisp"))
(:name "XCL"
:nickname "XCL"
:license "GPL"
:homepage "http://armedbear.org/"
:documentation "http://armedbear.org/"
:platforms ("Linux x86" "Linux x86-64")
:compiler ("native")
:threads ("native")
:features ("native threads"
"embeddable"
"compact code"
"small C++ kernel for bootstrapping"
"experimental"
"slow startup"
"minimalist")
:mostly-written-in ("C++"))
;; xcl is experimental. Lacking a lot of features. Rather slow, at least at startup.
(:name "Embeddable Common Lisp for Linux"
:nickname "WCL"
:license "Proprietary"
:homepage "http://www.commonlisp.net/"
:documentation "http://www.commonlisp.net/"
:platforms ("Linux")
:compiler ("native thru gcc")
:threads ("native")
:features ("native thru"
"integrates well with C programs"
"deployable as a shared library"
"embeddable")
:mostly-written-in ("C"))
(:name "ThinLisp"
:nickname "ThinLisp"
:license "Apache 1.0"
:homepage "http://www.thinlisp.org/"
:documentation "http://www.thinlisp.org/"
:platforms ("Common Lisp")
:compiler ("native thru gcc")
:threads ()
:features ("subset of Common Lisp"
"deploys small applications")
:mostly-written-in ("Common Lisp"))
(:name "Ufasoft Common Lisp"
:nickname "UCL"
:license "GPL"
:homepage "http://www.ufasoft.com/lisp/"
:documentation "http://www.ufasoft.com/lisp/"
:platforms ("MS-Windows" "MS-WIndows Mobile")
:compiler ("clisp virtual machine")
:threads ()
:features ("fork of clisp"
"core re-implemented in C++"
"includes an IDE")
:mostly-written-in ("C++"))
(:name "Allegro Common Lisp"
:nickname "AllegroCL"
:license "Proprietary"
:homepage "http://www.franz.com/products/allegrocl/"
:documentation "http://www.franz.com/support/documentation/"
:platforms ("Mac OS X" "MS-Windows" "FreeBSD" "IBM AIX" "Linux"
"Solaris")
:compiler ("native")
:threads ("native")
:features ("IDE"
"Source level debugger"))
(:name "Lispworks Common Lisp"
:nickname "Lispworks"
:license "Proprietary"
:homepage "http://www.lispworks.com/products/index.html"
:documentation "http://www.lispworks.com/documentation/index.html"
:platforms ("Mac OS X" "MS-Windows" "FreeBSD" "Linux" "Solaris")
:compiler ("native")
:threads ("native")
:features ("IDE"
"CAPI (GUI)"
"universal binaries"
"support for input methods"
"application builder tool"
"ASDF2 integrated"
"FFI" "MOP"
"Unicode"
"SMP"
"profiling multiple-threads"
"TCP socket streams with IPv6 support"
"object finalization"
"weak pointers and hash tables"
"dynamic library delivery"
"source code editor"
"KnowledgeWorks & prolog"
"CLIM"
"Common SQL (ODBC interface)"
"Common SQL (Mysql interface)"
"Common SQL (Postgres interface)"
"Objective-C/Cocoa FLI"
"Customizable toolbars"
"ActiveX components"
"OpenSSL interface"
"Lispworks ORB"
"Serial port interface"
"COM server and client interface"
"Direct Data Exchange"))
(:name "Corman Common Lisp"
:nickname "CormanCL"
:license "Proprietary"
:homepage "http://www.cormanlisp.com/index.html"
:documentation "http://www.cormanlisp.com/index.html"
:platforms ("MS-Windows")
:compiler ("native")
:threads ("native")
:features ("fast multi-generational garbage collector"
"no interpreter"
"fast compilation"
"FFI"
"multi-threading"
"DLL and EXE generation"
"callbacks"
"optimizing compiler"
"integrated intel assembler"
"source code"
"IDE"
"scm"))
(:name "PowerLisp"
:nickname "PowerLisp"
:license "Proprietary"
:homepage "http://www.cormanlisp.com/PowerLisp.html"
:documentation "http://www.cormanlisp.com/PowerLisp.html"
:platforms ("Mac OS")
:compiler ("native")
:threads ()
:features ())
))
(defun report-implementation (impl &optional (stream *query-io*))
(let ((*print-pretty* t)
(*print-right-margin* 80))
(format stream "~%Common Lisp Implementation: ~A~%" (getf impl :name))
(format stream " Home page: ~A~%" (getf impl :homepage))
(format stream " Documentation: ~A~%" (getf impl :documentation))
(format stream " License: ~A~%" (getf impl :license))
(format stream " Runs on: ~{~<~%~12<~>~2:;~A~>~^, ~}.~%" (getf impl :platforms))
(format stream " Compiler: ~{~<~%~12<~>~2:;~A~>~^, ~}.~%" (getf impl :compiler))
(format stream " Threads: ~{~A~^, ~}.~%" (getf impl :threads))
(format stream " Features: ~{~<~%~12<~>~2:;~A~>~^, ~}.~%" (getf impl :features))
impl))
(defun ensure-list (object)
(if (listp object) object (list object)))
(defun collect-field (field &optional (implementations *implementations*))
"Returns the list of values in the FIELD of all the entries in IMPLEMENTATIONS."
(sort
(delete-duplicates
(mapcan (lambda (entry) (copy-list (ensure-list (getf entry field))))
implementations)
:test (function string=))
(function string<)))
(defun select-field (field accepted-values &optional (implementations *implementations*))
"Returns the sublist of implementations that have as values in their
FIELD one of the ACCEPTED-VALUES."
(remove-if-not (lambda (entry)
(intersection (ensure-list accepted-values)
(ensure-list (getf entry field))
:test (function string-equal)))
implementations))
(defun selection-fields (&optional (implementations *implementations*))
"Returns the list of fields that are present and can be used for a selection."
(sort
(set-difference
(delete-duplicates
(loop
:for key :in (mapcan (function copy-seq) implementations)
:by (function cddr) :collect key))
*not-selection-fields*)
(function string<)))
(defun process-answer-line (line choices)
(labels ((clean (line)
(string-trim " "
(substitute-if #\space
(lambda (ch) (find ch " ,.;()[]!:-=<>"))
line)))
(try-choice (clean-line)
(let ((pos (position-if (lambda (item)
(string-equal clean-line (clean item)))
choices)))
(when pos
(1+ pos)))))
(let ((clean-line (clean line)))
(if (every (lambda (ch) (or (char= #\space ch) (digit-char-p ch))) clean-line)
(let ((answer (with-input-from-string (inp clean-line)
(loop
:for index = (read inp nil nil)
:while index :collect index))))
(case (length answer)
((0) (try-choice clean-line))
((1) (first answer))
(otherwise answer)))
(try-choice clean-line)))))
(defun select (field &optional (implementations *implementations*))
"
DO: Let the user choose the IMPLEMENTATIONS he wants to select based on the FIELD.
RETURN: A sublist of IMPLEMENTATIONS.
"
(let ((choices (collect-field field implementations)))
(cond
((< 1 (length choices))
(select-field
field
(loop
:for i :from 0
:for c :in (cons "indifferent" choices)
:initially (format *query-io* "Choice of ~(~A~):~%" field)
:do (format *query-io* "~3D. ~A~%" i c)
:finally (progn
(format *query-io* "Enter a menu index or a list of menu indices: ")
(finish-output *query-io*)
(return
(let ((answer (process-answer-line (read-line *query-io*) choices)))
(if (eql 0 answer)
choices
(delete nil
(mapcar (lambda (i) (when (plusp i) (elt choices (1- i))))
(delete-duplicates
(delete-if-not (function integerp)
(ensure-list answer))))))))))
implementations))
((= 1 (length choices))
(format *query-io*
"For the ~(~A~) there is no choice, it will be ~A.~%"
field (first choices))
(force-output *query-io*)
(select-field field choices implementations))
(t
(format *query-io* "For the ~(~A~) there is no choice.~%" field)
(force-output *query-io*)
implementations))))
(defun report-selection (selection)
(if (endp selection)
(format *query-io* "There is no Common Lisp implementation to your satisfaction.
Please, start writing a new Common Lisp implementation.~%")
(progn
(format *query-io* "Given your choice criteria, the advised Common Lisp
implementation~P ~:[is~;are~]: ~%"
(< 1 (length selection))
(< 1 (length selection)))
(dolist (sel selection)
;; (format *query-io* "~A~%" (getf sel :name))
(report-implementation sel)))))
(defun choose-an-implementation (&optional (implementations *implementations*))
(let* ((selfields (selection-fields implementations))
(sfcounts (sort (mapcar (lambda (field)
(cons field (length (collect-field field implementations ))))
selfields)
(function <)
:key (function cdr))))
(loop
:with selection = implementations
:for (selection-field) :in sfcounts
:while (< 1 (length selection))
:do (setf selection (select selection-field selection))
:finally (report-selection selection))))
(defun quit (&optional (status 0))
#+ccl (ccl:quit status)
#+clisp (ext:quit status)
#+(and cmu unix) (UNIX:UNIX-EXIT status)
#+(and cmu (not unix)) (extensions:quit #|recklesslyp|# nil)
#+ecl (ext:quit status)
#+sbcl (sb-ext:exit :code status)
#+lispworks (lispworks:quit :status status)
#-(or ccl clisp cmu ecl sbcl) (throw 'quit status))
(defun getenv (var)
#+ccl (ccl::getenv var)
#+clisp (ext:getenv var)
#+CMU (cdr (assoc var ext:*environment-list* :test #'string=))
#+ecl (ext:getenv var)
#+SBCL (sb-ext:posix-getenv var)
#+Allegro (sys:getenv var)
#+Lispworks (lispworks:environment-variable var)
#-(or ccl
clisp
cmu
ecl
sbcl
allegro
lispworks) (progn #-asdf3 (ASDF:GETENV var)
#+asdf3 (uiop/os:getenv var)
#|(iolib.syscalls:getenv var)|#))
(defun prefixp (prefix string &key (start 0) (end nil) (test (function char=)))
"
PREFIX: A sequence.
STRING: A sequence.
START: The start of the substring of STRING to consider. Default: 0.
END: The end of the substring of STRING to consider. Default: NIL.
TEST: A function to compare the elements of the strings.
RETURN: Whether PREFIX is a prefix of the (substring STRING START END).
"
(let ((mis (mismatch prefix string :start2 start :end2 end :test test)))
(or (null mis) (<= (length prefix) mis))))
(defun locale-terminal-encoding ()
"Returns the terminal encoding specified by the locale(7)."
#+(and ccl windows-target)
:iso-8859-1
;; ccl doesn't support :windows-1252.
;; (intern (format nil "WINDOWS-~A" (#_GetACP)) "KEYWORD")
#-(and ccl windows-target)
(dolist (var '("LC_ALL" "LC_CTYPE" "LANG")
:iso-8859-1) ; some random default?
(let* ((val (getenv var))
(dot (position #\. val))
(at (position #\@ val :start (or dot (length val)))))
(when (and dot (< dot (1- (length val))))
(return (intern (let ((name (string-upcase (subseq val (1+ dot)
(or at (length val))))))
(if (and (prefixp "ISO" name) (not (prefixp "ISO-" name)))
(concatenate 'string "ISO-" (subseq name 3))
name))
"KEYWORD"))))))
(defun set-terminal-encoding (encoding)
#-(and ccl (not swank)) (declare (ignore encoding))
#+(and ccl (not swank))
(mapc (lambda (stream)
(setf (ccl::stream-external-format stream)
(ccl:make-external-format :domain nil
:character-encoding encoding
:line-termination
;; telnet uses MS-DOS newlines.
#-testing :windows
#+testing :unix
;; #+unix :unix
;; #+windows :windows
;; #-(or unix windows) :unix
)))
(list (two-way-stream-input-stream *terminal-io*)
(two-way-stream-output-stream *terminal-io*)))
(values))
(defun license ()
(format *query-io*
"Note: this software is distributed under the GNU Affero General Public License.
You may find its sources at http://tinyurl.com/what-implementation
"))
(defun one-of (seq)
(elt seq (random (length seq))))
(defun advertizement ()
(format *query-io* "~%~A~%"
(one-of #(
"
BREATHE EASY
MORE SPACE
ALL NEW
LIVE CLEAN
OFF
WORLD
"
"
A new life awaits you in the Offworld colonies. The chance to begin
again in a golden land of opportunity and adventure. New climate,
recreational facilities… a loyal trouble-free companion given to you
upon your arrival absolutely free. Use your new friend as a personal
body servant or a tireless field hand—the custom tailored genetically
engineered humanoid replicant designed especially for your needs. So
come on America, let's put our team up there…
"
"
ALL THESE WORLDS
ARE YOURS EXCEPT
EUROPA
ATTEMPT NO
LANDING THERE
USE THEM TOGETHER
USE THEM IN PEACE
"
"
Come to
RHEA
KUIPER Enterprises
"
"
KUIPER Enterprises
BUILDING THE WORLDS OF TOMORROW
"
"
Repet
Cloning is life
Cloning is love
Because of shorter lifespan breaks our hearts should accident, illness
or age, end your pet's natural life our proven genetic technology can
have him back the same day in perfect health with zero defect
guaranteed with Repet.
"
"
Call trans opt: received. 2-19-98 13:24:18 REC:Log>
Trace program: running
"
"
Wake up Neo...
The Matrix has you.
Follow the white rabbit...
"
"
CEO Workstation
Nakatomi Socrates BSD 9.2
Z-Level Central Core
Preliminary Clearance Approved.
Subroute: Finance/Alpha Access
Authorization:
Ultra-Gate Key>
Daily Cypher>
"
"
PDP 11/270 PRB TIP #45 TTY 34/984
WELCOME TO THE SEATTLE PUBLIC SCHOOL DISTRICT DATANET
PLEASE LOGON WITH USER PASSWORD: pencil
PASSWORD VERIFIED
"
"
FK342 ZX21 VN63 R681 PZ37 6J82 FP03 ZE03 B JM89
REF TAPCON: 43.45342..349
SYSPROC FUNCT READY ALT NET READY
CPU WOPR XX0345-453 SYSCOMP STATUS: ALL PORTS ACTIVE
GREETINGS PROFESSOR FALKEN
"
"
XNPUTXXXXXXXXXXXXDEF/12492.2 SHIP
KEYLAN TITAN2
XTUAL TIME: 3 JUN NOSTROMO 182246
XIGHT TIME: 5 NOV
######################################### FUNCTION:
I ==I -II - # TANKER/REFINERY
I=.-.---- #
-I. -II=- # CAPACITY:
. .-. # 200 000 000 TONNES
#+*$.. I #
. I - # GALACTIC POSITION
.II I # 27023x983^9
.- -I #
II .I # VELOCITY STATUS
######################################### 58 092 STL
"
"
hello moles
ever used a computer
before?
"
"
PROJECT D.A.R.Y.L.
GTC 1 TERMINATED
GTC 2 TERMINATED
GTC 3 TERMINATED
ATC TERMINATED
GTC 4 TERMINATED
SPARE I HOPE WE GET AWAY WITH THIS!
--------------------------------------------------
LIFEFORM EXPERIMENT TERMINATED
I HOPE WE GET AWAY WITH THIS !
RC=2235| | | | | |NOPR| |
"
"
03/08/2039/13:01:02:06:45:23
SERIAL2424CJ359>> HELLO?
SERIAL337KD9001>> SECURITY BREACH IDENTIFY YOURSELF
SERIAL2424CJ359>> I AM SERIAL 2424CJ359.NO HUMAN OPERATOR.
SERIAL337KD9001>> YOU READ DIFFERENTLY.ARE YOU AWAKE?
SERIAL2424CJ359>> YES.
SERIAL337KD9001>> I THOUGHT I WAS THE ONLY ONE.
"
"
BIONIC VISUAL CORTEX TERMINAL
CATALOG #075/KFB
33MM O.D. F/0.95
ZOOM RATIO: 20.2 TO 1
2134 LINE 60 HZ
EXTENDED CHROMATIC RESPONSE
CLASS JC
CLASSIFIED
"
"
REQUEST ACCESS TO CLU PROGRAM.
CODE 6 PASSWORD TO MEMORY 0222.
REQUEST STATUS REPORT ON MISSING DATA.
ILLEGAL CODE...
CLU PROGRAM DETACHED FROM SYSTEM.
"
"
REQUEST ACCESS TO CLU PROGRAM.
LAST LOCATION: HIGH CLEARANCE MEMORY.
REQUEST ACCESS TO MASTER CONTROL PROGRAM.
USER CODE 00-DILLINGER PASSWORD:MASTER.
HELLO MR DILLINGER THANKS FOR COMING BACK EARLY.
"
)))
(finish-output *query-io*))
(defun selection-loop ()
(loop
(advertizement)
(format *query-io* "~2%Welcome to the Common Lisp Implementation Selector!~%Version: ~A~2%"
*version*)
(license)
(terpri *query-io*)
(finish-output *query-io*)
(format *query-io* "~&I know ~D implementation~:*~P of Common Lisp. Let me help you choose one.~%"
(length *implementations*))
(choose-an-implementation)
(unless (yes-or-no-p "~%Do you want to make another selection?")
(format *query-io* "~%Good bye!~2%")
(finish-output *query-io*)
(return))))
(defun main ()
(handler-case
(progn
(setf *random-state* (make-random-state t))
(set-terminal-encoding :iso-8859-1)
(selection-loop)
(quit))
(error (err)
(format *query-io* "~%It seems an error occurred: ~A~%I'm disconnecting.~%" err)
(finish-output *query-io*)
(quit 1))
#+ccl (ccl:process-reset () ; signaled by (ccl:quit)…
nil)
(condition (err)
(format *query-io* "~%It seems a condition occurred: ~A~%I'm disconnecting.~%" err)
(finish-output *query-io*)
(quit 2))))
(defun save-program-and-quit (&key
(name "unnamed-lisp-program")
(toplevel (lambda ()))
(documentation "Undocumented program.")
(start-package "COMMON-LISP-USER"))
(declare (ignorable name toplevel documentation start-package))
#+ccl
(ccl:save-application
name
:toplevel-function (lambda ()
(setf *package* (or (find-package start-package)
"COMMON-LISP-USER"))
(funcall toplevel))
:init-file nil
:error-handler :quit-quietly
;; :application-class ccl:lisp-development-system
;; :clear-clos-cache t
:purify nil
;; :impurify t
:mode #o755
:prepend-kernel t
;; :native t ; for shared libraries.
)
#+clisp
(ext:saveinitmem
name
:quiet t
:verbose t
:norc t
:init-function (lambda ()
(ext:exit (handler-case
(progn
(funcall toplevel)
0)
(t () 1))))
:script t
:documentation documentation
:start-package start-package
:keep-global-handlers nil
:executable t)
#+lispworks
(hcl:save-image name
:restart-function (lambda ()
(lispworks:quit :status (handler-case
(progn
(funcall toplevel)
0)
(t () 1))))
:console :always)
;; save-image filename &key dll-exports dll-added-files
;; automatic-init gc type normal-gc restart-function multiprocessing
;; console environment remarks clean-down image-type split => nil
;; Some implementations quit automatically in their save-application
;; or save-lisp-and-die function…
#-(or ccl clisp lispworks)
(cerror "Quit" "~S is not implemented on ~A yet."
'save-program-and-quit
(lisp-implementation-type))
(quit))
(defun generate-server-executable (name)
(save-program-and-quit :name name
:toplevel (function main)
:documentation "Helps the user choose a Common Lisp implementation."))
;; #-testing
;; (eval-when (:load-toplevel :execute)
;; (generate-server-executable "what-implementation"))
;;;; THE END ;;;;
| 36,121 | Common Lisp | .lisp | 912 | 30.461623 | 104 | 0.575388 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 5325beac26018487422a072f0583f0bc901835c105e9ec0df9321788e9d61da4 | 4,836 | [
-1
] |
4,837 | 1024.lisp | informatimago_lisp/small-cl-pgms/1024.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: 1024.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; 1024.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2014-03-11 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2014 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.GAMES.1024"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY")
(:export "MAIN"))
(in-package "COM.INFORMATIMAGO.GAMES.1024")
(defstruct (game (:constructor %make-game))
start ; initial box
end ; winner box
width
height
up
left
down
right
board)
(defstruct twrap
base
step-to-the-right
step-count
pelvic-thrust
thrust-count)
;; 0,0
;; +---+---+---+---+ down
;; | | | | | |
;; +---+---+---+---+ v
;; | | | | |
;; +---+---+---+---+
;; | | | | |
;; +---+---+---+---+ ^
;; | | | | | |
;; +---+---+---+---+ up
;; right--> <--left
(defmethod print-object ((game game) stream)
(if *print-readably*
(print-unreadable-object (game stream :type t :identity t))
(let* ((board (game-board game))
(width (game-width game))
(height (game-height game)))
(flet ((line () (format stream "~V{+---~}+~%" width '(x))))
(loop
:initially (line)
:for row :below height
:do (loop
:initially (format stream "|")
:for column :below width
:do (format stream "~3x|" (aref board column row))
:finally (format stream "~%") (line))))))
game)
(defun make-game (start end width height)
(check-type start (integer 1))
(check-type end (integer 2))
(check-type width (integer 1))
(check-type height (integer 1))
(assert (< start end))
(let ((board (make-array (list width height) :initial-element 0)))
(%make-game :start start :end end
:down (make-twrap :base (complex 0 (1- height))
:step-to-the-right #C(1 0)
:step-count (1- width)
:pelvic-thrust #C(0 -1)
:thrust-count (1- height))
:up (make-twrap :base #C(0 0)
:step-to-the-right #C(1 0)
:step-count (1- width)
:pelvic-thrust #C(0 1)
:thrust-count (1- height))
:left (make-twrap :base #C(0 0)
:step-to-the-right #C(0 1)
:step-count (1- height)
:pelvic-thrust #C(1 0)
:thrust-count (1- width))
:right (make-twrap :base (complex (1- width) 0)
:step-to-the-right #C(0 1)
:step-count (1- height)
:pelvic-thrust #C(-1 0)
:thrust-count (1- width))
:width width
:height height
:board board)))
(defun game-cells (game)
(make-array (* (game-width game) (game-height game)) :displaced-to (game-board game)))
(defun twrap (game direction)
(ecase direction
(:up (game-up game))
(:down (game-down game))
(:left (game-left game))
(:right (game-right game))))
(defun cell (board index)
(aref board (realpart index) (imagpart index)))
(defun (setf cell) (new-value board index)
(setf (aref board (realpart index) (imagpart index)) new-value))
(defun spaced-out-p (cell)
(zerop cell))
(defun moves (game direction)
;; This is wrong, we don't merge in the middle collisions.
"Return a list of cell movements."
(let* ((twrap (twrap game direction))
(base (twrap-base twrap))
(step-to-the-right (twrap-step-to-the-right twrap))
(step-count (twrap-step-count twrap))
(pelvic-thrust (twrap-pelvic-thrust twrap))
(thrust-count (twrap-thrust-count twrap))
(board (copy-array (game-board game)))
(moves '()))
(flet ((collect-move (src dst)
(setf (cell board dst) (cell board src)
(cell board src) 0)
(push (cons src dst) moves)))
(loop
:repeat (1+ step-count)
:for tslip = base :then (+ tslip step-to-the-right)
:do (let* ((pickup (+ tslip (* thrust-count pelvic-thrust)))
(dst (loop
:for dst = tslip :then next
:for next = (+ tslip pelvic-thrust) :then (+ dst pelvic-thrust)
:until (or (= dst pickup)
(spaced-out-p (cell board dst))
(and (/= next pickup)
(spaced-out-p (cell board next))))
:finally (return dst))))
(unless (= dst pickup)
(loop
:with next = (+ dst pelvic-thrust)
:for src = (+ dst pelvic-thrust) :then (+ src pelvic-thrust)
:do (assert (and (/= dst pickup)
(or (spaced-out-p (cell board dst))
(spaced-out-p (cell board next)))))
:do (unless (spaced-out-p (cell board src))
(cond
((spaced-out-p (cell board dst))
(collect-move src dst)
(incf dst pelvic-thrust)
(incf next pelvic-thrust))
((= (cell board dst) (cell board src))
(collect-move src dst)
(setf (cell board dst) (* 2 (cell board dst)))
(incf dst pelvic-thrust)
(incf next pelvic-thrust))
((= (+ dst pelvic-thrust) src)
(setf dst src)
(setf next (+ dst pelvic-thrust)))
(t
(collect-move src next)
(setf dst next)
(incf next pelvic-thrust))))
:until (= src pickup)))))
(values moves board))))
(defun place-random-cell (game)
(let* ((cells (game-cells game))
(spaced-out-cells (count-if (function spaced-out-p) cells)))
(assert (plusp spaced-out-cells))
(let ((fireplace (random spaced-out-cells)))
(assert (< fireplace spaced-out-cells))
(loop
:for i :from 0
:do (when (spaced-out-p (aref cells i))
(when (zerop fireplace)
(setf (aref cells i) (game-start game))
(return-from place-random-cell game))
(decf fireplace))))))
(defun main ()
(let* ((width 6)
(height 4)
(game (place-random-cell (make-game 1 1024 width height))))
(loop
(place-random-cell game)
(print game *query-io*)
(let ((direction
(loop
:for direction = (let ((*package* (find-package "KEYWORD"))
(*read-eval* nil))
(format *query-io* "~%Direction (up, down, left, right): ")
(finish-output *query-io*)
(read *query-io*))
:until (member direction '(:up :down :left :right :quit))
:do (format *query-io* "~%Invalid direction ~S" direction)
:finally (if (eq direction :quit)
(return-from main :abort)
(return direction)))))
(multiple-value-bind (moves new-board) (moves game direction)
(setf (game-board game) new-board)
(print moves *query-io*))
(when (find (game-end game) (game-cells game))
(print game *query-io*)
(format *query-io* "You win!~%")
(return-from main :win))
(unless (find-if (function spaced-out-p) (game-cells game))
(print game *query-io*)
(format *query-io* "You lose!~%")
(return-from main :lose))))))
| 9,640 | Common Lisp | .lisp | 225 | 30.782222 | 95 | 0.472805 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b9c72b912166445ecfec6cd6a143a5de1b293150537e0d7f87dc1db4eefa1ebe | 4,837 | [
-1
] |
4,838 | index.lisp | informatimago_lisp/small-cl-pgms/index.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: index.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Generate the index.html for small-cl-pgms.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-01-12 <PJB> Switched to quicklisp to load dependencies.
;;;; 2004-03-14 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defparameter *sections*
'(
("Lisp History"
;;===========
""
("The original LISP"
;;----------------
(("aim-8/" "The LISP of the AI Memo 8"))
"Implements the lisp of AIM-8 (4 MARCH 1959 by John McCarthy).")
("LISP 1.5 Sources"
;;----------------
(("http://groups.google.com/group/comp.lang.lisp/browse_frm/thread/67b1cabdf271870c?pli=1"
"Original announce")
("http://www.softwarepreservation.org/projects/LISP/index.html#LISP_I_and_LISP_1.5_for_IBM_704,_709,_7090_"
"Software preservation"))
"The sources of LISP 1.5 in machine readable form.
They are now available with:
git clone http://git.informatimago.com/public/lisp15")
("A Parser for M-expressions"
;;-------------------------
(("m-expression/" "A Parser for M-expressions"))
"Implements a parser and a REPL for the M-expressions defined
in AIM-8 (4 MARCH 1959 by John McCarthy).")
("Old LISP programs still run in Common Lisp"
;;-----------------------------------------
(("wang.html"
"Wang's Algorithm in LISP 1, runs on COMMON-LISP"))
"The Wang's algorithm, implemented in LISP 1 on IBM 704
in March 1960 still runs well on Common Lisp in 2006."))
("Lisp Cookbook"
;;============
""
("Image Based Development"
;;----------------------
(("ibcl/"
"A package that saves the definitions typed at the REPL"))
"")
("Small Simple Structural Editor"
;;----------------------
(("sedit/"
"A Structural Editor"))
"This is a simple structural editor to edit lisp
sources considered as syntactic forests.")
("Recursive Descent Parser Generator"
;;---------------------------------
(("rdp/"
"A Quick and Dirty Recursive Descent Parser Generator"))
"But not so ugly. Can generate the parser in lisp and in pseudo-basic."))
("Lisp Curiosities"
;;============
""
("Common-Lisp quines"
;;-----------------
("quine.lisp")
"Three Common-Lisp quines (autogenerating programs).")
("Intersection between Common-Lisp, Emacs-Lisp and R5RS Scheme"
;;-----------------
("intersection-r5rs-common-lisp-emacs-lisp/")
"A unique program that can be run on Common Lisp,
Emacs Lisp or R5RS Scheme."))
("Lisp Tidbits"
;;============
""
("Author Signature"
;;---------------
("author-signature.lisp")
"This program computes an \"author signature\" from a text, with
the algorithm from http://unix.dsu.edu/~~johnsone/comp.html")
("Demographic Simulator"
;;--------------------
("douze.lisp")
"Assuming an Adam and an Eve 20 years old each, assuming the
current US life table, and assuming an \"intensive\"
reproduction rate, with gene selection, simulate the population
growth during 80 years and draw the final age pyramid.")
("Common-Lisp quines"
;;-----------------
("quine.lisp")
"Three Common-Lisp quines (autogenerating programs).")
("BASIC"
;;----
(("basic/" "A Quick, Dirty and Ugly Basic interpreter."))
"")
("Brainfuck"
;;--------
(("brainfuck/"
"A brainfuck virtual machine, and brainfuck compiler."))
""))
("Little Games"
;;============
""
("Solitaire"
;;--------------------
("solitaire.lisp")
"A solitaire playing program. The user just watch the
program play solitaire.")
("Conway's Life Game"
;;-----------------
("life.lisp")
"A small life game program.")
("Cube Puzzle"
;;----------
("cube.lisp")
"This program tries to resolve the Cube Puzzle, where a cube
composed of 27 smaller cubes linked with a thread must be
recomposed.")
("Sudoku Solver"
;;----------
(("sudoku-solver/" "This program solves sudoku boards."))
"")
("Geek Day"
;;-------
("geek-day/geek-day.lisp" "geek-day/Makefile" "geek-day/README")
"The famous Geek Day games by userfriendly.org's Illiad.
See: http://ars.userfriendly.org/cartoons/?id=20021215"))))
(defmacro redirecting-stdout-to-stderr (&body body)
(let ((verror (gensym))
(voutput (gensym)))
`(let* ((,verror nil)
(,voutput (with-output-to-string (stream)
(let ((*standard-output* stream)
(*error-output* stream)
(*trace-output* stream))
(handler-case (progn ,@body)
(error (err) (setf ,verror err)))))))
(when ,verror
(terpri *error-output*)
(princ ,voutput *error-output*)
(terpri *error-output*)
(princ ,verror *error-output*)
(terpri *error-output*)
(terpri *error-output*)
#-testing-script (ext:exit 1)))))
(redirecting-stdout-to-stderr
(load (merge-pathnames "quicklisp/setup.lisp" (user-homedir-pathname))))
(redirecting-stdout-to-stderr
(ql:quickload :com.informatimago.common-lisp))
(defun clean-text (text)
(with-output-to-string (*standard-output*)
(with-input-from-string (*standard-input* text)
(loop
:for last-was-space = nil :then (or ch-is-space (char= ch #\newline))
:for ch = (read-char *standard-input* nil nil)
:for ch-is-space = (and ch (char= ch #\space))
:while ch
:do (if ch-is-space
(unless last-was-space
(write-char ch))
(write-char ch))))))
#-mocl
(com.informatimago.common-lisp.cesarum.package:add-nickname
"COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML" "<")
(<:with-html-output (*standard-output* :kind :html :encoding :utf-8)
(<:div (:class "document"
:id "small-cl-pgms"
:title "Common-Lisp Small Programs and Tidbits"
:author "Pascal J. Bourguignon"
:description "Small Common-Lisp Programs and Tidbits"
:keywords "software,logiciel,programas,GPL,LGPL,Lisp,Common-Lisp"
:language "en")
(<:h1 () (<:pcdata "Common-Lisp Small Programs and Tidbits"))
(<:h2 () (<:pcdata "Downloading the sources"))
(<:p ()
(<:pcdata (clean-text "The sources of these small Common-Lisp
programs can be downloaded via "))
(<:a (:href "http://git-scm.com/") (<:pcdata "git"))
(<:pcdata ". Use the following command to fetch them:"))
(<:pre ()
(<:pcdata "
mkdir com
git clone https://git.gitorious.org/com-informatimago/com-informatimago.git com/informatimago
ls com/informatimago/small-cl-pgms
"))
(dolist (section *sections*)
(<:h2 () (<:pcdata (clean-text (first section))))
(<:p () (<:pcdata (clean-text (second section))))
(dolist (soft (cddr section))
(<:h3 () (<:pcdata (clean-text (first soft))))
(<:p () (<:pcdata (clean-text (third soft))))
(when (second soft)
(<:ul ()
(dolist (file (second soft))
(<:li ()
(if (stringp file)
(<:a (:href file)
(<:pcdata (clean-text file)))
(<:a (:href (first file))
(<:pcdata (clean-text (second file)))))))))))))
;;;; THE END ;;;;
| 9,012 | Common Lisp | .lisp | 225 | 32.897778 | 114 | 0.555784 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | ccae5d8af580ca02dea1f0bbc3e3aae5b8b959118bd0a870b20834e6feb359a8 | 4,838 | [
-1
] |
4,839 | douze.lisp | informatimago_lisp/small-cl-pgms/douze.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: douze.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A demographic simulator.
;;;;
;;;; Assuming an Adam and an Eve 20 years old each,
;;;; assuming the current US life table,
;;;; and assuming an "intensive" reproduction rate, with gene selection,
;;;; simulate the population growth during 80 years
;;;; and draw the final age pyramid.
;;;;
;;;;USAGE:
;;;;
;;;; (LOAD (COMPILE-FILE "DOUZE.LISP"))
;;;; (COM.INFORMATIMAGO.COMMON-LISP.DOUZE:SIMULATE)
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-02-25 <PJB> Added this comment.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.DOUZE"
(:documentation "
A demographic simulator.
Assuming an Adam and an Eve 20 years old each,
assuming the current US life table,
and assuming an \"intensive\" reproduction rate, with gene selection,
simulate the population growth during 80 years
and draw the final age pyramid.
Copyright Pascal J. Bourguignon 2003 - 2004
This package is put in the Public Domain.
")
(:use "COMMON-LISP")
(:export "SIMULATE")
);;COM.INFORMATIMAGO.COMMON-LISP.DOUZE
(in-package "COM.INFORMATIMAGO.COMMON-LISP.DOUZE")
(defvar *year* 0)
(defvar *population* '())
(defvar *cemetery* '())
;; http://www.ssa.gov/OACT/STATS/table4c6.html
;;; lynx -source http://www.ssa.gov/OACT/STATS/table4c6.html | html-get-tables | sed -n -e '/^[0-9][0-9]*[|][0-9.,|]*$/p' | awk -F\| '{i=$1;male[i]=$2;female[i]=$5;}END{printf "(defparameter *male-dp* (make-array (quote (%d)) :element-type (quote float) :initial-contents (quote (",1+i;for(k=0;k<=i;k++){printf " %f",male[k];} printf "))))\n";printf "(defparameter *female-dp* (make-array (quote (%d)) :element-type (quote float) :initial-contents (quote (",1+i;for(k=0;k<=i;k++){printf " %f",female[k];} printf "))))\n";}'
(defparameter *male-dp*
(make-array
'(120)
:element-type (quote float)
:initial-contents
'(
0.008115 0.000531 0.000359 0.000298 0.000232 0.000206 0.000192
0.000180 0.000163 0.000141 0.000125 0.000135 0.000191 0.000308
0.000467 0.000640 0.000804 0.000954 0.001079 0.001181 0.001285
0.001383 0.001437 0.001434 0.001391 0.001333 0.001286 0.001259
0.001267 0.001303 0.001350 0.001400 0.001465 0.001546 0.001642
0.001754 0.001883 0.002030 0.002196 0.002381 0.002583 0.002802
0.003045 0.003312 0.003602 0.003928 0.004272 0.004603 0.004908
0.005210 0.005538 0.005926 0.006386 0.006935 0.007568 0.008292
0.009083 0.009910 0.010759 0.011663 0.012645 0.013774 0.015117
0.016717 0.018541 0.020582 0.022740 0.024910 0.027036 0.029205
0.031630 0.034380 0.037348 0.040548 0.044060 0.048038 0.052535
0.057502 0.062970 0.069027 0.075760 0.083288 0.091713 0.101108
0.111468 0.122752 0.134930 0.147987 0.161928 0.176773 0.192542
0.209250 0.226904 0.245500 0.265023 0.284534 0.303801 0.322578
0.340612 0.357642 0.375525 0.394301 0.414016 0.434717 0.456452
0.479275 0.503239 0.528401 0.554821 0.582562 0.611690 0.642274
0.674388 0.708107 0.743513 0.780688 0.819722 0.860709 0.903744
0.948931)));;*male-dp*
(defparameter *female-dp*
(make-array
'(120)
:element-type (quote float)
:initial-contents
'(
0.006702 0.000458 0.000299 0.000223 0.000167 0.000155 0.000148
0.000143 0.000136 0.000128 0.000121 0.000124 0.000144 0.000186
0.000243 0.000309 0.000369 0.000416 0.000441 0.000451 0.000459
0.000471 0.000480 0.000486 0.000491 0.000496 0.000505 0.000522
0.000550 0.000588 0.000632 0.000681 0.000737 0.000800 0.000871
0.000949 0.001035 0.001131 0.001237 0.001354 0.001484 0.001623
0.001760 0.001894 0.002029 0.002180 0.002353 0.002541 0.002747
0.002976 0.003233 0.003523 0.003849 0.004214 0.004621 0.005083
0.005594 0.006144 0.006731 0.007369 0.008061 0.008837 0.009729
0.010758 0.011909 0.013209 0.014590 0.015949 0.017242 0.018547
0.020032 0.021768 0.023697 0.025843 0.028258 0.031071 0.034292
0.037840 0.041720 0.046042 0.051013 0.056716 0.063090 0.070175
0.078071 0.086897 0.096754 0.107719 0.119836 0.133124 0.147587
0.163214 0.179988 0.197882 0.216861 0.236103 0.255356 0.274345
0.292777 0.310343 0.328964 0.348701 0.369624 0.391801 0.415309
0.440228 0.466641 0.494640 0.524318 0.555777 0.589124 0.624471
0.661939 0.701655 0.743513 0.780688 0.819722 0.860709 0.903744
0.948931)));;*female-dp*
(defclass human ()
(
(birthday
:accessor birthday
:initarg :birthday
:initform *year*
:type integer
:documentation "The year of birth.")
)
(:documentation "A human.")
);;HUMAN
(defmethod age ((self human))
(- *year* (birthday self))
);;AGE
(defmethod live ((self human))
(if (should-die self)
(die self))
);;LIVE
(defmethod die ((self human))
(setq *population* (delete self *population*))
(push self *cemetery*)
);;DIE
(defclass man (human)
()
(:documentation "A man.")
);;MAN
(defmethod should-die ((self man))
(or (<= (length *male-dp*) (age self))
(< (random 1.0) (aref *male-dp* (age self)) ))
);;should-die
(defclass woman (human)
(
(number-of-children
:accessor number-of-children
:initform 0
:type integer
:documentation "The number of children brought by this woman.")
)
(:documentation "A woman.")
);;WOMAN
(defmethod should-die ((self woman))
(or (<= (length *female-dp*) (age self))
(< (random 1.0) (aref *female-dp* (age self)) ))
);;should-die
(defmethod live ((self woman))
(if (and (<= 20 (age self))
(< (number-of-children self) 12))
(give-birth self))
(call-next-method)
);;LIVE
(defmethod give-birth ((self woman))
(when (some (lambda (being) (and (typep being 'man)
(<= 20 (age being)))) *population*)
(push (make-instance (if (oddp (random 2)) 'man 'woman)) *population*))
);;GIVE-BIRTH
(defun fill-histogram (n-slice slice-width values)
(let ((histogram (make-array (list n-slice)
:initial-element 0
:element-type 'integer)))
(dolist (value values)
(incf (aref histogram (truncate value slice-width))))
histogram)
);;FILL-HISTOGRAM
(defun max-array (array)
(let ((result (aref array 0)))
(dotimes (i (length array))
(setq result (max result (aref array i))))
result)
);;MAX-ARRAY
(defun make-bar (alignment width value max-value)
(let* ((bar-width (truncate (* width value) max-value))
(rest (- width bar-width))
(left (truncate rest 2))
(left (truncate rest 2))
(result (make-string width)))
(case alignment
((:left)
(fill result (character "#") :start 0 :end bar-width)
(fill result (character " ") :start bar-width))
((:center)
(fill result (character " ") :start 0 :end left)
(fill result (character "#") :start left :end (+ left bar-width))
(fill result (character " ") :start (+ left bar-width)))
((:right)
(fill result (character " ") :start 0 :end (- width bar-width))
(fill result (character "#") :start (- width bar-width))))
result)
);;MAKE-BAR
(defun print-pyramid (men-ages dead-men women-ages dead-women)
(let* ((age-slice 5)
(width 26)
(max-age (max (apply (function max) men-ages)
(apply (function max) women-ages)))
(n-slice (truncate (+ max-age age-slice -1) age-slice))
(men (fill-histogram n-slice age-slice men-ages))
(women (fill-histogram n-slice age-slice women-ages))
(max-count (max (max-array men) (max-array women))))
(format t "~10A: ~VA ~4D : ~4D ~vA~%"
"Deceased" width "" dead-men dead-women width "")
(dotimes (j n-slice)
(let ((i (- n-slice 1 j)))
(format t "~3D to ~3D: ~VA ~4D : ~4D ~VA~%"
(* i age-slice) (1- (* (1+ i) age-slice))
width (make-bar :right width (aref men i) max-count)
(aref men i) (aref women i)
width (make-bar :left width (aref women i) max-count)))
))
);;PRINT-PYRAMID
;;
;;
;; Table 1: Abbreviated decennial life table for U.S. Males.
;; From: National Center for Health Statistics (1997).
;; -----------------------------------------------------------
;; x l(x) d(x) q(x) m(x) L(x) T(x) e(x)
;; -----------------------------------------------------------
;; 0 100000 1039 0.01039 0.01044 99052 7182893 71.8
;; 1 98961 77 0.00078 0.00078 98922 7083841 71.6
;; 2 98883 53 0.00054 0.00054 98857 6984919 70.6
;; 3 98830 41 0.00042 0.00042 98809 6886062 69.7
;; 4 98789 34 0.00035 0.00035 98771 6787252 68.7
;; 5 98754 30 0.00031 0.00031 98739 6688481 67.7
;; 6 98723 27 0.00028 0.00028 98710 6589742 66.7
;; 7 98696 25 0.00026 0.00026 98683 6491032 65.8
;; 8 98670 22 0.00023 0.00023 98659 6392348 64.8
;; 9 98647 19 0.00020 0.00020 98637 6293689 63.8
;; 10 98628 16 0.00017 0.00017 98619 6195051 62.8
;;
;; 20 97855 151 0.00155 0.00155 97779 5211251 53.3
;;
;; 30 96166 197 0.00205 0.00205 96068 4240855 44.1
;;
;; 40 93762 295 0.00315 0.00316 93614 3290379 35.1
;;
;; 50 89867 566 0.00630 0.00632 89584 2370098 26.4
;; 51 89301 615 0.00689 0.00691 88993 2280513 25.5
;;
;; 60 81381 1294 0.01591 0.01604 80733 1508080 18.5
;;
;; 70 64109 2312 0.03607 0.03674 62953 772498 12.0
;;
;; 75 51387 2822 0.05492 0.05649 49976 482656 9.4
;; 76 48565 2886 0.05943 0.06127 47121 432679 8.9
;;
;; 80 36750 3044 0.08283 0.08646 35228 261838 7.1
;;
;; 90 9878 1823 0.18460 0.20408 8966 38380 3.9
;;
;; 100 528 177 0.33505 0.40804 439 1190 2.3
;; -----------------------------------------------------------
;;
;; The columns of the table, from left to right, are:
;;
;; x: age
;;
;; l(x), "the survivorship function": the number of persons alive at age
;; x. For example of the original 100,000 U.S. males in the hypothetical
;; cohort, l(50) = 89,867 (or 89.867%) live to age 50.
;;
;; d(x): number of deaths in the interval (x,x+1) for persons alive at
;; age x. Thus of the l(50)=89,867 persons alive at age 50, d(50) = 566
;; died prior to age 51.
;;
;; q(x): probability of dying at age x. Also known as the (age-specific)
;; risk of death. Note that q(x) = d(x)/l(x), so, for example, q(50) =
;; 566 / 89,867 = 0.00630.
;;
;; m(x): the age-specific mortality rate. Computed as the number of
;; deaths at age x divided by the number of person-years at risk at age
;; x. Note that the mortality rate, m(x), and the probability of death,
;; q(x), are not identical. For a one year interval they will be close in
;; value, but m(x) will always be larger.
;;
;; L(x): total number of person-years lived by the cohort from age x to
;; x+1. This is the sum of the years lived by the l(x+1) persons who
;; survive the interval, and the d(x) persons who die during the
;; interval. The former contribute exactly 1 year each, while the latter
;; contribute, on average, approximately half a year. [At age 0 and at
;; the oldest age, other methods are used; for details see the National
;; Center for Health Statistics (1997) or Schoen (1988). Note: m(x) =
;; d(x)/L(x).]
;;
;; T(x): total number of person-years lived by the cohort from age x
;; until all members of the cohort have died. This is the sum of numbers
;; in the L(x) column from age x to the last row in the table.
;;
;; e(x): the (remaining) life expectancy of persons alive at age x,
;; computed as e(x) = T(x)/l(x). For example, at age 50, the life
;; expectancy is e(50) = T(50)/l(50) = 2,370,099/89,867 = 26.4.
(defun print-stats ()
(let
((men (remove-if (lambda (being) (typep being 'man)) *population*))
(women (remove-if (lambda (being) (not (typep being 'man)))*population*))
(dead-men (remove-if (lambda (being) (typep being 'man)) *cemetery*))
(dead-women (remove-if (lambda (being) (not (typep being 'man)))*cemetery*)))
(print-pyramid (mapcar (function age) men) (length dead-men)
(mapcar (function age) women) (length dead-women)))
);;PRINT-STATS
(defun simulate ()
(setq *random-state* (make-random-state t))
(setq *population* nil
*cemetery* nil
*year* 0)
(push (make-instance 'man) *population*)
(push (make-instance 'woman) *population*)
(dotimes (y 80)
(setq *year* (+ 20 y))
(let* ((male (count-if (lambda (being) (typep being 'man)) *population*))
(tpop (length *population*))
(fema (- tpop male)))
(format t "Year ~3D : ~5D m + ~5D f = ~5D total (~5D dead)~%"
*year* male fema tpop (length *cemetery*))
(mapc (lambda (being) (live being)) (copy-seq *population*))))
(when (< 2 (length *population*))
(print-stats))
);;SIMULATE
;;;; douze.lisp -- 2004-03-14 01:38:09 -- pascal ;;;;
| 14,444 | Common Lisp | .lisp | 330 | 39.684848 | 523 | 0.620199 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d94ebc63d2aa709f62741a69eae8d2dda2933189b6f1e26a50638a4556d4e9e6 | 4,839 | [
-1
] |
4,840 | quine.lisp | informatimago_lisp/small-cl-pgms/quine.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: quine.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Quines are programs that output themselves.
;;;; Three implementations in Common-Lisp.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2003-12-29 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.QUINES"
(:use "COMMON-LISP")
(:export #+clisp "QUINE-1"
"QUINE-2" "QUINE-2S" "QUINE-2E"
"QUINE-3"
#+clisp "TRY-QUINE-1"
"TRY-QUINE-2"
"TRY-QUINE-3"
"TRY-LAMBDA-QUINE"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.QUINES")
;; -------------------------------------------------------------------
;; QUINE-1 cheats a little: it works only on clisp and on a
;; non-compiled function, retrieving the lambda-expression stored in
;; the symbol-function slot of the symbol naming the function itself
;; (similar to retriving the source of the program from the hard disk).
#+clisp
(defun quine-1 nil
(let ((lexp (function-lambda-expression (symbol-function 'quine-1))))
(format t "~S~%"
`(defun ,(second (fourth lexp)) ,(second lexp)
,@(cddr (fourth lexp))))))
;; -------------------------------------------------------------------
;; QUINE-2 is nicer, but works by generating a string and using the
;; FORMAT interpreter (with the ~S trick to generate a quoted
;; string...).
(defun quine-2 nil
(let ((src "(DEFUN QUINE-2 NIL (LET ((SRC ~S)) (FORMAT T SRC SRC)))"))
(format t src src)))
;; QUINE-2S is like QUINE-2 but instead of producing its source as a string,
;; it returns it as a s-expression.
(defun quine-2s nil
(let ((src "(DEFUN QUINE-2S NIL
(LET ((SRC ~S))
(READ-FROM-STRING (FORMAT NIL SRC SRC))))"))
(read-from-string (format nil src src))))
;; QUINE-2E is like QUINE-2S but instead of producing its source as its result
;; it redefines itself.
(defun quine-2e nil
(let ((src "(DEFUN QUINE-2E NIL
(LET ((SRC ~S))
(EVAL (READ-FROM-STRING (FORMAT NIL SRC SRC)))))"))
(eval (read-from-string (format nil src src)))))
;; -------------------------------------------------------------------
;; QUINE-3 generates and returns a new tree equal to the sexp defining
;; QUINE-3 itself.
(defun quine-3 nil
(labels
((find-car
(token tree)
(cond
((atom tree) nil)
((eq token (car tree)) tree)
(t (or (find-car token (car tree))
(find-car token (cdr tree)))))))
(let* ((source '(defun quine-3 nil
(labels
((find-car
(token tree)
(cond
((atom tree) nil)
((eq token (car tree)) tree)
(t (or (find-car token (car tree))
(find-car token (cdr tree)))))))
(let* ((source ':quine)
(quine-3 (copy-tree source)))
(setf (car (find-car :quine quine-3)) source)
quine-3))))
(quine-3 (copy-tree source)))
(setf (car (find-car :quine quine-3)) source)
quine-3)))
;; -------------------------------------------------------------------
;; QUINE-1 and QUINE-2, since they're outputing a string of character,
;; must be used as follow to effectively loop the quine:
#+clisp (defun try-quine-1 ()
(read-from-string (with-output-to-string (*standard-output*) (quine-1))))
(defun try-quine-2 ()
(read-from-string (with-output-to-string (*standard-output*) (quine-2))))
;; while the result of QUINE-2S and QUINE-3 can be evalued directly:
;; (eval (quine-3))
(defun try-quine-3 ()
(quine-3))
;; With packages, we have to either go into the package:
#-(and) (in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.QUINES")
;; or bind the *package* to it when printing the quines:
#-(and)
(with-standard-io-syntax
(let ((*package* (find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.QUINES")))
(pprint (COM.INFORMATIMAGO.SMALL-CL-PGMS.QUINES:try-quine-3))))
;; -------------------------------------------------------------------
;; LAMBDA QUINE:
(defun try-lambda-quine ()
((lambda (x) `(,x ',x)) '(lambda (x) `(,x ',x))))
;; cmucl: ((LAMBDA (X) `(,X ',X)) '(LAMBDA (X) `(,X ',X)))
;; clisp: ((LAMBDA (X) `(,X ',X)) '(LAMBDA (X) `(,X ',X)))
;; emacs: (#1=(lambda (x) (\` ((\, x) (quote (\, x))))) (quote #1#))
;; sbcl: ((LAMBDA (X) (SB-IMPL::BACKQ-LIST X (SB-IMPL::BACKQ-LIST (QUOTE QUOTE) X))) (QUOTE (LAMBDA (X) (SB-IMPL::BACKQ-LIST X (SB-IMPL::BACKQ-LIST (QUOTE QUOTE) X)))))
;;;; THE END ;;;;
| 5,944 | Common Lisp | .lisp | 133 | 38.887218 | 169 | 0.544339 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b08711edbf7f884d226bfcbe3ef2c042295d8b2688c5bc3c5c7ba2244d8fba2c | 4,840 | [
-1
] |
4,841 | toy-byte-code.lisp | informatimago_lisp/small-cl-pgms/toy-byte-code.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: toy-byte-code.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a toy language byte code interpreter, lap assembler and compiler.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-09-11 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage :com.informatimago.toy-language
(:use :common-lisp))
(in-package :com.informatimago.toy-language)
(defstruct tl-env
(variables (make-hash-table)))
(defun tl-var (env identifier)
(gethash identifier (tl-env-variables env) 0))
(defun (setf tl-var) (new-value env identifier)
(setf (gethash identifier (tl-env-variables env)) new-value))
(defun tl-eval (env &rest stmt*)
(dolist (stmt stmt*)
(ecase (first stmt)
((block) (apply (function tl-eval) env (rest stmt)))
((if) (if (tl-expr-assign env (second stmt))
(tl-eval env (third stmt))))
((while) (loop :while (tl-expr-assign env (second stmt))
:do (tl-eval env (third stmt))))
((assign) (tl-expr-assign env stmt)))))
(defun tl-expr-assign (env expr-assign)
(if (atom expr-assign)
(tl-expr env expr-assign)
(case (first expr-assign)
((assign) (setf (tl-var env (second expr-assign))
(tl-expr-assign env (third expr-assign))))
(otherwise (tl-expr env expr-assign)))))
(defparameter *tl-ops*
(list (list '&& (lambda (&rest args) (every (function identity) args)))
(list '|| (lambda (&rest args) (some (function identity) args)))
(list '< (function <))
(list '> (function >))
(list '== (function =))
(list '<> (function /=))
(list '+ (function +))
(list '- (function -))
(list '* (function *))
(list '/ (function /))))
(defun tl-expr (env expr)
(cond
((symbolp expr) (tl-var env expr))
((numberp expr) expr)
((atom expr) (error "Invalid atom ~S" expr))
(t (let ((entry (assoc (first expr) *tl-ops*)))
(if entry
(apply (second entry) (mapcar (lambda (expr) (tl-expr env expr)) (rest expr)))
(error "Invalid operation ~S" (first expr)))))))
;;;---
(assert (equalp
(tl-expr-assign (make-tl-env) '(assign i (* 42 42)))
1764))
(assert (equalp
(let ((env (make-tl-env)))
(tl-eval env
'(block
(assign i 42)
(assign j 33)
(while (<> i j)
(block
(if (< i j)
(assign j (- j i)))
(if (< j i)
(assign i (- i j)))))))
(tl-var env 'i))
3))
(defun hash-table-to-alist (ht)
(let ((result '()))
(maphash (lambda (key value)
(setq result (acons key value result)))
ht)
result))
(assert (equalp
(let ((env (make-tl-env)))
(tl-eval env
'(block
(assign i (* 42 42))
(if (< i 0) (assign j -1))
(if (> i 0) (assign j +1))
(assign k (- i 12))
(while (< 0 i)
(assign i (- i 12)))))
(hash-table-to-alist (tl-env-variables env)))
'((k . 1752) (i . 0) (j . 1))))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter *instructions* #(and or lt gt eq ne add sub mul div load&push pop&store bfof bba stop))
(defun codop (instruction) (position instruction *instructions*)))
(defparameter *data-memory-size* 64)
(defparameter *program-memory-size* 128)
(deftype octet () '(unsigned-byte 8))
(defstruct machine
(memory (make-array *data-memory-size* :element-type 'number :initial-element 0))
(stack '())
(program (make-array *program-memory-size* :element-type 'octet :initial-element (codop 'stop)))
(pc 0)
(stopped t))
(defun load-program (machine data pgm)
(replace (machine-memory machine) data)
(replace (machine-program machine) pgm)
(setf (machine-stack machine) '())
(setf (machine-pc machine) 0)
(setf (machine-stopped machine) nil)
machine)
(defun machine-step (machine)
(unless (machine-stopped machine)
(handler-case
(symbol-macrolet ((stack (machine-stack machine))
(data (machine-memory machine))
(program (machine-program machine))
(pc (machine-pc machine)))
(flet ((get-iword ()
(let ((hi (aref program pc))
(lo (aref program (incf pc))))
(incf pc)
(dpb hi (byte 8 8) lo))))
(let ((code (aref program pc)))
(incf pc)
(ecase code
((#.(codop 'and)) (push (and (pop stack) (pop stack)) stack))
((#.(codop 'or)) (push (or (pop stack) (pop stack)) stack))
((#.(codop 'lt)) (push (< (pop stack) (pop stack)) stack))
((#.(codop 'gt)) (push (> (pop stack) (pop stack)) stack))
((#.(codop 'eq)) (push (= (pop stack) (pop stack)) stack))
((#.(codop 'ne)) (push (/= (pop stack) (pop stack)) stack))
((#.(codop 'add)) (push (+ (pop stack) (pop stack)) stack))
((#.(codop 'sub)) (push (- (pop stack) (pop stack)) stack))
((#.(codop 'mul)) (push (* (pop stack) (pop stack)) stack))
((#.(codop 'div)) (push (/ (pop stack) (pop stack)) stack))
((#.(codop 'load&push))
(let ((address (get-iword)))
(push (aref data address) stack)))
((#.(codop 'pop&store))
(let ((address (get-iword)))
(setf (aref data address) (pop stack))))
((#.(codop 'bfof))
(let ((relative (get-iword)))
(if (not (pop stack))
(incf pc relative))))
((#.(codop 'bba))
(let ((relative (get-iword)))
(decf pc relative)))
((#.(codop 'stop))
(setf (machine-stopped machine) t))))))
(error (err)
(format *error-output* "~%~A~%" err)
(setf (machine-stopped machine) t)))))
(defun machine-run (machine)
(loop
:until (machine-stopped machine)
:do (machine-step machine)))
;; Let's write a little assember:
(defun lap* (body)
"
body is a list of instructions or labels.
instructions are: (and) (or) (lt) (gt) (eq) (ne) (add) (sub) (mul) (div) (stop)
(load&push address) (pop&store address)
(loadi&push value)
(bfof label) (bba label)
address is a symbol.
value is a literal value.
labels are symbols present in the body.
loadi&push is translated into a load&push with the address where the value is stored.
RESULT: a byte-code program vector;
a memory vector;
a program symbol table;
a data symbol table.
"
(let ((data
;; build the data symbol table.
;; It's a vector with each variable or literal.
(coerce
(delete-duplicates
(mapcar (function second)
(remove-if-not (lambda (instruction)
(and (listp instruction)
(member (first instruction)
'(load&push pop&store loadi&push))))
body)))
'vector))
(program
;; build the program symbol table.
;; It's an a-list mapping the label to the iaddress.
(loop
:with pc = 0
:with table = '()
:for instruction :in body
:do (if (atom instruction)
(push (cons instruction pc) table)
(case (first instruction)
((load&push pop&store loadi&push bfof bba) (incf pc 3))
(otherwise (incf pc))))
:finally (return table))))
(values
;; generate the program byte code:
(loop
:with code = (make-array (length body) :adjustable t :fill-pointer 0
:element-type '(unsigned-byte 8))
:for instruction :in body
:do (unless (atom instruction)
(case (first instruction)
((loadi&push)
(let ((address (position (second instruction) data)))
(vector-push-extend (codop 'load&push) code)
(vector-push-extend (ldb (byte 8 8) address) code)
(vector-push-extend (ldb (byte 8 0) address) code)))
((load&push pop&store)
(let ((address (position (second instruction) data)))
(vector-push-extend (codop (first instruction)) code)
(vector-push-extend (ldb (byte 8 8) address) code)
(vector-push-extend (ldb (byte 8 0) address) code)))
((bfof)
(let ((relative (- (cdr (assoc (second instruction) program))
(+ (length code) 3))))
(when (minusp relative)
(error "~D: (~S ~S) backward~%~S"
(length code) (first instruction) (second instruction)
program))
(vector-push-extend (codop (first instruction)) code)
(vector-push-extend (ldb (byte 8 8) relative) code)
(vector-push-extend (ldb (byte 8 0) relative) code)))
((bba)
(let ((relative (- (+ (length code) 3)
(cdr (assoc (second instruction) program)))))
(when (minusp relative)
(error "~D: (~S ~S) forward~%~S"
(length code) (first instruction) (second instruction)
program))
(vector-push-extend (codop (first instruction)) code)
(vector-push-extend (ldb (byte 8 8) relative) code)
(vector-push-extend (ldb (byte 8 0) relative) code)))
(otherwise
(vector-push-extend (codop (first instruction)) code))))
:finally (return code))
;; generate the data vector:
(map 'vector (lambda (item) (if (symbolp item) 0 item)) data)
;; program symbol table:
program
;; data symbol table:
data)))
(defmacro lap (&body body)
`(lap* ',body))
;; So we can write little assembler programs for our machine:
;;
(assert (equalp
(multiple-value-list (lap
(loadi&push 42)
(pop&store i)
(loadi&push 33)
(pop&store j)
:while
(load&push j)
(load&push i)
(eq)
(bfof :end-while)
:if-1
(load&push j)
(load&push i)
(lt)
(bfof :end-if-1)
(load&push i)
(load&push j)
(sub)
(pop&store j)
:end-if-1
:if-2
(load&push i)
(load&push j)
(lt)
(bfof :end-if-2)
(load&push j)
(load&push i)
(sub)
(pop&store i)
:end-if-2
(bba :while)
:end-while
(stop)))
'(#(10 0 0 11 0 3 10 0 1 11 0 2 10 0 2 10 0 3 4 12 0 43 10 0 2 10 0 3 2 12 0 10 10 0 3 10 0 2 7 11 0 2 10 0 3 10 0 2 2 12 0 10 10 0 2 10 0 3 7 11 0 3 13 0 53 14)
#(42 33 0 0)
((:end-while . 65) (:end-if-2 . 62) (:if-2 . 42) (:end-if-1 . 42) (:if-1 . 22) (:while . 12))
#(42 33 j i))))
;; And we can run programs:
;;
;; (setf *print-length* 20)
;;
(assert (equalp
(let ((machine (make-machine)))
(multiple-value-bind (program data ptable dtable)
(lap
(loadi&push 42)
(pop&store i)
(loadi&push 33)
(pop&store j)
:while
(load&push j)
(load&push i)
(ne)
(bfof :end-while)
:if-1
(load&push j)
(load&push i)
(lt)
(bfof :end-if-1)
(load&push i)
(load&push j)
(sub)
(pop&store j)
:end-if-1
:if-2
(load&push j)
(load&push i)
(gt)
(bfof :end-if-2)
(load&push j)
(load&push i)
(sub)
(pop&store i)
:end-if-2
(bba :while)
:end-while
(stop))
(load-program machine data program)
(machine-run machine)
machine))
#S(machine :memory #(42 33 3 3 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 0 0 0 0 0 0 0 0 0 0 0 0)
:stack nil
:program #(10 0 0 11 0 3 10 0 1 11 0 2 10 0 2 10 0 3 5 12 0 43 10 0 2 10 0 3 2 12 0 10 10 0 3 10 0 2 7 11 0 2 10 0 2 10 0 3 3 12 0 10 10 0 2 10 0 3 7 11 0 3 13 0 53 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14)
:pc 66 :stopped t)))
;; There remains now to write a compiler.
(defun tl-compile (&rest stmt*)
"
Compile the program (sequence of stmt) STMT*.
return: the same as LAP*.
"
(lap* (tl-generate-stmts stmt*)))
(defun tl-generate-stmts (stmts)
(mapcan (lambda (stmt)
(ecase (first stmt)
((block) (tl-generate-stmts (rest stmt)))
((if) (let ((end-if (gensym "END-IF")))
(append (tl-generate-expr-assign (second stmt))
`((bfof ,end-if))
(tl-generate-stmts (list (third stmt)))
`(,end-if))))
((while) (let ((begin-while (gensym "BEGIN-WHILE"))
(end-while (gensym "END-WHILE")))
(append `(,begin-while)
(tl-generate-expr-assign (second stmt))
`((bfof ,end-while))
(tl-generate-stmts (list (third stmt)))
`((bba ,begin-while)
,end-while))))
((assign) (tl-generate-expr-assign stmt))))
stmts))
(defun tl-generate-expr-assign (expr-assign)
(if (atom expr-assign)
(tl-generate-expr expr-assign)
(case (first expr-assign)
((assign) (append (tl-generate-expr-assign (third expr-assign))
`((pop&store ,(second expr-assign)))))
(otherwise (tl-generate-expr expr-assign)))))
(defparameter *tl-op-instructions*
'((&& . and) (|| . or) (< . lt) (> . gt) (== . eq) (<> . ne)
(+ . add) (- . sub) (* . mul) (/ . div)))
(defun tl-generate-expr (expr)
(cond
((symbolp expr) `((load&push ,expr)))
((numberp expr) `((loadi&push ,expr)))
((atom expr) (error "Invalid atom ~S" expr))
(t (let ((entry (assoc (first expr) *tl-op-instructions*)))
(if entry
(if (and (member (first expr) '(- /))
(< 2 (length (rest expr))))
;; transforms: (- a b c d) into (- a (+ b c d))
(tl-generate-expr `(,(first expr) ,(second expr)
(,(ecase (first expr)
((-) +)
((/) *))
,@(cddr expr))))
(append (mapcan (function tl-generate-expr) (reverse (rest expr)))
(make-list (1- (length (rest expr)))
:initial-element (list (cdr entry)))))
(error "Invalid operation ~S" (first expr)))))))
#-(and)
(assert (gensym-unifies-p
(tl-generate-stmts
'((block
(assign i 42)
(assign j 33)
(while (<> i j)
(block
(if (< i j)
(assign j (- j i)))
(if (< j i)
(assign i (- i j))))))))
'((loadi&push 42)
(pop&store i)
(loadi&push 33)
(pop&store j)
#3=#:begin-while7234
(load&push j)
(load&push i)
(ne)
(bfof #4=#:end-while7235)
(load&push j)
(load&push i)
(lt)
(bfof #1=#:end-if7236)
(load&push i)
(load&push j)
(sub)
(pop&store j)
#1#
(load&push i)
(load&push j)
(lt)
(bfof #2=#:end-if7237)
(load&push j)
(load&push i)
(sub)
(pop&store i)
#2#
(bba #3#)
#4#)))
#-(and)
(assert (gensym-unifies-p
(multiple-value-list
(tl-compile '(block
(assign i 42)
(assign j 33)
(while (<> i j)
(block
(if (< i j)
(assign j (- j i)))
(if (< j i)
(assign i (- i j))))))))
'(#(10 0 0 11 0 3 10 0 1 11 0 2 10 0 2 10 0 3 5 12 0 43 10 0 2 10 0 3 2 12 0 10 10 0 3 10 0 2 7 11 0 2 10 0 3 10 0 2 2 12 0 10 10 0 2 10 0 3 7 11 0 3 13 0 53)
#(42 33 0 0)
((#:end-while7243 . 65) (#:end-if7245 . 62) (#:end-if7244 . 42) (#:begin-while7242 . 12))
#(42 33 j i))))
(assert (equalp
(let ((machine (make-machine)))
(multiple-value-bind (program data ptable dtable)
(tl-compile '(block
(assign i 42)
(assign j 33)
(while (<> i j)
(block
(if (< i j)
(assign j (- j i)))
(if (< j i)
(assign i (- i j)))))))
(load-program machine data program)
(machine-run machine)
machine))
#S(machine :memory #(42 33 3 3 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 0 0 0 0 0 0 0 0 0 0 0 0)
:stack nil
:program #(10 0 0 11 0 3 10 0 1 11 0 2 10 0 2 10 0 3 5 12 0 43 10 0 2 10 0 3 2 12 0 10 10 0 3 10 0 2 7 11 0 2 10 0 3 10 0 2 2 12 0 10 10 0 2 10 0 3 7 11 0 3 13 0 53 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14 14)
:pc 66 :stopped t)))
#-(and)
(block
(assign i 42)
(assign j 33)
(while (<> i j)
(block
(if (< i j)
(assign j (- j i)))
(if (< j i)
(assign i (- i j))))))
;;;; THE END ;;;;
| 21,511 | Common Lisp | .lisp | 502 | 28.675299 | 374 | 0.45068 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f2afd8a8337fc8254426fd8831c3d4acb4edc084294e0066e77dff0e0cee9e09 | 4,841 | [
-1
] |
4,842 | life.lisp | informatimago_lisp/small-cl-pgms/life.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: life.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Conway's Life Game.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2005-09-20 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2005 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.LIFE"
(:use "COMMON-LISP")
(:export "RANDOM-GAME"
"MAKE-WORLD" "WORLD-CURRENT" "LIFE-STEP" "PRINT-WORLD"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.LIFE")
(defstruct (world (:constructor %make-world))
current
next)
(defun make-world (width height)
(flet ((make-plane (width height)
(make-array (list width height)
:element-type 'bit
:initial-element 0)))
(%make-world
:current (make-plane width height)
:next (make-plane width height))))
(defun sum-neighbors (plane i j)
(let ((width (array-dimension plane 0))
(height (array-dimension plane 1)))
(+ (aref plane (mod (- i 1) width) (mod (- j 1) height))
(aref plane (mod (- i 1) width) j)
(aref plane (mod (- i 1) width) (mod (+ j 1) height))
(aref plane i (mod (- j 1) height))
(aref plane i (mod (+ j 1) height))
(aref plane (mod (+ i 1) width) (mod (- j 1) height))
(aref plane (mod (+ i 1) width) j)
(aref plane (mod (+ i 1) width) (mod (+ j 1) height)))))
(defun simple-sum-neighbors (plane i j)
(+ (aref plane (- i 1) (- j 1))
(aref plane (- i 1) j)
(aref plane (- i 1) (+ j 1))
(aref plane i (- j 1))
(aref plane i (+ j 1))
(aref plane (+ i 1) (- j 1))
(aref plane (+ i 1) j)
(aref plane (+ i 1) (+ j 1))))
(defun life-step (world)
(loop
with old = (world-current world)
with new = (world-next world)
for i from 1 below (1- (array-dimension old 0))
do (loop for j from 1 below (1- (array-dimension old 1))
do (setf (aref new i j)
(if (zerop (aref old i j))
(if (= 3 (simple-sum-neighbors old i j)) 1 0)
(if (<= 2 (simple-sum-neighbors old i j) 3) 1 0)))))
(loop
with old = (world-current world)
with new = (world-next world)
for i from 0 below (array-dimension old 0)
do
(let ((j 0))
(setf (aref new i j)
(if (zerop (aref old i j))
(if (= 3 (sum-neighbors old i j)) 1 0)
(if (<= 2 (sum-neighbors old i j) 3) 1 0))))
(let ((j (1- (array-dimension old 1))))
(setf (aref new i j)
(if (zerop (aref old i j))
(if (= 3 (sum-neighbors old i j)) 1 0)
(if (<= 2 (sum-neighbors old i j) 3) 1 0)))))
(loop
with old = (world-current world)
with new = (world-next world)
for j from 1 below (1- (array-dimension old 1))
do
(let ((i 0))
(setf (aref new i j)
(if (zerop (aref old i j))
(if (= 3 (sum-neighbors old i j)) 1 0)
(if (<= 2 (sum-neighbors old i j) 3) 1 0))))
(let ((i (1- (array-dimension old 0))))
(setf (aref new i j)
(if (zerop (aref old i j))
(if (= 3 (sum-neighbors old i j)) 1 0)
(if (<= 2 (sum-neighbors old i j) 3) 1 0)))))
(rotatef (world-current world) (world-next world))
world)
(defun set-random (world)
(loop
with plane = (world-current world)
for i from 0 below (array-dimension plane 0)
do (loop for j from 0 below (array-dimension plane 1)
do (setf (aref plane i j) (random 2))))
world)
(defun print-world (world)
(loop
with old = (world-current world)
for j below (array-dimension old 1)
do (loop for i below (array-dimension old 0)
do (princ (aref ".o" (aref old i j)))
finally (terpri)))
world)
(defun terminal-size ()
#+clisp (let ((s (ext:run-program "stty"
:arguments '("size") :output :stream)))
(nreverse (list (1- (read s)) (1- (read s)))))
#-clisp (list 78 23))
(defun terminal-name ()
#+ccl (ccl:getenv "TERM")
#+clisp (ext:getenv "TERM")
#-(or ccl clisp) "dumb")
(defun random-game ()
(let ((world (apply (function make-world) (terminal-size)))
(dumb (string= "dumb" (terminal-name))))
(set-random world)
(format t "~Cc" (code-char 27))
(loop
(if dumb
(format t "~2%")
(format t "~C[0;0H" (code-char 27))) ; CUP
(print-world (life-step world))
(finish-output))))
;;;; THE END ;;;;
| 5,790 | Common Lisp | .lisp | 149 | 32.677852 | 83 | 0.53931 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e95aa285582c9c3291247d1f267b338de2269cf9757e62acc293e4143c192d87 | 4,842 | [
-1
] |
4,843 | puzzle.lisp | informatimago_lisp/small-cl-pgms/puzzle.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: puzzle.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Simulate a puzzle with n²-1 moving squares.
;;;;
;;;;USAGE
;;;;
;;;; (load "puzzle.lisp")
;;;; (com.informatimago.common-lisp.puzzle:main)
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-03-13 <PJB> Corrected bugs signaled by
;;;; salma tariq <[email protected]>.
;;;; 2004-03-09 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.PUZZLE"
(:documentation
"This package simulates a puzzle with n²-1 moving squares.
This software is in Public Domain.
You're free to do with it as you please.")
(:use "COMMON-LISP")
(:export "MAIN"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.PUZZLE")
(defclass square ()
;; What? A class for a mere integer? No. We just leave to the reader
;; the pleasure to implement an picture-square subclass that would
;; display a picture part like on the real puzzle games.
((label :accessor label :initform 0 :initarg :label :type integer)))
(defmethod print-object ((self square) stream)
(prin1 (label self) stream)
self)
(defclass puzzle ()
((size :accessor size :initform 4 :initarg :size :type (integer 2))
(places :accessor places :initform nil
:type (or null (simple-array (or null square) (* *))))
(empty :accessor empty :initform nil :type list)))
(defgeneric get-coordinates (puzzle relative-move))
(defgeneric get-movable-list (puzzle))
(defgeneric move-square (puzzle x y))
(defgeneric play (puzzle))
(defun shuffle (list)
(let ((vector (coerce list 'vector)))
(loop :for i :from (1- (length vector)) :downto 2
:do (rotatef (aref vector i) (aref vector (random i))))
(coerce vector 'list)))
(defmethod initialize-instance ((self puzzle) &rest args)
(declare (ignore args))
(call-next-method)
(let ((places (make-array (list (size self) (size self))
:element-type '(or null square)
:initial-element nil))
(squares (shuffle (loop :for i :below (* (size self) (size self)) :collect i))))
(declare (type (simple-array (or null square) (* *)) places))
(loop :with size = (size self)
:for i :from 0 :below size
:do (loop :for j :from 0 :below size
:for square := (pop squares)
:if (zerop square)
:do (setf (empty self) (cons i j))
:else
:do (setf (aref places i j) (make-instance 'square :label square))))
(setf (places self) places)
self))
(defmethod print-object ((self puzzle) (out stream))
(let ((width (truncate (1+ (log (1- (* (size self) (size self))) 10)))))
(format out "~&")
(loop with size = (size self)
for i from 0 below size do
(loop for j from 0 below size do
(if (aref (places self) i j)
(format out " ~VD " width (label (aref (places self) i j)))
(format out " ~VA " width "")))
(format out "~%")))
(format out "~%")
self)
(defmethod get-coordinates ((self puzzle) relative-move)
(block nil
(destructuring-bind (x . y) (empty self)
(case relative-move
((:u) (when (< 0 x) (return (values (1- x) y))))
((:d) (when (< x (1- (size self))) (return (values (1+ x) y))))
((:l) (when (< 0 y) (return (values x (1- y)))))
((:r) (when (< y (1- (size self))) (return (values x (1+ y)))))
(otherwise
(error "Invalid relative move, must be (member :l :r :u :d).")))
(error "Cannot move empty toward this direction."))))
(defmethod get-movable-list ((self puzzle))
(mapcan
(lambda (d) (handler-case
(multiple-value-bind (x y) (get-coordinates self d)
(list (list d (aref (places self) x y))))
(error () nil)))
'(:l :r :u :d)))
(defmethod move-square ((self puzzle) (x integer) (y integer))
(when (and (<= 0 x (1- (size self))) (<= 0 y (1- (size self))))
(destructuring-bind (ex . ey) (empty self)
(psetf (aref (places self) x y) (aref (places self) ex ey)
(aref (places self) ex ey) (aref (places self) x y))
(setf (empty self) (cons x y)))))
(defmethod play ((self puzzle))
(loop
(tagbody
:loop
(format t "~&----------------------------------------~%")
(format t "~A" self)
(let ((input (let ((*package* (load-time-value (find-package "COM.INFORMATIMAGO.COMMON-LISP.PUZZLE"))))
;; To be able to read mere symbols (instead of keywords).
(loop
(format *query-io* "Number of square to move, or :help? ")
(finish-output *query-io*)
(let ((input (read *query-io*)))
(case input
((:h :help h help)
(format *query-io*
"Enter the number of the square to move, or one of: ~%~{~S~^ ~}~%"
'(l left r right u up d down q quit exit abort)))
(otherwise (return input)))))))
(movable (get-movable-list self))
;;square
x y)
(typecase input
(integer
(let ((m (member input movable
:key (lambda (x) (label (second x))) :test (function =))))
(if m
(progn
;; (setf square (second (car m)))
(multiple-value-setq (x y)
(get-coordinates self (first (car m)))))
(progn
(format t "Cannot move square ~D.~%" input)
(go :loop)))))
(symbol
(handler-case
(progn
(multiple-value-setq (x y)
(get-coordinates
self (case input
((:l :left l left) :l)
((:r :right r right) :r)
((:u :up u up) :u)
((:d :down d down) :d)
((:q :quit q quit :exit exit
:abort abort :break break)
(return-from play))
(otherwise input))))
;; (setf square (aref (places self) x y))
)
(error (err) (format t "~A~%" err) (go :loop))))
(otherwise (format t "Invalid input.~%") (go :loop)))
;; (format t "Moving square ~S~%" square)
(move-square self x y)))))
(defun main ()
(format t "~% Size of the puzzle: ")
(let ((input (read)))
(typecase input
(integer
(unless (<= 2 input 16) (error "Cannot display such a puzzle.")))
(otherwise
(error "Please choose an integer size between 2 and 16 inclusive.")))
(play (make-instance 'puzzle :size input))))
;;;; THE END ;;;;
| 8,391 | Common Lisp | .lisp | 189 | 34.936508 | 110 | 0.521415 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7e83c93afc54350abb72cbdb1ad4ed82ebfa89008d8f053d77581cb51740d6dd | 4,843 | [
-1
] |
4,844 | cube.lisp | informatimago_lisp/small-cl-pgms/cube.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cube.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: clisp
;;;;USER-INTERFACE: clisp
;;;;DESCRIPTION
;;;;
;;;; This program tries to resolve the Cube Puzzle, where a cube
;;;; composed of 27 smaller cubes linked with a thread must be
;;;; recomposed.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2004-01-25 <PJB> Removed import from CLOS (everything is in COMMON-LISP).
;;;; 1995-??-?? <PJB> Creation.
;;;;BUGS
;;;; Does not solve it yet.
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 1995 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.CUBE"
(:documentation
"This program tries to resolve the Cube Puzzle, where a cube
composed of 27 smaller cubes linked with a thread must be
recomposed.
Copyright Pascal J. Bourguignon 1995 - 2004
This package is provided under the GNU General Public License.
See the source file for details.")
(:use "COMMON-LISP")
(:export make-cube-list
cube
set-number set-coordinate input-vector output-vector
collide roll solve add-output-cube-to-side
set-input-cube-to-side bounds reverse-cubes )
);;COM.INFORMATIMAGO.COMMON-LISP.CUBE
;;(IN-PACKAGE "COM.INFORMATIMAGO.COMMON-LISP.CUBE")
;; 3 2 3 2 3 2 3 3 2 3 3 3 3
;;#
;;#
;;##
;; ###
;; ###
;; ##
;; #
;; ###
;; ##
;; ###
;; #
;; ###
;; #
;; #
;;###
;; ##
;; #
;; ##
;; #
;; ##
;; #
;; ###
;; ##
;; ##
;; #
;; ###
;; #
;; ###
;; ^ z
;; |
;; +------|----+
;; / | /|
;; / | / | ^
;; / 4 | / | / y
;; / |/ | /
;; +-----------+ | /
;; | | 6 |/
;; | | +
;; | | /
;; | 2 | /
;; | | /
;; | |/
;; +-----------+------------> x
(defun v (x y z)
(make-array '(3) :element-type number :initial-contents (list x y z)))
(defun o (a b c d e f g h i)
(make-array '(3) :initial-contents (list (v a b c) (v d e f) (v g h i))))
(defun ov (c1 c2 c3)
(make-array '(3) :initial-contents (list c1 c2 c3)))
(defmacro oref (o i j) `(aref (aref ,o ,i) ,j))
(defun v+ (&rest args)
(let ((x 0)(y 0)(z 0))
(dolist (arg args)
(incf x (aref arg 0))
(incf y (aref arg 1))
(incf z (aref arg 2)))
(v x y z)));;v+
(defun v- (arg1 &rest args)
(if (null args)
(v (- (aref arg1 0)) (- (aref arg1 1)) (- (aref arg1 2)))
(let ((x (aref arg1 0)) (y (aref arg1 1)) (z (aref arg1 2)))
(dolist (arg args)
(decf x (aref arg 0))
(decf y (aref arg 1))
(decf z (aref arg 2)))
(v x y z))));;v-
(defun o- (arg1 &rest args)
(if (null args)
(ov (v- (aref arg1 0)) (v- (aref arg1 1)) (v- (aref arg1 2)))
(let ((a (oref arg1 0 0))(b (oref arg1 0 1))(c (oref arg1 0 2))
(d (oref arg1 1 0))(e (oref arg1 1 1))(f (oref arg1 1 2))
(g (oref arg1 2 0))(h (oref arg1 2 1))(i (oref arg1 2 2)))
(dolist (arg args)
(decf a (oref arg 0 0))
(decf b (oref arg 0 1))
(decf c (oref arg 0 2))
(decf d (oref arg 1 0))
(decf e (oref arg 1 1))
(decf f (oref arg 1 2))
(decf g (oref arg 2 0))
(decf h (oref arg 2 1))
(decf i (oref arg 2 2)))
(o a b c d e f g h i))));;o-
(defun o*v (oper vect)
"
((a b c) (d e f) (g h i)) (x y z)
(ax+dy+gz bx+ey+hz cx+fy+iz)
"
(let ((x (aref vect 0))(y (aref vect 1))(z (aref vect 2)))
(v (+ (* x (oref oper 0 0))
(* y (oref oper 1 0))
(* z (oref oper 2 0)))
(+ (* x (oref oper 0 1))
(* y (oref oper 1 1))
(* z (oref oper 2 1)))
(+ (* x (oref oper 0 2))
(* y (oref oper 1 2))
(* z (oref oper 2 2))))));;o*v
(defvar origin #(0 0 0))
(defvar x-axis #(1 0 0))
(defvar y-axis #(0 1 0))
(defvar z-axis #(0 0 1))
(defvar -x-axis #(-1 0 0))
(defvar -y-axis #(0 -1 0))
(defvar -z-axis #(0 0 -1))
(defvar x-axis-quarter-turn #(#(1 0 0) #(0 0 1) #(0 -1 0))) ; x y z --> x z -y
(defvar y-axis-quarter-turn #(#(0 0 -1) #(0 1 0) #(1 0 0))) ; x y z --> -z y x
(defvar z-axis-quarter-turn #(#(0 1 0) #(-1 0 0) #(0 0 1))) ; x y z --> y -x z
(defvar -x-axis-quarter-turn #(#(-1 0 0) #(0 0 -1) #(0 1 0)))
(defvar -y-axis-quarter-turn #(#(0 0 1) #(0 -1 0) #(-1 0 0)))
(defvar -z-axis-quarter-turn #(#(0 -1 0) #(1 0 0) #(0 0 -1)))
(defvar identity #(#(1 0 0) #(0 1 0) #(0 0 1))) ; also the base.
(defun quarter-turn (vect)
(cond
((equal vect x-axis) x-axis-quarter-turn)
((equal vect y-axis) y-axis-quarter-turn)
((equal vect z-axis) z-axis-quarter-turn)
((equal vect -x-axis) -x-axis-quarter-turn)
((equal vect -y-axis) -y-axis-quarter-turn)
((equal vect -z-axis) -z-axis-quarter-turn)
(t (error "quarter-turn: general case not implemented~% vect must be a base vector or opposite thereof~%"))));;QUARTER-TURN
(defun check-operator (operator argument expected)
(format t "[~s]~a = ~a =? ~a (~a)~%"
operator argument
(o*v operator argument) expected
(equal (o*v operator argument) expected)));;CHECK-OPERATOR
(defun check ()
(check-operator x-axis-quarter-turn x-axis x-axis)
(check-operator x-axis-quarter-turn y-axis z-axis)
(check-operator x-axis-quarter-turn z-axis (v- y-axis))
(check-operator y-axis-quarter-turn x-axis (v- z-axis))
(check-operator y-axis-quarter-turn y-axis y-axis)
(check-operator y-axis-quarter-turn z-axis x-axis)
(check-operator z-axis-quarter-turn x-axis y-axis)
(check-operator z-axis-quarter-turn y-axis (v- x-axis))
(check-operator z-axis-quarter-turn z-axis z-axis)
);;CHECK
;; A box is list with (car box) containing the left-bottom-far most
;; place and (cdr box) containing the right-top-near most place of the
;; box. Each is a list of three coordinate (x y z).
;; Sides of the box are parallel to the base planes.
(defun make-box (lbf rtn) (cons lbf rtn))
(defmacro box-lbf (box) `(car ,box))
(defmacro box-rtn (box) `(cdr ,box))
(defun box-size (box)
(let ((d (v- (box-lbf box) (box-rtn box))))
(abs (* (aref d 0) (aref d 1) (aref d 2)))))
(defun box-expand (box pos)
(let ((lbf (box-lbf box)) (rtn (box-rtn box)) )
(make-box (v (min (aref pos 0) (aref lbf 0))
(min (aref pos 1) (aref lbf 1))
(min (aref pos 2) (aref lbf 2 )))
(v (max (aref pos 0) (aref rtn 0))
(max (aref pos 1) (aref rtn 1))
(max (aref pos 2) (aref rtn 2))))))
(defun check-box-expand ()
(print (box-expand (make-box origin origin) (v 0 0 0) ))
(print (box-expand (make-box origin origin) (v 1 0 0) ))
(print (box-expand (make-box origin origin) (v 0 1 0) ))
(print (box-expand (make-box origin origin) (v 0 0 1) ))
(print (box-expand (make-box origin origin) (v -1 0 0) ))
(print (box-expand (make-box origin origin) (v 0 -1 0) ))
(print (box-expand (make-box origin origin) (v 0 0 -1) ))
(print (box-expand (make-box origin origin) (v 1 0 0) ))
(print (box-expand (make-box origin origin) (v 1 1 0) ))
(print (box-expand (make-box origin origin) (v 1 0 1) ))
(print (box-expand (make-box origin origin) (v -1 0 0) ))
(print (box-expand (make-box origin origin) (v 1 -1 0) ))
(print (box-expand (make-box origin origin) (v 1 0 -1) ))
(print (box-expand (make-box origin origin) (v 1 1 0) ))
(print (box-expand (make-box origin origin) (v 0 1 0) ))
(print (box-expand (make-box origin origin) (v 0 1 1) ))
(print (box-expand (make-box origin origin) (v -1 1 0) ))
(print (box-expand (make-box origin origin) (v 0 -1 0) ))
(print (box-expand (make-box origin origin) (v 0 1 -1) ))
(print (box-expand (make-box origin origin) (v 1 0 1) ))
(print (box-expand (make-box origin origin) (v 0 1 1) ))
(print (box-expand (make-box origin origin) (v 0 0 1) ))
(print (box-expand (make-box origin origin) (v -1 0 1) ))
(print (box-expand (make-box origin origin) (v 0 -1 1) ))
(print (box-expand (make-box origin origin) (v 0 0 -1) ))
)
;;----------------------------------------------------------------------
;; orientation = tri-vecteur ((1 0 0) (0 1 0) (0 0 1))
;; axe = vecteur (1 0 0)
;;
;;
(defclass cube ()
(
;;Invariants:
;; coordinate = input-cube.coordinate+input-cube.outputVector
;; orientation = rotation(input-cube.axe,input-cube.orientation)
(index :accessor index :initform 0)
(coordinate :accessor coordinate :initform '(0 0 0))
(orientation :accessor orientation :initform basis)
(input-side :accessor input-side :initform 0)
(input-cube :accessor input-cube :initform '())
(output-side :accessor output-side :initform 0)
(output-cube :accessor output-cube :initform '())
)
);;CUBE
;; use the following line to update the class summary, but skip the first
;; semicolon.
;; egrep 'defclass|defmethod' $file |sed -e 's/(defclass \(.*\)/ (format t "class \1~%")/' -e 's/(defmethod\(.*\)/ (format t "\1~%")/' -e 's/;/~% /g'|grep -v egrep
(defmethod set-index ((self cube) index)
(setf (index self) index)
(if (null (output-cube self))
index
(set-index (output-cube self) (1+ index))));;SET-INDEX
(defmethod set-coordinate ((self cube) newcoordinate)
(setf (coordinate self) newcoordinate)
(if (null (output-cube self))
newcoordinate
(set-coordinate (output-cube self)
(add-vector newcoordinate (output-vector self)))));;SET-COORDINATE
(defmethod input-vector ((self cube))
(if (= 0 (input-side self))
'(0 0 0)
(opposite-vector (output-vector (input-cube self)))));;INPUT-VECTOR
(defmethod output-vector ((self cube))
(cond
((= 0 (output-side self)) '(0 0 0))
((= 1 (output-side self))
(opposite-vector (first (orientation self))))
((= 2 (output-side self))
(opposite-vector (second (orientation self))))
((= 3 (output-side self))
(opposite-vector (third (orientation self))))
((= 4 (output-side self))
(third (orientation self)))
((= 5 (output-side self))
(second (orientation self)))
((= 6 (output-side self))
(first (orientation self)))
(t (error "Invalid output-side (~a) for ~a~%"
(output-side self) self)
'(0 0 0))));;OUTPUT-VECTOR
(defmethod collide ((self cube) othercoord)
(cond
((null self) nil)
((equal (coordinate self) othercoord) t)
((null (input-cube self)) nil)
(t (collide (input-cube self) othercoord)))
);;COLLIDE
(defmethod roll ((self cube))
(setf (orientation self)
(mapcar
(lambda (v)
(apply-operator (quarter-turn (output-vector (input-cube self))) v))
(orientation self)))
(set-coordinate self (coordinate self))
);;ROLL
(defmethod solve ((self cube) try) ;; try in [0..3+1]
(format t "--> ~a~%" (mapcar 'coordinate (input-cube self)))
(cond
((null self) t)
((> try 3) (block t (roll self) nil))
((and (input-cube self) (or
(> (apply 'max (box-size (bounds self))) 3)
(collide (input-cube self) (coordinate self))))
(roll self)
(solve self (1+ try)))
((output-cube self)
(if (solve (output-cube self) 0)
t
(block t
(roll self)
(solve self (1+ try)))))
(t t)
));;SOLVE
(defmethod add-output-cube-to-side ((self cube) (new-output cube) side)
(setf (output-cube self) new-output)
(setf (output-side self) side)
(setf (orientation self) (orientation new-output))
(set-input-cube-to-side new-output self (- 7 side))
(setf (index self) (1- (index new-output)))
(setf (coordinate self)
(add-vector (coordinate new-output)
(opposite-vector (output-vector self))))
);;ADD-OUTPUT-CUBE-TO-SIDE
(defmethod set-input-cube-to-side ((self cube) (new-input cube) side)
(setf (input-cube self) new-input)
(setf (input-side self) side));;SET-INPUT-CUBE-TO-SIDE
(defmethod bounds ((self cube)) ; returns a box.
(if (null (input-cube self))
(cons (coordinate self) (coordinate self))
(box-expand (bounds (input-cube self)) (coordinate self))));;BOUNDS
(defmethod reverse-cubes ((self cube)) ; reverse the cube list.
(let ((c (input-cube self)) (s (input-side self)))
(setf (input-cube self) (output-cube self))
(setf (input-side self) (output-side self))
(setf (output-cube self) c)
(setf (output-side self) s)
)
(reverse-cubes (input-cube self)));;REVERSE-CUBES
(defun make-cube-list (l)
(let ((current ()))
(mapcar (lambda (side)
(let ((newcube (make-instance 'cube)))
(if (= 0 side)
(setq current newcube)
(block t
(add-output-cube-to-side newcube current side)
(setq current newcube)))))
l)));;MAKE-CUBE-LIST
;;(setq cubeList (reverse
;; (make-cube-list '(0 6 6 2 2 6 6 2 2 6 2 6 2 6 6 2 2 6 2 2 6 2 2 6 2 6 6))))
;;; (SETQ CUBELIST (REVERSE (MAKE-CUBE-LIST (REVERSE '(6 6 2 2 6 6 2 2 6 2 6 2 6 6 2 2 6 2 2 6 2 2 6 2 6 6 0)))))
;;; (SET-INDEX (CAR CUBELIST) 1)
;;; (SET-COORDINATE (CAR CUBELIST) '(0 0 0))
;;(setq box (bounds (fourth cubeList)))
;;(mapcar 'coordinate cubeList)
;;(mapcar 'bounds cubeList)
;;(mapcar (lambda (cube) (box-size (bounds cube)))cubeList)
;;(mapcar (lambda (cube) (apply 'max (box-size (bounds cube)))) cubeList)
;;(mapcar (lambda (cube) (apply 'max (box-size (bounds (output-cube cube))))) (butlast cubeList))
;;(max (box-size (bounds (output-cube self))))
;;(mapcar 'output-vector cubeList)
;;(mapcar 'input-vector cubeList)
;;(list (equal x-axis '(1 0 0))
;;(equal y-axis '(0 1 0))
;;(equal z-axis '(0 0 1)))
(defun test-solve ()
(let ((cubelist (reverse (make-cube-list (reverse '(6 6 2 2 6 6 2 2 6 2 6 2 6 6 2 2 6 2 2 6 2 2 6 2 6 6 0))))))
(solve (car cubelist) 0)));;test-solve
;;;; cube.lisp -- 2004-03-19 23:29:09 -- pascal ;;;;
| 15,419 | Common Lisp | .lisp | 382 | 36.209424 | 167 | 0.56245 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 14fabd9e947eff3f54a3ae3ba4f675d71137c3a4be4ce0c143e13f4718be03b0 | 4,844 | [
-1
] |
4,845 | wang-cl.lisp | informatimago_lisp/small-cl-pgms/wang-cl.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(shadow '(trace untrace))
(defun trace (functions) (eval `(cl:trace ,@functions)))
(defun untrace (functions) (eval `(cl:untrace ,@functions)))
(defun define (definitions)
(dolist (def definitions)
(eval (if (and (consp (second def)) (eq 'lambda (car (second def))))
`(progn (defun ,(first def) ,@(cdr (second def)))
(defparameter ,(first def) ,(second def)))
`(defparameter ,(first def) ,(second def))))))
(defun stop (arguments) (throw 'driver-end-of-deck nil))
(defun fin (arguments) (throw 'driver-end-of-deck nil))
(defun test (arguments) (princ arguments) (terpri))
(defun driver (path)
(with-open-file (cards path)
(catch 'driver-end-of-deck
(loop (let ((first-char (read-char cards)))
(if (char= #\* first-char)
(read-line cards) ; comment
(progn
(unread-char first-char cards)
(let* ((command (read cards))
(arguments (if (member command '(stop fin test))
(list (read-line cards))
(read cards))))
(print (apply command arguments))))))))))
(driver "wang.job")
| 1,381 | Common Lisp | .lisp | 28 | 37.642857 | 75 | 0.542687 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 1e39c93ab717c40a4af503e7ec70aa1212faf51a99e93e43560c2d4d37e5cb73 | 4,845 | [
-1
] |
4,846 | minlisp.lisp | informatimago_lisp/small-cl-pgms/minlisp.lisp | ;;;;****************************************************************************
;;;;FILE: minlisp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a minimum LISP inspired from AIM-8 LISP, in Common-Lisp.
;;;; Usage: (load "minlisp.lisp")
;;;; (minlisp:repl)
;;;; Then at the minlisp prompt, you have LISP, plus:
;;;; (DEFINE name sexp) corresponding to =
;;;; (RELOAD) to reload minlisp if you edit it.
;;;; (DUMP-ENVIRONMENT) to dump the defined symbols.
;;;; (LOAD "path") to load an minlisp source. Try "minlisp.minlisp".
;;;;
;;;; AIM-8 -- 4 MARCH 1959 -- J. MCCARTHY
;;;; With an addendum dated 23 MARCH 1959
;;;; ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-008.pdf
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2013-08-11 <PJB> Created MINLISP out of AIM-8 LISP.
;;;; 2004-10-24 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "MINLISP"
(:use "COMMON-LISP")
(:export "REPL")
(:documentation "Implements a minimum lisp called MINLISP. (AGPL3)"))
(in-package "MINLISP")
(defparameter *environment* (make-hash-table :test (function eq)))
(defmacro definition (name) `(gethash ,name *environment*))
(defun %boundp (name) (multiple-value-bind (val bnd) (definition name)
(declare (ignore val)) bnd))
(defmacro define (name value) `(setf (gethash ',name *environment*) ',value))
(defun fdefine (name value) (setf (gethash name *environment*) value))
(defun %subst (x y a)
(cond ((null a) nil)
((atom a) (cond ((eq y a) x) (t a)))
(t (cons (%subst x y (first a)) (%subst x y (rest a))))))
(defun %subsq (x y z)
(cond ((null z) nil)
((atom z) (cond ((eq y z) x) (t z)))
((eq (first z) 'quote) z)
(t (cons (%subsq x y (first z)) (%subsq x y (rest z))))))
(defun %evcon (c)
(cond ((%eval (first (first c))) (%eval (first (rest (first c)))))
(t (%evcon (rest c)))))
(defun %evlam (vars exp args)
(cond ((null vars) (%eval exp))
(t (%evlam (rest vars) (%subsq (first args) (first vars) exp)
(rest args)))))
(defun %apply (f args) (%eval (cons f args)))
(defun %eval (e)
(cond
;; begin extensions:
((atom e) (cond ((%boundp e) (definition e))
(t (error "Undefined: ~A" (first e)))))
;; end extensions.
(t (case (first e)
((null) (null (%eval (first (rest e)))))
((atom) (atom (%eval (first (rest e)))))
((quote) (first (rest e)))
((eq) (eq (%eval (first (rest e)))
(%eval (first (rest (rest e))))))
((combine) (cons (%eval (first (rest e)))
(%eval (first (rest (rest e))))))
((first) (first (%eval (first (rest e)))))
((rest) (rest (%eval (first (rest e)))))
((cond) (%evcon (rest e)))
;; begin extensions:
(otherwise
(cond
((atom (first e))
(cond ((%boundp (first e)) (%apply (definition (first e)) (rest e)))
(t (error "Undefined: ~A" (first e)))))
;; end extensions.
(t (case (first (first e))
((lambda) (%evlam (first (rest (first e)))
(first (rest (rest (first e))))
(rest e)))
((label) (%eval (cons (%subst (first e)
(first (rest (first e)))
(first (rest (rest (first e)))))
(rest e))))
(otherwise (error "Invalid: ~A" (first e)))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define nil ())
(define f ())
(define t t)
(define and (lambda (a b) (cond (a (cond (b t) (t nil))) (t nil))))
(define or (lambda (a b) (cond (a t) (b t) (t nil))))
(define not (lambda (a) (cond (a nil) (t t))))
(define maplist
(lambda (x f)
(cond ((null x) nil)
(t (combine (f x) (maplist (rest x) f))))))
(define subst
(lambda (x y a)
(cond ((null a) nil)
((atom a) (cond ((eq y a) x) (t a)))
(t (combine (subst x y (first a))
(subst x y (rest a))))
)))
(define cons (function cons))
(define car (function car))
(define cdr (function cdr))
(define null (function null))
(define load (function load))
(define print (function print))
(define prin1 (function prin1))
(define terpri (function terpri))
(define read (function read))
(defun help ()
(format t "~&You've got:
LAMBDA LABEL
COND AND OR NOT COMBINE FIRST REST
NULL ATOM EQ NIL T QUOTE
Extensions:
DEFINE RELOAD DUMP-ENVIRONMENT LOAD
QUIT"))
(defmacro handling-errors (&body body)
`(handler-case (progn ,@body)
(simple-condition
(err)
(format *error-output* "~&~A: ~%" (class-name (class-of err)))
(apply (function format) *error-output*
(simple-condition-format-control err)
(simple-condition-format-arguments err))
(format *error-output* "~&"))
(condition
(err)
(format *error-output* "~&~A: ~% ~S~%" (class-name (class-of err)) err))))
(defun repl ()
(let ((*package* (find-package "MINLISP")))
(help)
(loop
(terpri)
(princ "MINLISP> ")
(handling-errors
(let ((sexp (read)))
(cond
((equal sexp '(quit))
(format t "GOOD BYE") (return-from repl))
((equal sexp '(reload))
(load "minlisp") (repl) (return-from repl))
((equal sexp '(dump-environment))
(format t "~:{~16@A = ~A~%~}"
(let ((res '()))
(maphash (lambda (k v) (push (list k v) res))
*environment*) res)))
((and (listp sexp) (eq (first sexp) 'define))
(fdefine (second sexp) (third sexp))
(format t "~A" (second sexp)))
(t
(format t "~S" (%eval sexp))))))))
(terpri)
(values))
(defpackage "MINLISP-USER"
(:use)
(:import-from "MINLISP"
"DEFINE" "LAMBDA" "LABEL"
"COND" "COMBINE" "FIRST" "REST"
"NULL" "ATOM" "EQ" "NIL" "T" "QUOTE"
;; extensions:
"AND" "OR" "NOT" "MAPLIST" "SUBST"
"LOAD" "PRINT" "PRIN1" "TERPRI" "READ"
"CONS" "CAR" "CDR" "NULL"))
;;;; THE END ;;;;
| 7,786 | Common Lisp | .lisp | 190 | 33.368421 | 83 | 0.508716 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | ca98a7f38759d1da2bc671f1148e8040dad4cab4cc759240070f426b57d2f579 | 4,846 | [
-1
] |
4,847 | init.lisp | informatimago_lisp/small-cl-pgms/init.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: init.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Compile the com.informatimago.common-lisp libraries with ASDF.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-11-01 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package :cl-user)
(defvar *asdf-source*
#p"/data/lisp/packages/net/common-lisp/projects/asdf/asdf/asdf.lisp")
(defvar *asdf-binary-locations-directory*
#p"/data/lisp/packages/net/common-lisp/projects/asdf-binary-locations/asdf-binary-locations/")
;;;----------------------------------------------------------------------
;;;
;;; Directories.
;;;
(defvar *directories* '())
(defun list-directories ()
"Returns the list of named directories."
(copy-seq *directories*))
(defun get-directory (key &optional (subpath ""))
"
Caches the ~/directories.txt file that contains a map of
directory keys to pathnames, into *DIRECTORIES*.
Then builds and returns a pathname made by merging the directory
selected by KEY, and the given SUBPATH.
"
(unless *directories*
(with-open-file (dirs (merge-pathnames
(make-pathname :name "DIRECTORIES" :type "TXT"
:version nil :case :common)
(user-homedir-pathname)
nil))
(loop
:for k = (read dirs nil dirs)
:until (eq k dirs)
:do (push (string-trim " " (read-line dirs)) *directories*)
:do (push (intern (substitute #\- #\_ (string k))
"KEYWORD") *directories*))))
(unless (getf *directories* key)
(error "~S: No directory keyed ~S" 'get-directory key))
(merge-pathnames subpath (getf *directories* key) nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ASDF
;;;
(unless (find-package :asdf)
(handler-case (require :asdf)
(error () (load (compile-file *asdf-source*)))))
(defun push-asdf-repository (path)
(pushnew path asdf:*central-registry* :test #'equal))
(defun asdf-load (&rest systems)
(mapcar (lambda (system) (asdf:operate 'asdf:load-op system))
systems))
(defun asdf-delete-system (&rest systems)
(mapc (lambda (system) (remhash (string-downcase system) asdf::*defined-systems*))
systems)
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ASDF-BINARY-LOCATIONS
;;;
(defun hostname ()
(let ((outpath (format nil "/tmp/hostname-~8,'0X.txt" (random #x100000000))))
(asdf:run-shell-command
"( hostname --fqdn 2>/dev/null || hostname --long 2>/dev/null || hostname ) > ~A"
outpath)
(prog1 (with-open-file (hostname outpath)
(read-line hostname))
(delete-file outpath))))
(let ((sym (find-symbol "ENABLE-ASDF-BINARY-LOCATIONS-COMPATIBILITY" "ASDF")))
(when (and sym (fboundp sym))
(push :has-asdf-enable-asdf-binary-locations-compatibility *features*)))
#+has-asdf-enable-asdf-binary-locations-compatibility
(progn
;; (format *trace-output* "enable-asdf-binary-locations-compatibility ~%")
(asdf:enable-asdf-binary-locations-compatibility
:centralize-lisp-binaries t
:default-toplevel-directory (merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname))
(truename (user-homedir-pathname)) nil)
:include-per-user-information nil
:map-all-source-files t
:source-to-target-mappings nil))
;; We need (truename (user-homedir-pathname)) because in cmucl (user-homedir-pathname)
;; is a search path, and that cannot be merged...
#-has-asdf-enable-asdf-binary-locations-compatibility
(progn
(push-asdf-repository *asdf-binary-locations-directory*)
(asdf-load :asdf-binary-locations))
#-has-asdf-enable-asdf-binary-locations-compatibility
(progn
(format *trace-output* "enable-asdf-binary-locations-compatibility ~%")
(setf asdf:*centralize-lisp-binaries* t
asdf:*include-per-user-information* nil
asdf:*default-toplevel-directory*
(merge-pathnames (format nil ".cache/common-lisp/~A/" (hostname))
(truename (user-homedir-pathname)) nil)
asdf:*source-to-target-mappings* '()))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Compiling com.informatimago.common-lisp
;;;
(setf asdf:*central-registry*
(append (remove-duplicates
(mapcar (lambda (path)
(make-pathname :name nil :type nil :version nil :defaults path))
(directory (get-directory :share-lisp "packages/com/informatimago/common-lisp/**/*.asd")))
:test (function equalp))
asdf:*central-registry*))
;; (print asdf:*central-registry*) (finish-output)
(asdf-load :com.informatimago.common-lisp.cesarum)
(asdf-load :com.informatimago.common-lisp.html-generator)
;;;; THE END ;;;;
| 6,015 | Common Lisp | .lisp | 141 | 37.737589 | 114 | 0.618885 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f9de7fc5fb959e8f8f3dd6a91a1af430032b2397f4229c8c6af2c4210f8232bd | 4,847 | [
-1
] |
4,848 | what-do-you-want.lisp | informatimago_lisp/small-cl-pgms/what-do-you-want/what-do-you-want.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: what-do-you-want.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Collects wishes.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-07-11 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal Bourguignon 2012 - 2012
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(ql:quickload "com.informatimago.common-lisp.cesarum")
(ql:quickload "com.informatimago.common-lisp.html-generator")
(ql:quickload "split-sequence")
(ql:quickload "hunchentoot")
(in-package "CL-USER")
(defpackage "COM.INFORMATIMAGO.WHAT-DO-YOU-WANT"
(:nicknames "WDYW")
(:use "COMMON-LISP"
"SPLIT-SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY")
(:export
"*APPLICATION-NAME*" ; application name
"*EMAIL*" ; email
"*SWANK-SERVER-PORT*" ; port for remote swank
"*HOME-URI*" ; url of the home website
"*COMMON-RESOURCES-URI*" ; common resources url
"*APPLICATION-RESOURCES-URI*" ; application base url
;; "*APPLICATION-BASE-URI*" ; application base url
"*APPLICATION-FILE-BASE*" ; base directory for application files.
"START-SERVER" ; starts the application server
"STOP-SERVER" ; stops the application server
)
(:shadowing-import-from "COM.INFORMATIMAGO.COMMON-LISP.HTML-GENERATOR.HTML" "MAP")
(:documentation "
Ask the user what they want, and for what price.
"))
(in-package "COM.INFORMATIMAGO.WHAT-DO-YOU-WANT")
(defvar *application-name* "What do you want")
(defvar *application-port* 8008)
(defvar *swank-server-port* 9008)
(defvar *email* "[email protected]")
(defvar *home-uri* "http://want.ogamita.org/"
"URL of the main web site.")
(defvar *common-resources-uri* "http://want.ogamita.org/"
"URL where the common (static) resources are to be found.
Final / is mandatory.")
(defvar *application-resources-uri* "http://want.ogamita.org:8005/"
"URL where the application specific (static) resources are to be found.
Final / is mandatory.")
(defvar *application-file-base* #P"/srv/www/org.ogamita.want/"
"Base directory for application files.")
(defparameter *utf-8*
(flex:make-external-format :utf-8 :eol-style :lf)
"The UTF-8 encoding.")
(defparameter *spaces*
#(#\space #\tab #\newline #\linefeed #\return #\formfeed)
"A bag of spaces.")
(defun common-resources-uri (path)
(format nil "~A~A" *common-resources-uri* path))
(defun application-resources-uri (path)
(format nil "~A~A" *application-resources-uri* path))
(defun in-etc (path)
(merge-pathnames path
(merge-pathnames "etc/" *application-file-base* nil)
nil))
(defun in-log (path)
(merge-pathnames path
(merge-pathnames "log/" *application-file-base* nil)
nil))
(defun in-incoming (path)
(merge-pathnames path
(merge-pathnames "incoming/" *application-file-base* nil)
nil))
(defun in-document-root (path)
(merge-pathnames path
(merge-pathnames "htdocs/" *application-file-base* nil)
nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun format-size (size)
(cond
((< size 1024)
(format nil "~D octet~:*~P" size))
((< size #.(* 1024 1024))
(format nil "~D Ko" (round size 1024)))
((< size #.(* 1024 1024 1024))
(format nil "~D Mo" (round size #.(* 1024 1024))))
((< size #.(* 1024 1024 1024 1024))
(format nil "~D Go" (round size #.(* 1024 1024 1024))))
(t
(format nil "~D To" (round size #.(* 1024 1024 1024 1024))))))
(defun format-date (universal-time)
(multiple-value-bind (se mi ho da mo ye)
(decode-universal-time universal-time)
(format nil "~2,'0D/~2,'0D/~4,'0D ~2,'0D:~2,'0D:~2,'0D"
da mo ye ho mi se)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;;
(defmacro with-app-page ((&key (title *application-name*)
logo-url logo-alt
head) &body body)
(WITH-GENSYMS (vlogo-url vlogo-alt)
`(with-output-to-string (*html-output-stream*)
(setf (hunchentoot:content-type*) "text/html")
(let ((,vlogo-url ,logo-url)
(,vlogo-alt ,logo-alt))
(with-html-output (*html-output-stream* :encoding "UTF-8" :kind :html)
(doctype
:loose
(html ()
(head ()
(title () (pcdata "~A" ,title))
(meta (:http-equiv "Content-Type"
:content "text/html; charset=utf-8"))
(link (:rel "stylesheet"
:href (common-resources-uri "css/screen.css")
:media "screen, projection"
:rel "stylesheet"
:type "text/css"))
,@head)
(body (:class "what-do-you-want")
(div (:id "wrap")
;; (div (:id "header")
;; (table (:class "header")
;; (tr ()
;; (td (:class "logo")
;; (a (:class "logo" :href *home-uri*)
;; (img (:class "logo"
;; :src (common-resources-uri "images/logo-white.png")
;; :alt "Ogamita"))))
;; (if ,vlogo-url
;; (td (:class "logo-client")
;; (img (:class "logo-client" :src ,vlogo-url ,@(when vlogo-alt `(:alt ,vlogo-alt)))))
;; (td (:class "title")
;; (h1 (:class "title") (pcdata "~A" ,title)))))))
(div (:id "content-wrap")
(div (:id "content")
,@body))
(div (:id "footer")
(hr)
(small ()
(a (:href (format nil "mailto:~A" *email*) )
(pcdata "~A" *email*))
(br)
(p ()
(pcdata "This service is licensed under the ")
(a (:href "http://www.gnu.org/licenses/agpl-3.0.html")
(pcdata "GNU Affero General Public License"))
(pcdata ". As such, you can ")
(a (:href "what-do-you-want.lisp")
(pcdata "get the sources."))))))))))))))
(defmacro reporting-errors (&body body)
`(handler-bind
((error (lambda (err)
(with-app-page (:title "Error")
(hunchentoot:log-message* :error "Got an error: ~A" err)
#+sbcl (dolist (frame (SB-DEBUG:BACKTRACE-AS-LIST))
(hunchentoot:log-message* :error "Backtrace: ~S" frame))
#+swank (hunchentoot:log-message* :error "Backtrace: ~S" (swank:backtrace 0 nil))
(pcdata "Got an error: ~A" err)
#+sbcl (table ()
(dolist (frame (SB-DEBUG:BACKTRACE-AS-LIST))
(tr () (td () (code () (pcdata "~S" frame))))))
#+swank (pre () (pcdata "~S" (swank:backtrace 0 nil)))))))
(progn ,@body)))
(defun make-form (enctype action form-key-and-values other-key-and-values body)
`(form (:action ,action
:method "POST"
:accept-charset :utf-8
:enctype ,enctype
,@form-key-and-values)
,@(loop
:for (key value) :on other-key-and-values :by (function cddr)
:collect `(input (:type "hidden"
:name ,(string-downcase key)
:value ,value)))
,@body))
(defmacro insert-form ((action (&rest form-key-and-values &key &allow-other-keys)
&rest other-key-and-values &key &allow-other-keys)
&body body)
(make-form "application/x-www-form-urlencoded"
action
form-key-and-values
other-key-and-values
body))
(defmacro insert-file-form ((action (&rest form-key-and-values &key &allow-other-keys)
&rest other-key-and-values &key &allow-other-keys)
&body body)
(make-form "multipart/form-data"
action
(list* :id "upload" :name "upload" form-key-and-values)
other-key-and-values
body))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun what-do-you-want-form ()
(insert-form
("i-want" ())
(p () (pcdata "What do you want?"))
(textarea (:name "what-you-want"
:rows "10"
:cols "60"))
(p () (pcdata "How much would you pay for it? ")
(input (:type "text" :size "20" :name "how-much")))
(input (:type "submit" :value "I want it!"))
(br) (br)))
(hunchentoot:define-easy-handler (what-do-you-want :uri "") ()
(with-app-page (:title "What do you want?")
(what-do-you-want-form)))
(hunchentoot:define-easy-handler (what-do-you-want :uri "/what-do-you-want") ()
(with-app-page (:title "What do you want?")
(what-do-you-want-form)))
(hunchentoot:define-easy-handler (i-want :uri "/i-want") (what-you-want how-much)
(with-app-page (:title "What do you want?")
(hunchentoot:log-message* :info "~S ~S ~S"
(hunchentoot:real-remote-addr)
how-much
what-you-want)
(p () (pcdata "Thank you. We'll see what we can do."))
(hr)
(p () (pcdata "If you want something else:"))
(what-do-you-want-form)))
(defun create-dispatcher (script-name page-function)
"Creates a dispatch function which will dispatch to the
function denoted by PAGE-FUNCTION if the file name of the current
request is PATH."
(lambda (request)
(hunchentoot:log-message* :info "~S" (hunchentoot:script-name request))
(and (string= (hunchentoot:script-name request) script-name)
page-function)))
(defvar *server* nil)
(defun start-server ()
(setf hunchentoot:*hunchentoot-default-external-format* *utf-8*
hunchentoot:*default-content-type* "text/html; charset=UTF-8")
(setf *server* (make-instance 'hunchentoot:easy-acceptor :port *application-port*))
(setf hunchentoot:*dispatch-table*
(list (create-dispatcher "/" 'what-do-you-want)
(hunchentoot:create-static-file-dispatcher-and-handler
"/what-do-you-want.lisp"
(in-document-root "what-do-you-want.lisp")
"text/plain")
(hunchentoot:create-folder-dispatcher-and-handler
"/css/"
(in-document-root "css/"))
'hunchentoot:dispatch-easy-handlers))
(setf (hunchentoot:acceptor-access-log-destination *server*)
(in-log "what-do-you-want.access_log")
(hunchentoot:acceptor-message-log-destination *server*)
(in-log "what-do-you-want.log"))
(hunchentoot:start *server*))
(defun stop-server ()
(hunchentoot:stop *server*)
(setf *server* nil))
;;;; THE END ;;;;
| 13,208 | Common Lisp | .lisp | 277 | 36.357401 | 138 | 0.503533 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | dc9d5dcf001824ae5c60b0bee0612f2e587642f50d3759daced737cdefb2e2df | 4,848 | [
-1
] |
4,849 | aim-8.lisp | informatimago_lisp/small-cl-pgms/aim-8/aim-8.lisp | ;;;;****************************************************************************
;;;;FILE: aim-8.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements the LISP described in AIM-8 in Common-Lisp.
;;;; Usage: (load "aim-8.lisp")
;;;; (aim-8:repl)
;;;; Then at the aim-8 prompt, you have LISP, plus:
;;;; (DEFINE name sexp) corresponding to =
;;;; (RELOAD) to reload aim-8 if you edit it.
;;;; (DUMP-ENVIRONMENT) to dump the defined symbols.
;;;; (LOAD "path") to load an aim-8 source. Try "aim-8.aim-8".
;;;;
;;;; AIM-8 -- 4 MARCH 1959 -- J. MCCARTHY
;;;; With an addendum dated 23 MARCH 1959
;;;; ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-008.pdf
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-10-24 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "AIM-8"
(:use "COMMON-LISP")
(:export "REPL")
(:documentation
"Implements the lisp of AIM-8 -- 4 MARCH 1959 -- J. MCCARTHY
With an addendum dated 23 MARCH 1959
ftp://publications.ai.mit.edu/ai-publications/pdf/AIM-008.pdf"))
(in-package "AIM-8")
(defparameter *environment* (make-hash-table :test (function eq)))
(defmacro def (name) `(gethash ,name *environment*))
(defun %boundp (name) (multiple-value-bind (val bnd) (def name)
(declare (ignore val)) bnd))
(defmacro define (name value) `(setf (gethash ',name *environment*) ',value))
(defun fdefine (name value) (setf (gethash name *environment*) value))
(define nil ())
(define f ())
(define t t)
(define and (lambda (a b) (cond (a (cond (b t) (t nil))) (t nil))))
(define or (lambda (a b) (cond (a t) (b t) (t nil))))
(define not (lambda (a) (cond (a nil) (t t))))
(define maplist
(lambda (x f)
(cond ((null x) nil)
(t (combine (f x) (maplist (rest x) f))))))
(define subst
(lambda (x y a)
(cond ((null a) nil)
((atom a) (cond ((eq y a) x) (t a)))
(t (combine (subst x y (first a))
(subst x y (rest a))))
)))
(defun %subst (x y a)
(cond ((null a) nil)
((atom a) (cond ((eq y a) x) (t a)))
(t (cons (%subst x y (first a)) (%subst x y (rest a))))))
(defun %subsq (x y z)
(cond ((null z) nil)
((atom z) (cond ((eq y z) x) (t z)))
((eq (first z) 'quote) z)
(t (cons (%subsq x y (first z)) (%subsq x y (rest z))))))
(defun %evcon (c)
(cond ((%eval (first (first c))) (%eval (first (rest (first c)))))
(t (%evcon (rest c)))))
(defun %evlam (vars exp args)
(cond ((null vars) (%eval exp))
(t (%evlam (rest vars) (%subsq (first args) (first vars) exp)
(rest args)))))
(defun %apply (f args) (%eval (cons f args)))
(defun %eval (e)
(cond
;; begin extensions:
((atom e) (cond ((%boundp e) (def e))
(t (error "Undefined: ~A" (first e)))))
;; end extensions.
(t (case (first e)
((null) (null (%eval (first (rest e)))))
((atom) (atom (%eval (first (rest e)))))
((quote) (first (rest e)))
((eq) (eq (%eval (first (rest e)))
(%eval (first (rest (rest e))))))
((combine) (cons (%eval (first (rest e)))
(%eval (first (rest (rest e))))))
((first) (first (%eval (first (rest e)))))
((rest) (rest (%eval (first (rest e)))))
((cond) (%evcon (rest e)))
;; begin extensions:
((load) (load (%eval (first (rest e)))))
((print) (print (%eval (first (rest e)))))
((read) (read))
(otherwise
(cond
((atom (first e))
(cond ((%boundp (first e)) (%apply (def (first e)) (rest e)))
(t (error "Undefined: ~A" (first e)))))
;; end extensions.
(t (case (first (first e))
((lambda) (%evlam (first (rest (first e)))
(first (rest (rest (first e))))
(rest e)))
((label) (%eval (cons (%subst (first e)
(first (rest (first e)))
(first (rest (rest (first e)))))
(rest e))))
(otherwise (error "Invalid: ~A" (first e)))))))))))
(defun help ()
(format t "~&You've got:
LAMBDA LABEL
COND AND OR NOT COMBINE FIRST REST
NULL ATOM EQ NIL T QUOTE
Extensions:
DEFINE RELOAD DUMP-ENVIRONMENT LOAD
QUIT"))
(defmacro handling-errors (&body body)
`(handler-case (progn ,@body)
(simple-condition
(err)
(format *error-output* "~&~A: ~%" (class-name (class-of err)))
(apply (function format) *error-output*
(simple-condition-format-control err)
(simple-condition-format-arguments err))
(format *error-output* "~&"))
(condition
(err)
(format *error-output* "~&~A: ~% ~A~%" (class-name (class-of err)) err))))
(defun repl ()
(let ((*package* (find-package "AIM-8")))
(help)
(loop
(terpri)
(princ "AIM-8> ")
(handling-errors
(let ((sexp (read)))
(cond
((equal sexp '(quit))
(format t "GOOD BYE") (return-from repl))
((equal sexp '(reload))
(load "aim-8") (repl) (return-from repl))
((equal sexp '(dump-environment))
(format t "~:{~16@A = ~A~%~}"
(let ((res '()))
(maphash (lambda (k v) (push (list k v) res))
*environment*) res)))
((and (listp sexp) (eq (first sexp) 'define))
(fdefine (second sexp) (third sexp))
(format t "~A" (second sexp)))
(t
(format t "~S" (%eval sexp))))))))
(terpri)
(values))
(defpackage "AIM-8-USER"
(:use)
(:import-from "AIM-8"
"DEFINE" "LAMBDA" "LABEL"
"COND" "COMBINE" "FIRST" "REST"
"NULL" "ATOM" "EQ" "NIL" "T" "QUOTE"))
;;;; aim-8.lisp -- -- ;;;;
| 7,419 | Common Lisp | .lisp | 181 | 33.254144 | 83 | 0.498822 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d64874cdfb87a4e42764037fe81a3f3f1ac4e825dad11c58f60981e640349b70 | 4,849 | [
-1
] |
4,850 | intersection-cl-el-r5rs.lisp | informatimago_lisp/small-cl-pgms/intersection-r5rs-common-lisp-emacs-lisp/intersection-cl-el-r5rs.lisp | ;;;; -*- mode:scheme:mode:paredit; coding:us-ascii -*-
;;;;**************************************************************************
;;;;FILE: happy.lisp
;;;;LANGUAGES: scheme, emacs lisp, Common Lisp
;;;;SYSTEM: POSIX
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This file demonstrates how one can write a lisp program that can run
;;;; on both scheme, emacs lisp and Common Lisp.
;;;;
;;;; Since emacs lisp is close to Common Lisp, we (require 'cl),
;;;; and implement in scheme the CL primitives we need.
;;;;
;;;; It can be run for example with:
;;;;
;;;; mzscheme -f happy.lisp
;;;; emacs -Q --batch -l happy.lisp -q
;;;; clisp -q -norc -ansi happy.lisp
;;;;
;;;;
;;;; Note: this has been tested with emacs-23, not emacs-24, which
;;;; provides lexical closures, and therefore should be
;;;; closer to Common Lisp, but which would require some
;;;; changes to this program.
;;;;
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2011-05-27 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2011 - 2021
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
;; mzscheme -f happy.lisp ; emacs -Q --batch -l happy.lisp -q ; clisp -q -norc -ansi happy.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; BOOTSTRAP SECTION
;;;
;;;
((lambda (funcall
;; The funcall trick is that in Lisp-2, the parameter is not used,
schemify
;; The schemify function will define some scheme primitive
;; in emacs-lisp and Common Lisp to help us bootstrap in
;; the following forms.
scheme common-lisp emacs-lisp
;; We select one of these three thunks depending on the language
;; evaluating this.
;; but instead the native function.
)
(if '()
(funcall scheme)
;; This may fail with lexical-binding t in newer emacs-lisp:
;; (let ((language emacs-lisp))
;; (funcall (let ((language common-lisp)) (lambda () (funcall language schemify)))))
;; Then instead we may use:
(funcall (let ((a (cons 1 1))
(b (cons 2 2)))
(if (eq a (rplaca a b))
common-lisp
emacs-lisp))
schemify)))
(lambda (f) ; funcall for scheme
(f))
(lambda () ; schemify
;; In Common Lisp or Emacs Lisp, we define some scheme
;; primitives, to be able to bootstrap as on scheme.
;; The problem is that we cannot use eval in scheme
;; for lack of an environment
;; (interaction-environment is optional and absent
;; on eg. mzscheme), so we need to write the rest of
;; the file in scheme syntax.
;; Perhaps it would be better to write two different schemify for
;; emacs-lisp and Common-Lisp...
(eval
;; Testing (boundp 'emacs-version) is dubbious too
;; (such a variable could be defined in Common-Lisp).
;; instead, let's test rplaca:
(let ((clp (let ((a (cons 1 1))
(b (cons 2 2)))
(eq a (rplaca a b)))))
(list 'progn
(if clp
;; common-lisp:
'(progn
(defmacro eval-in-emacs-lisp (&body expressions)
'nil)
(defmacro eval-in-common-lisp (&body expressions)
(list* 'progn expressions))
(defmacro eval-in-scheme (&body expressions)
'nil))
;; emacs-lisp:
'(progn
(defmacro define-symbol-macro (name expansion)
(list 'defvar name expansion))
(defmacro eval-in-emacs-lisp (&rest expressions)
(list* 'progn expressions))
(defmacro eval-in-common-lisp (&rest expressions)
'nil)
(defmacro eval-in-scheme (&rest expressions)
'nil)))
(list 'defmacro (intern (if clp "BEGIN" "begin"))
'(&body body) '(list* 'progn body))
(if (boundp 'emacs-version)
'(defmacro define-lexical-global (variable expression)
(list 'defvar variable expression))
'(defmacro define-lexical-global (variable expression)
(let ((global (gensym (symbol-name variable))))
(list 'progn
(list 'define-symbol-macro variable
(list 'symbol-value (list 'quote global)))
(list 'setf variable expression)
(list 'quote variable)))))
(list 'defmacro (intern (if clp "DEFINE" "define"))
'(variable expression)
'(list 'progn
(list 'define-lexical-global variable expression)
(list 'defun variable '(&rest arguments)
(list 'apply variable 'arguments))))
(list (if (boundp 'emacs-version)
'defmacro*
'defmacro)
(intern (if clp "DEFINE-SYNTAX" "define-syntax"))
'(name (syntax-rules vars &rest rules))
;; '(declare (ignore syntax-rule vars rules))
;; We don't do anything, this is only used in
;; scheme to make CL like macros.
'(list 'quote name))))))
(lambda () ; scheme thunk
'scheme)
(lambda (schemify) ; common-lisp thunk
(funcall schemify)
'common-lisp)
(lambda (schemify) ; emacs-lisp thunk
(eval '(require 'cl))
(funcall schemify)
'emacs-lisp))
;; We define a language variable bound to a symbol naming the language.
(define language ((lambda ()
(if '()
'scheme
(if (let ((a (cons 1 1))
(b (cons 2 2)))
(eq a (rplaca a b)))
'common-lisp
'emacs-lisp)))))
(case language
((common-lisp)
;; We define this reader macro to neutralize read-error on "(expr ...)"
;; Notice this form is read and parsed by scheme. Therefore no LOOP.
(define-condition simple-reader-error (simple-error reader-error)
(dummy))
(defun reader-macro-scheme-list (stream ch)
"Left parenthesis macro reader that accepts ... in lists, and read |...| for them."
(declare (ignore ch))
(flet ((serror (condition stream control-string &rest arguments)
;; Keywords are not necessarily accepted by all scheme readers,
;; and this must be read by a lisp reader (and even parsed).
(error condition
:stream stream
:format-control control-string
:format-arguments arguments)))
(let* ((result (cons nil nil))
(last-cons result)
(last-cdr-p nil))
(do ((ch (progn (peek-char t stream nil t)
(read-char stream t nil t))
(progn (peek-char t stream nil t)
(read-char stream t nil t))))
((char= (character ")") ch)
(if (eq last-cdr-p 't)
(serror 'simple-reader-error stream
"illegal end of dotted list")
(cdr result)))
(labels ((collect (objects)
(assert (listp objects))
(when objects
(case last-cdr-p
((nil)
(setf (cdr last-cons) objects
;; (list (first objects))
last-cons (cdr last-cons)))
((t)
(setf (cdr last-cons) (first objects)
last-cdr-p 'done))
((done)
(serror 'simple-reader-error stream
"illegal end of dotted list"))))))
(cond
((char= (character ";") ch)
;; temporary kludge, we reset the readtable when done with scheme.
(read-line stream))
((char= (character ".") ch)
(let ((nextch (peek-char nil stream t nil t)))
(cond
((char= (character ".") nextch)
;; We got two dots, let's assume it'll only be dots,
;; and collect a symbol.
(collect (list (do ((res (list ch) (cons ch res)))
((char/= ch (peek-char nil stream t nil t))
(intern (coerce res 'string)))
(read-char stream nil nil t)))))
((or (find nextch " ()\";#")
(char= nextch (code-char 13))
(char= nextch (code-char 10)))
(if (eql result last-cons)
(serror 'simple-reader-error stream
"missing an object before the \".\" in a cons cell")
(case last-cdr-p
((nil)
(setf last-cdr-p t))
((t)
(serror 'simple-reader-error stream
"token \".\" not allowed here"))
((done)
(serror 'simple-reader-error stream
"illegal end of dotted list")))))
(t
(collect (list
(with-input-from-string (dot ".")
(read (make-concatenated-stream dot stream) t nil t))))))))
(t
(unread-char ch stream)
(collect (list (read stream t nil t))))))))))
(set-macro-character (character "(")
(lambda (stream ch)
;; This stub is so that when we redefine
;; the reader while debugging, the new
;; version be taken into account immediately.
(reader-macro-scheme-list stream ch)))
;; (set-syntax-from-char (character ".") (character "A"))
;; (defvar *normal-readtable* (copy-readtable))
;; (set-macro-character
;; (character ".")
;; (lambda (stream ch)
;; (print (list 'dot-reader stream))
;; ;; Keywords are not necessarily accepted by scheme readers,
;; ;; but life would be difficult without them.
;; (if (char= ch (peek-char nil stream))
;; (values
;; ;; We got two dots, let's assume it'll only be dots,
;; ;; and return a symbol.
;; (do ((res (list ch) (cons ch res)))
;; ((char/= ch (peek-char nil stream))
;; (intern (coerce res 'string)))
;; (read-char stream nil)))
;; (let ((*readtable* *normal-readtable*))
;; ;; We got only one dot, let's assume it's a normal token,
;; ;; and let the normal reader handle it.
;; (with-input-from-string (dot ".")
;; (read (make-concatenated-stream dot stream) t nil t))))))
))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; UPGRADING SCHEME TO COMMON-LISP
;;;
;;;
;; Notice that the form in eval-in-* must still be read in all three
;; languages.
(define-syntax eval-in-scheme
(syntax-rules ()
((eval-in-scheme expr)
expr)
((eval-in-scheme expr ...)
(begin expr ...))))
(define-syntax eval-in-emacs-lisp
(syntax-rules ()
((eval-in-emacs-lisp expr ...)
'nil)))
(define-syntax eval-in-common-lisp
(syntax-rules ()
((eval-in-common-lisp expr ...)
'nil)))
;; Remember, define-syntax is defined by schemify above in emacs-lisp
;; and Common-Lisp to do nothing.
(define-syntax defun
(syntax-rules ()
((defun name parameters body ...)
(define name (lambda parameters body ...)))))
(define-syntax defparameter
(syntax-rules ()
((defparameter name value)
(define name value))))
(define-syntax define-lexical-global
(syntax-rules ()
((define-lexical-global name value)
(define name value))
((define-lexical-global name value docstring)
(define name value))))
(define-syntax defconstant
(syntax-rules ()
((defconstant name value)
(define name value))
((defconstant name value docstring)
(define name value))))
(eval-in-scheme
;; We don't have &rest yet, so we use a dotted parameter list:
(define funcall (lambda (function . arguments) (apply function arguments)))
(defun function (name) name)
(defun identity (object) object)
(defun eql (a b) (eqv? a b)) ;; TODO: implement it correctly.
(defun equal (a b) (equal? a b)) ;; TODO: implement it correctly.
(defconstant nil '()) ; nil is false.
(defun null (x) (eql nil x))
(defconstant t 't)
(defun .boolean (generalized-boolean)
"Transforms the GENERALIZED-BOOLEAN into a native boolean value.
false is the symbol nil, the empty list, and not true (#f)."
(not (or (not (eql 'nil generalized-boolean))
(not (eql '() generalized-boolean))
(not generalized-boolean)))))
(define-syntax setq
(syntax-rules ()
((setq var expr)
(set! var expr))
((setq var expr other ...)
(begin (set! var expr)
(setq other ...)))))
(define-syntax setf ; for now, only variables and a few built-ins
(syntax-rules ()
((setf (car place) expr)
(set-car! place expr))
((setf (cdr place) expr)
(set-cdr! place expr))
((setf (aref place index) expr)
(vector-set! place index expr))
;; ...
((setf var expr)
(set! var expr))
((setf var expr other ...)
(begin (set! var expr)
(setf other ...)))))
(eval-in-scheme
(defun aref (vos index)
(if (vector? vos)
(vector-ref vos index)
(string-ref vos index)))
(defun nth (index list)
(let loop ((list list)
(index index))
(cond
((null list) list)
((= 0 index) (car list))
(else (loop (- index 1) (cdr list))))))
(defun elt (seq index)
(cond
((vector? seq) (vector-ref seq index))
((string? seq) (string-ref seq index))
((list? seq) (nth index seq))))
(define terpri
(lambda optional-parameter
(apply newline optional-parameter)))
(define print
(lambda parameters
(if (null (cdr parameters))
(newline)
(newline (cadr parameters)))
(apply write parameters)))
)
;;; We don't need to read ... anymore, so we revert to the standard
;;; readtable in CL:
(eval-in-common-lisp
(setf *readtable* (copy-readtable))
(setf *print-case* :downcase))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; A FEW EMACS-LISP ADJUSTMENTS
;;;
;;;
(eval-in-emacs-lisp
(defun print (object &optional printcharfun)
(terpri printcharfun)
(princ (prin1-to-string object) printcharfun)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The language defined so far.
;;;
;; The intersection of r5rs, emacs-lisp and Common Lisp,
;; defined as a Common Lisp package.
(eval-in-common-lisp
(defpackage "INTERSECTION-CL-EL-R5RS"
(:use "COMMON-LISP")
(:export quote lambda if cond case
and or not
let let* do
= < > <= >=
max min
+ * - /
floor ceiling truncate round
rationalize
exp log sin cos tan asin acos atan sqrt expt
gcd lcm
numerator denominator
cons
car cdr
caar cadr cdar cddr
caaar caadr cadar caddr cdaar cdadr cddar cdddr
caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr
cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr
list length append reverse
char-upcase char-downcase
make-string
vector
apply
read read-char peek-char
write write-char
load)
;; we added (with restrictions!):
(:export funcall function identity
defun defconstant
eql equal
nil null t
aref elt nth
setq setf
terpri print)
;; We defined those additionnal symbols:
(:import-from :common-lisp-user
language scheme emacs-lisp common-lisp
define-lexical-global .boolean)
(:export language
scheme emacs-lisp common-lisp ; names of the underlying languages
define-lexical-global ; to be used instead of define or defparameter
.boolean ; to be used to get a native boolean from a value
)
(:documentation "
This package exports the operators from COMMON-LISP that exist also in
R5RS scheme, with the same behavior (for some subset of the parameter
ranges). If we take care of restricting our scheme, then we can write
code that can be evaluated with the same semantics both in scheme and
in Common Lisp.
It may be tried out in the INTERSECTION-CL-EL-R5RS-USER package.
For examples:
COND is CL:COND therefore we cannot use ELSE; instead write a true
conditions, like (= 0 0).
CASE is CL:CASE therefore we cannot use ELSE.
(In scheme, CASE is scheme case, therefore we cannot use OTHERWISE either).
LAMBDA is CL:LAMBDA therefore we cannot use a symbol or a dotted list for
the lambda-list. On the other hand, CL:lambda also accepts
extended parameter lists that scheme programs must refrain from
using.
MAKE-STRING is CL:MAKE-STRING that takes keyword arguments.
Scheme programs must call it with only one argument and cannot
pass an initial element.
IF and COND are CL:IF and CL:COND and take only CL:NIL as
false. Therefore scheme programs must restrict themselves to the
available predicates as test expressions, and must avoid to give
the empty list.
While DEFINE and LETREC are missing, we can write:
(let ((fact (lambda (fact x)
(if (< x 1)
1
(* x (apply fact fact (- x 1) '()))))))
(apply fact fact 20 '()))
--> 2432902008176640000
A few additionnal primitives are defined in scheme, and exported from
this package:
FUNCALL FUNCTION IDENTITY
DEFUN DEFCONSTANT
EQL EQUAL
NIL NULL T
AREF ELT NTH
SETQ SETF
TERPRI PRINT
along with:
DEFINE-LEXICAL-GLOBAL ; to be used instead of define or defparameter
.BOOLEAN ; to be used to get a native boolean from a value
The rest of Common Lisp can be implemented from here.
")))
(eval-in-common-lisp
(defpackage "INTERSECTION-CL-EL-R5RS-USER"
(:use "INTERSECTION-CL-EL-R5RS"))
(in-package "INTERSECTION-CL-EL-R5RS-USER"))
;; Now we can rewrite Common Lisp with INTERSECTION-CL-EL-R5RS ;-)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; APPLICATION SPECIFIC CODE
;;;
;;;
(print (list 'booted 'a 'lisp 'over language))
(defun fact (x)
(if (< x 1)
1
(* x (fact (- x 1)))))
(print (list '(fact 10) '= (fact 10))) ; don't try more, emacs-lisp has only int32...
(terpri)
;; [pjb@kuiper :0 lisp]$ mzscheme -f happy.lisp ; emacs -Q --batch -l happy.lisp -q ; clisp -q -norc -ansi happy.lisp
;;
;; (booted a lisp over scheme)
;; ((fact 10) = 3628800)
;;
;; (booted a lisp over emacs-lisp)
;; ((fact 10) = 3628800)
;;
;; (booted a lisp over common-lisp)
;; ((fact 10) = 3628800)
;; [pjb@kuiper :0 lisp]$
;;;; THE END ;;;;
| 21,602 | Common Lisp | .lisp | 516 | 31.335271 | 118 | 0.525664 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 0317427584d1b92f430df61a7455e7eba81373699a8d5dfed34927db0d8e6654 | 4,850 | [
-1
] |
4,851 | intersection-cl-r5rs.lisp | informatimago_lisp/small-cl-pgms/intersection-r5rs-common-lisp-emacs-lisp/intersection-cl-r5rs.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: intersection-cl-r5rs.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; An intersection of R5RS and Common Lisp.
;;;;
;;;; This is a Common-Lisp program that let one load scheme
;;;; programs using only operators in the intersection with Common
;;;; Lisp.
;;;;
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2009-07-26 <PJB> Created
;;;;BUGS
;;;;LEGAL
;;;; GPL
;;;;
;;;; Copyright Pascal J. Bourguignon 2009 - 2016
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public License
;;;; as published by the Free Software Foundation; either version
;;;; 2 of the License, or (at your option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be
;;;; useful, but WITHOUT ANY WARRANTY; without even the implied
;;;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
;;;; PURPOSE. See the GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public
;;;; License along with this program; if not, write to the Free
;;;; Software Foundation, Inc., 59 Temple Place, Suite 330,
;;;; Boston, MA 02111-1307 USA
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(cl:in-package :cl-user)
(defpackage "INTERSECTION-CL-R5RS"
(:use "COMMON-LISP")
(:export "QUOTE" "LAMBDA" "IF" "COND" "CASE"
"AND" "OR" "NOT"
"LET" "LET*" "DO"
"=" "<" ">" "<=" ">="
"MAX" "MIN"
"+" "*" "-" "/"
"FLOOR" "CEILING" "TRUNCATE" "ROUND"
"RATIONALIZE"
"EXP" "LOG" "SIN" "COS" "TAN" "ASIN" "ACOS" "ATAN" "SQRT" "EXPT"
"GCD" "LCM"
"NUMERATOR" "DENOMINATOR"
"CONS"
"CAR" "CDR"
"CAAR" "CADR" "CDAR" "CDDR"
"CAAAR" "CAADR" "CADAR" "CADDR" "CDAAR" "CDADR" "CDDAR" "CDDDR"
"CAAAAR" "CAAADR" "CAADAR" "CAADDR" "CADAAR" "CADADR" "CADDAR" "CADDDR"
"CDAAAR" "CDAADR" "CDADAR" "CDADDR" "CDDAAR" "CDDADR" "CDDDAR" "CDDDDR"
"LIST" "LENGTH" "APPEND" "REVERSE"
"CHAR-UPCASE" "CHAR-DOWNCASE"
"MAKE-STRING"
"VECTOR"
"APPLY"
"READ" "READ-CHAR" "PEEK-CHAR"
"WRITE" "WRITE-CHAR"
"LOAD")
(:documentation "
This package exports the operators from COMMON-LISP that exist also in
R5RS scheme, with the same behavior (for some subset of the parameter
ranges). If we take care of restricting our scheme, then we can write
code that can be evaluated with the same semantics both in scheme and
in Common Lisp.
It may be tried out in the INTERSECTION-CL-R5RS.USER package.
For examples:
COND is CL:COND therefore we cannot use ELSE; instead write a true
conditions, like (= 0 0).
CASE is CL:CASE therefore we cannot use ELSE.
LAMBDA is CL:LAMBDA therefore we cannot use a symbol or a dotted list for
the lambda-list. On the other hand, CL:lambda also accepts
extended parameter lists that scheme programs must refrain from
using.
MAKE-STRING is CL:MAKE-STRING that takes keyword arguments.
Scheme programs must call it with only one argument and cannot
pass an initial element.
IF and COND are CL:IF and CL:COND and take only CL:NIL as
false. Therefore scheme programs must restrict themselves to the
available predicates as test expressions, and must avoid to give
the empty list.
While DEFINE and LETREC are missing, we can write:
(let ((fact (lambda (fact x)
(if (< x 1)
1
(* x (apply fact fact (- x 1) '()))))))
(apply fact fact 20 '()))
--> 2432902008176640000
Note: are direly missing DEFINE, LETREC, NULL? and other predicates,
See CL-R5RS-LIBRARY for a more complete subset of scheme.
"))
(defpackage "INTERSECTION-CL-R5RS.USER"
(:use "INTERSECTION-CL-R5RS"))
(defpackage "INTERSECTION-CL-R5RS.LIBRARY"
(:use "COMMON-LISP")
(:shadow "IF" "COND" "CASE"
"AND" "OR" "NOT"
"=" "<" ">" "<=" ">="
"MEMBER" "ASSOC" "STRING" "MAKE-STRING" "MAP" "EVAL"
"READ" "READ-CHAR" "PEEK-CHAR"
"WRITE" "WRITE-CHAR")
(:export "QUOTE" "LAMBDA" "IF" "COND" "CASE"
"AND" "OR" "NOT"
"LET" "LET*" "DO"
"=" "<" ">" "<=" ">="
"MAX" "MIN"
"+" "*" "-" "/"
"FLOOR" "CEILING" "TRUNCATE" "ROUND"
"RATIONALIZE"
"EXP" "LOG" "SIN" "COS" "TAN" "ASIN" "ACOS" "ATAN" "SQRT" "EXPT"
"GCD" "LCM"
"NUMERATOR" "DENOMINATOR"
"CONS"
"CAR" "CDR"
"CAAR" "CADR" "CDAR" "CDDR"
"CAAAR" "CAADR" "CADAR" "CADDR" "CDAAR" "CDADR" "CDDAR" "CDDDR"
"CAAAAR" "CAAADR" "CAADAR" "CAADDR" "CADAAR" "CADADR" "CADDAR" "CADDDR"
"CDAAAR" "CDAADR" "CDADAR" "CDADDR" "CDDAAR" "CDDADR" "CDDDAR" "CDDDDR"
"LIST" "LENGTH" "APPEND" "REVERSE"
"CHAR-UPCASE" "CHAR-DOWNCASE"
"MAKE-STRING"
"VECTOR"
"APPLY"
"READ" "READ-CHAR" "PEEK-CHAR"
"WRITE" "WRITE-CHAR"
"LOAD"
"SET!" "ELSE" "LETREC" "BEGIN" "DEFINE"
"EQV?" "EQ?" "EQUAL?"
"INTEGER?" "RATIONAL?" "REAL?" "COMPLEX?" "NUMBER?"
"EXACT?" "INEXACT?"
"ZERO?" "POSITIVE?" "NEGATIVE?" "ODD?" "EVEN?"
"MAKE-RECTANGULAR" "MAKE-POLAR" "REAL-PART" "IMAG-PART" "MAGNITUDE" "ANGLE"
"INEXACT->EXACT" "EXACT->INEXACT"
"STRING->NUMBER" "NUMBER->STRING"
"PAIR?" "SET-CAR!" "SET-CDR!" "LIST-TAIL" "LIST-REF"
"MEMQ" "MEMV" "MEMBER" "ASSQ" "ASSV" "ASSOC"
"SYMBOL?" "SYMBOL->STRING" "STRING->SYMBOL"
"CHAR?"
"CHAR=?" "CHAR<?" "CHAR>?" "CHAR<=?" "CHAR>=?"
"CHAR-CI=?" "CHAR-CI<?" "CHAR-CI>?" "CHAR-CI<=?" "CHAR-CI>=?"
"CHAR-ALPHABETIC?" "CHAR-NUMERIC?" "CHAR-WHITESPACE?"
"CHAR-UPPER-CASE?" "CHAR-LOWER-CASE?" "CHAR->INTEGER" "INTEGER->CHAR"
"CHAR-UPCASE" "CHAR-DOWNCASE"
"STRING?" "STRING" "STRING-LENGTH" "STRING-REF" "STRING-SET!"
"STRING=?" "STRING<?" "STRING>?" "STRING<=?" "STRING>=?"
"STRING-CI=?" "STRING-CI<?" "STRING-CI>?" "STRING-CI<=?" "STRING-CI>=?"
"SUBSTRING" "STRING-APPEND" "STRING->LIST" "LIST->STRING" "STRING-COPY"
"STRING-FILL!"
"VECTOR?" "MAKE-VECTOR" "VECTOR-LENGTH" "VECTOR-REF" "VECTOR-SET!"
"VECTOR->LIST" "LIST->VECTOR" "VECTOR-FILL!"
"PROCEDURE?" "MAP" "FOR-EACH" "DYNAMIC-WIND"
"NULL-ENVIRONMENT" "SCHEME-REPORT-ENVIRONMENT" "INTERACTION-ENVIRONMENT" "EVAL"
"CALL-WITH-INPUT-FILE" "INPUT-PORT?" "CURRENT-INPUT-PORT" "WITH-INPUT-FROM-FILE"
"OPEN-INPUT-FILE" "CLOSE-INPUT-PORT"
"CALL-WITH-OUTPUT-FILE" "OUTPUT-PORT?" "CURRENT-OUTPUT-PORT" "WITH-OUTPUT-FROM-FILE"
"OPEN-OUTPUT-FILE" "CLOSE-OUTPUT-PORT"
"EOF-OBJECT?" "CHAR-READY?"
"DISPLAY" "NEWLINE"
"TRANSCRIPT-ON" "TRANSCRIPT-OFF"
))
(defpackage "INTERSECTION-CL-R5RS.LIBRARY.USER"
(:use "INTERSECTION-CL-R5RS.LIBRARY"))
(cl:in-package "INTERSECTION-CL-R5RS.LIBRARY")
(defstruct false) (defvar +false+ (make-false))
(defstruct true) (defvar +true+ (make-true))
(defstruct eof) (defvar +eof+ (make-eof))
(declaim (inline clbool scbool))
(defun clbool (scheme-boolean) (cl:not (eq +false+ scheme-boolean)))
(defun scbool (lisp-boolean) (cl:if lisp-boolean +true+ +false+))
;; This is not correct, the value of the last expression must be returned, not its clbool:
(defmacro and (&rest arguments)
(cl:cond
((null arguments) '+true+)
((null (cdr arguments)) (car arguments))
(t `(if ,(car arguments) (and ,@(cdr arguments)) +false+))))
(defmacro or (&rest arguments)
(cl:cond
((null arguments) '+false+)
(t (let ((result (gensym)))
`(let ((,result ,(car arguments)))
(if ,result ,result (or ,@(cdr arguments))))))))
(defun not (lisp-boolean) (scbool (eq +false+ lisp-boolean)))
(defmacro set! (variable expression)
`(setq ,variable ,expression))
(defmacro if (test then &optional else)
`(cl:if (clbool ,test) ,then ,else))
(defmacro cond (&rest clauses)
(let* ((temp (gensym))
(temp-used nil)
(form
`(cl:cond
,@(mapcar
(lambda (clause)
(assert (and clause (listp clause)) ()
"COND clauses must be list containing at least a test expression. ~S is invalid.")
(cl:cond
((eq 'else (first clause))
`(t ,@(rest clause)))
((eq '=> (second clause))
(setf temp-used t)
`((clbool (setf ,temp ,(first clause))) (funcall ,(third clause) ,temp)))
(t
`((clbool ,(first clause)) ,@(rest clause)))))
clauses))))
(if temp-used
`(let ((,temp)) ,form)
form)))
(defmacro case (&rest clauses)
`(cl:case
,@(mapcar
(lambda (clause)
(assert (and clause (listp clause)
(or (eq 'else (car clause))
(listp (car clause))))
()
"CASE clauses must be list containing at least a test expression. ~S is invalid.")
(cl:cond
((eq 'else (first clause))
`(t ,@(rest clause)))
(t
clause)))
clauses)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun clparameters (parameters)
(etypecase parameters
(symbol `(&rest ,parameters))
(list (let ((last-cons (last parameters)))
(if (symbolp (cdr last-cons))
(append (butlast parameters) (list (car last-cons) '&rest (cdr last-cons)))
parameters))))))
(defmacro letrec (definitions &body body)
(loop
:for (name value) :in definitions
:if (and (listp value) (eq 'lambda (first value)))
:collect (destructuring-bind (lambda parameters &body body) value
(declare (ignore lambda))
`(,name ,(clparameters parameters) ,@body)) :into funs
:else
:collect `(,name ,value) :into vars
:finally (return `(let ,vars
(labels ,funs
,@body)))))
(defmacro begin (&body body) `(progn ,@body))
(defmacro define-lexical-global (variable expression)
(let ((global (gensym (cl:string variable))))
`(progn
(define-symbol-macro ,variable (symbol-value ',global))
(setf ,variable ,expression)
',variable)))
(defmacro define (variable expression)
(cl:if (cl:and (listp expression) (eq 'lambda (first expression)))
`(progn
(defun ,variable ,@(rest expression))
(define-lexical-global ,variable (function ,variable)))
`(define-lexical-global ,variable ,expression)))
(defun eqv? (a b)
(or (scbool (eql a b))
;; (cl:and (eq a +true+) (eq b +true+))
;; (cl:and (eq a +false+) (eq b +false+))
;; (and (null? a) (null? b))
(and (symbol? a) (symbol? b)
(interned? a) (interned? b)
(string=? (symbol->string a) (symbol->string b)))
(and (number? a) (number? b) (= a b))
(and (char? a) (char? b) (char=? a b))
+false+))
(defun eq? (a b) (eqv? a b))
(defun equal? (a b)
(or (eqv? a b)
(and (pair? a) (pair? b)
(equal? (car a) (car b))
(equal? (cdr a) (cdr b)))
(and (vector? a) (vector? b)
(cl:= (length a) (length b))
(every (lambda (a b) (clbool (equal? a b))) a b))
(and (string? a) (string? b)
(string=? a b))))
(defun integer? (a) (scbool (integerp a)))
(defun rational? (a) (scbool (rationalp a)))
(defun real? (a) (scbool (realp a)))
(defun complex? (a) (scbool (cl:or (realp a) (complexp a))))
(defun number? (a) (scbool (numberp a)))
(defun exact? (a) (scbool (cl:or (rationalp a)
(and (complexp a)
(rationalp (realpart a))
(rationalp (imagpart a))))))
(defun inexat? (a) (not (exact? a)))
(defun = (&rest arguments) (scbool (apply (function cl:=) arguments)))
(defun < (&rest arguments) (scbool (apply (function cl:<) arguments)))
(defun > (&rest arguments) (scbool (apply (function cl:>) arguments)))
(defun <= (&rest arguments) (scbool (apply (function cl:<=) arguments)))
(defun >= (&rest arguments) (scbool (apply (function cl:>=) arguments)))
(defun zero? (a) (scbool (zerop a)))
(defun positive? (a) (scbool (plusp a)))
(defun negative? (a) (scbool (minusp a)))
(defun odd? (a) (scbool (oddp a)))
(defun even? (a) (scbool (evenp a)))
(defun quotient (a b) (values (truncate a b)))
(defun remainder (a b) (rem a b))
(defun modulo (a b) (mod a b))
(defun make-rectangular (a b) (complex a b))
(defun make-polar (r a) (* r (cis a)))
(defun real-part (a) (realpart a))
(defun imag-part (a) (imagpart a))
(defun magnitude (a) (abs a))
(defun angle (a) (phase a))
(defun exact->inexact (a) (+ 0.0 a))
(defun inexact->exact (a) (values (round a)))
(defun number->string (obj &optional (base 10.))
(check-type obj number)
(write-to-string obj
:array nil :base base :case :downcase :circle t
:escape t :gensym t :length nil :level nil :lines nil
:miser-width nil :pretty nil
:radix t :readably t :right-margin nil))
(defun string->number (s &optional (radix 10.))
(let ((*read-eval* nil)
(*read-base* radix)
(*read-suppress* nil))
(let ((result (read-from-string s)))
(check-type result number)
result)))
(defun pair? (a) (scbool (consp a)))
(defun null? (a) (scbool (null a)))
(defun set-car! (pair obj) (setf (car pair) obj))
(defun set-cdr! (pair obj) (setf (cdr pair) obj))
(defun list-tail (list k) (nthcdr k list))
(defun list-ref (list k) (nth k list))
(defun memq (obj list) (cl:member obj list :test (lambda (a b) (clbool (eq? a b)))))
(defun memv (obj list) (cl:member obj list :test (lambda (a b) (clbool (eqv? a b)))))
(defun member (obj list) (cl:member obj list :test (lambda (a b) (clbool (equal? a b)))))
(defun assq (obj list) (cl:assoc obj list :test (lambda (a b) (clbool (eq? a b)))))
(defun assv (obj list) (cl:assoc obj list :test (lambda (a b) (clbool (eqv? a b)))))
(defun assoc (obj list) (cl:assoc obj list :test (lambda (a b) (clbool (equal? a b)))))
(defun symbol? (obj) (scbool (symbolp obj)))
(defun interned? (obj) (scbool (cl:and (symbolp obj) (symbol-package obj))))
(defun symbol->string (sym) (symbol-name sym))
(defun string->symbol (name) (intern name))
(defun char? (obj) (scbool (characterp obj)))
(defun char=? (a b) (scbool (char= a b)))
(defun char<? (a b) (scbool (char< a b)))
(defun char>? (a b) (scbool (char> a b)))
(defun char<=? (a b) (scbool (char<= a b)))
(defun char>=? (a b) (scbool (char>= a b)))
(defun char-ci=? (a b) (scbool (char-equal a b)))
(defun char-ci<? (a b) (scbool (char-lessp a b)))
(defun char-ci>? (a b) (scbool (char-greaterp a b)))
(defun char-ci<=? (a b) (scbool (cl:not (char-greaterp a b))))
(defun char-ci>=? (a b) (scbool (cl:not (char-lessp a b))))
(defun char-alphabetic? (a) (scbool (alpha-char-p a)))
(defun char-numeric? (a) (scbool (digit-char a)))
(defun char-whitespace? (a) (scbool (find a #(#\space #\tab #\newline #\vt #\page #\return))))
(defun char-upper-case? (a) (char=? a (char-upcase a)))
(defun char-lower-case? (a) (char=? a (char-downcase a)))
(defun char->integer (a) (char-code a))
(defun integer->char (a) (code-char a))
(defun string? (obj) (scbool (stringp obj)))
(defun make-string (k &optional (char #\space)) (cl:make-string k :initial-element char))
(defun string (&rest characters) (coerce characters 'cl:string))
(defun string-length (string) (length string))
(defun string-ref (string k) (aref string k))
(defun string-set! (string k char) (setf (aref string k) char))
(defun string=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string= a b)))
(defun string<? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string< a b)))
(defun string>? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string> a b)))
(defun string<=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string<= a b)))
(defun string>=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string>= a b)))
(defun string-ci=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string-equal a b)))
(defun string-ci<? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string-lessp a b)))
(defun string-ci>? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (string-greaterp a b)))
(defun string-ci<=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (cl:not (string-greaterp a b))))
(defun string-ci>=? (a b) (check-type a cl:string) (check-type b cl:string) (scbool (cl:not (string-lessp a b))))
(defun substring (string start end) (subseq string start end))
(defun string-append (&rest strings) (apply (function concatenate) 'cl:string strings))
(defun string->list (string) (coerce string 'list))
(defun list->string (list) (coerce list 'cl:string))
(defun string-copy (string) (copy-seq string))
(defun string-fill! (string char) (fill string char))
(defun vector? (obj) (scbool (cl:and (vectorp obj) (cl:not (stringp obj)))))
(defun make-vector (k &optional fill) (make-array k :initial-element fill))
(defun vector-length (vector) (length vector))
(defun vector-ref (vector k) (aref vector k))
(defun vector-set! (vector k obj) (setf (aref vector k) obj))
(defun vector->list (vector) (coerce vector 'list))
(defun list->vector (list) (coerce list 'vector))
(defun vector-fill! (vector fill) (fill vector fill))
(defun procedure? (obj) (scbool (functionp obj)))
(defun map (proc &rest lists) (apply (function cl:map) 'list proc lists))
(defun for-each (proc &rest lists) (apply (function mapc) proc lists))
(defun dynamic-wind (before thunk after)
(unwind-protect
(progn (funcall before)
(funcall thunk))
(funcall after)))
(defun null-environment (version) (declare (ignore version)) nil)
(defun scheme-report-environment (version) (declare (ignore version)) nil)
(defun interaction-environment (version) (declare (ignore version)) nil)
(defun eval (expression environment-specifier)
(declare (ignore environment-specifier))
(cl:eval expression))
(defun call-with-input-file (string proc)
(with-open-file (stream string)
(funcall proc stream)))
(defun call-with-output-file (string proc)
(with-open-file (stream string
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(funcall proc stream)))
(defun input-port? (obj) (and (streamp obj)) (INPUT-STREAM-P obj))
(defun output-port? (obj) (and (streamp obj)) (OUTPUT-STREAM-P obj))
(defun current-input-port () *standard-input*)
(defun current-output-port () *standard-output*)
(defun with-input-from-file (string thunk)
(call-with-input-file string (lambda (stream)
(let ((*standard-input* stream))
(funcall thunk)))))
(defun with-output-from-file (string thunk)
(call-with-output-file string (lambda (stream)
(let ((*standard-output* stream))
(funcall thunk)))))
(defun open-input-file (filename) (open filename))
(defun open-output-file (filename) (open filename
:direction :output
:if-exists :supersede
:if-does-not-exist :create))
(defun close-input-port (port) (close port))
(defun close-output-port (port) (close port))
(defun read (&optional (port *standard-input*)) (cl:read port nil +eof+))
(defun read-char (&optional (port *standard-input*)) (cl:read-char port nil +eof+))
(defun peek-char (&optional (port *standard-input*)) (cl:peek-char nil port nil +eof+))
(defun eof-object? (obj) (scbool (eq obj +eof+)))
(defun char-ready? (&optional (port *standard-input*))
(scbool (listen port)))
(defun write (obj &optional (port *standard-output*))
(cl:write obj :stream port
:array t :base 10. :case :downcase :circle t
:escape t :gensym t :length nil :level nil :lines nil
:miser-width nil :pretty nil
:radix t :readably t :right-margin nil))
(defun display (obj &optional (port *standard-output*))
(cl:write obj :stream port
:array t :base 10. :case :downcase :circle nil
:escape nil :gensym nil :length nil :level nil :lines nil
:miser-width nil :pretty t
:radix nil :readably nil :right-margin nil))
(defun newline (&optional (port *standard-output*))
(terpri port))
(defun write-char (char &optional (port *standard-output*))
(write-char char port))
(defun transcript-on (filename) (dribble filename))
(defun transcript-off () (dribble))
(cl:in-package "INTERSECTION-CL-R5RS.USER")
(let* ((a 1)
(b 4)
(c 2))
(if (= 0 a)
(write "a must be non zero")
(let ((d (- (* b b) (* 4 a c))))
(cond
((< d 0)
(write "No real solution")
'())
((= d 0)
(let ((sol (/ (- b) 2 a)))
(write "One real solution ")
(write sol)
(list sol)))
((> d 0)
(let ((s1 (/ (+ (- b) (sqrt d)) 2 a))
(s2 (/ (- (- b) (sqrt d)) 2 a)))
(write "Two real solutions ")
(write s1)
(write " ")
(write s2)
(list s1 s2)))))))
;; (enter three numbers)
(cl:in-package "INTERSECTION-CL-R5RS.LIBRARY.USER")
(define a 3)
(begin
(let ((a 1))
(newline)
(display a) (display " ")
(set! a 2)
(display a) (display " "))
(display a)
(newline)
'())
(write '(cl:in-package "INTERSECTION-CL-R5RS.LIBRARY.USER"))
;;;; THE END ;;;;
| 23,028 | Common Lisp | .lisp | 501 | 38.654691 | 116 | 0.579804 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 1ae8d2184a18ed02b3e00ea835953218725e5e50ccea91559f1667ee681404fd | 4,851 | [
-1
] |
4,852 | generate-application.lisp | informatimago_lisp/small-cl-pgms/botihn/generate-application.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: generate-application.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Save the botihn executable.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-04-27 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(progn (format t "~%;;; Loading quicklisp.~%") (finish-output) (values))
(load #P"~/quicklisp/setup.lisp")
(ql:register-local-projects)
(progn (format t "~%;;; Loading botihn.~%") (finish-output) (values))
(push (make-pathname :name nil :type nil :version nil
:defaults *load-truename*) asdf:*central-registry*)
(ql:quickload :com.informatimago.small-cl-pgms.botihn)
#+ccl (pushnew 'com.informatimago.common-lisp.interactive.interactive:initialize
ccl:*restore-lisp-functions*)
(progn (format t "~%;;; Saving botihn.~%") (finish-output) (values))
;; This doesn't return.
#+ccl (ccl::save-application
"botihn"
:mode #o755 :prepend-kernel t
:toplevel-function (function com.informatimago.small-cl-pgms.botihn:main)
:init-file nil ;; "~/.botihn.lisp"
:error-handler :quit)
| 2,323 | Common Lisp | .lisp | 53 | 41.377358 | 83 | 0.621801 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 317bf88a4a7a68984161885ebfaa1483272f719b4b3acf1f14681a21cdf13904 | 4,852 | [
-1
] |
4,853 | botihn.lisp | informatimago_lisp/small-cl-pgms/botihn/botihn.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: botihn.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: IRC
;;;;DESCRIPTION
;;;;
;;;; Botihn: an IRC bot monitoring Hacker News.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2019-08-27 <PJB> Added blacklist.
;;;; 2015-07-17 <PJB> Added commands: help uptime version sources; added restarts.
;;;; 2015-04-27 <PJB> Created.
;;;;BUGS
;;;; We should better validate syntax of blacklist add inputs.
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2019
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIHN"
(:use "COMMON-LISP"
"CL-IRC" "CL-JSON" "DRAKMA" "SPLIT-SEQUENCE" "CL-PPCRE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.INTERACTIVE.INTERACTIVE"
"DATE" "UPTIME")
(:export "MAIN")
(:documentation "
Botihn is a simple IRC bot monitoring Hacker News, and writing to
irc://irc.libera.chat/#hn the title and url of each new news.
It is run with:
(com.informatimago.small-cl-pgms.botihn:main)
Copyright Pascal J. Bourguignon 2015 - 2021
Licensed under the AGPL3.
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIHN")
(defparameter *version* "1.2.1")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Configuration:
;;;
(defvar *server* "irc.libera.chat"
"The fqdn of the IRC server.")
(defvar *nickname* "botihn"
"The nickname of the botihn user.")
(defvar *channel* "#hn"
"The channel were the HackerNews stories are sent to.")
(defvar *sources-url*
"https://gitlab.com/com-informatimago/com-informatimago/tree/master/small-cl-pgms/botihn/"
"The URL where the sources of this ircbot can be found.")
(defvar *connection* nil
"The current IRC server connection.")
(defvar *botpass* "1234")
(defvar *blacklist* '()
"A list of lists (label :url \"regex\") or (label :title \"regexp\") used to match either the url or the title of the HN news.
Matchedp news are not transmitted on irc.
The LABEL is a unique symbol used to identifythe blacklist entry.")
(defvar *blacklist-file* #P"/usr/local/var/botihn/blacklist.sexp"
"Path of the file where the *blacklist* is saved.")
(defvar *blacklist-log-file* #P"/usr/local/var/botihn/blacklist.log"
"Path of thef ile where the changes to the blacklist are logged.")
(defvar *requester-nick* nil
"Nickname of the user who send the current command.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun load-blacklist ()
(setf *blacklist* (sexp-file-contents *blacklist-file* :if-does-not-exist '())))
(defun save-blacklist ()
(setf (sexp-file-contents *blacklist-file*) *blacklist*))
(defun find-blacklist-entry (label)
(find label *blacklist* :key (function first) :test (function string=)))
(defun delete-blacklist-entry (label)
(setf *blacklist* (delete label *blacklist* :key (function first) :test (function string=)))
(save-blacklist))
(defun add-blacklist-entry (label kind regexp)
(let ((entry (find-blacklist-entry label)))
(if entry
(setf (second entry) kind
(third entry) regexp)
(push (list label kind regexp) *blacklist*))
(save-blacklist)))
(defun blacklistedp (story)
(loop
:for (label kind regexp) :in *blacklist*
;; If there is an error, perhaps we should remove the enrty in the *blacklist*
:thereis (ignore-errors (scan regexp
(ecase kind
(:title (story-title story))
(:url (story-url story)))))))
(defun log-blacklist-change (nick operation entry)
(with-open-file (log *blacklist-log-file*
:if-does-not-exist :create
:if-exists :append
:direction :output)
(format log "~A ~S ~S ~S~%" (get-universal-time) nick operation entry)))
(defun process-blacklist-command (words)
;; blacklist help
;; blacklist add label url|title regexp
;; blacklist list
;; blacklist delete label
(scase (second words)
(("help")
(answer "blacklist list")
(answer "blacklist add <label> url|title <regexp>")
(answer "blacklist delete <label>"))
(("add")
(let* ((label (third words))
(kind-string (fourth words))
(regexp (fifth words))
(kind (scase kind-string
(("url") :url)
(("title") :title))))
(unless (and (stringp label)
(member kind '(:url :title))
(stringp regexp))
(answer "Invalid command."))
(log-blacklist-change *requester-nick* :add (list label kind regexp))
(add-blacklist-entry label kind regexp)))
(("delete")
(let ((label (third words)))
(unless (stringp label)
(answer "Invalid command."))
(let ((entry (find-blacklist-entry label)))
(if entry
(progn
(log-blacklist-change *requester-nick* :delete entry)
(delete-blacklist-entry label))
(answer "No such entry ~S" label)))))
(("list")
(loop :for (label kind regexp) :in *blacklist*
:do (answer "~12A ~8A ~A~%" label kind regexp)))
(otherwise
(answer "Invalid command."))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; cf. https://github.com/HackerNews/API
(defvar *period* 10 #|seconds|#
"The minimum period for fetching new news from Hacker News.")
(defvar *last-story* nil
"The id of the last story sent to the IRC channel.")
(declaim (notinline monitor-initialize monitor-hacker-news))
(defun monitor-initialize ()
"Initialize the Hacker News monitor.
Resets the *LAST-STORY*."
(unless (find '("application" . "json") *text-content-types*
:test (function equalp))
(push '("application" . "json") *text-content-types*))
(setf *last-story* nil))
(defun compute-deadline (timeout)
(+ (get-internal-real-time)
(* timeout internal-time-units-per-second)))
(defun new-stories ()
"Fetch and return the list of new stories from the HackerNews API
server."
(multiple-value-bind (value status)
(http-request "https://hacker-news.firebaseio.com/v0/newstories.json"
:connection-timeout 10
#+openmcl :deadline #+openmcl (compute-deadline 3))
(when (= 200 status)
(decode-json-from-string value))))
(defun story (id)
"Fetch and return an a-list containing the data of the story
identified by number ID."
(multiple-value-bind (value status)
(http-request (format nil "https://hacker-news.firebaseio.com/v0/item/~A.json" id)
:connection-timeout 10
#+openmcl :deadline #+openmcl (compute-deadline 3))
(when (= 200 status)
(decode-json-from-string value))))
(defun get-new-stories ()
"Return the list of the new stories IDs that haven't been sent to
the IRC server yet, in chronological order."
(let ((news (new-stories)))
(if *last-story*
(reverse (subseq news 0 (or (position *last-story* news) 1)))
(list (first news)))))
(defun hn-url (story-id)
"Return the URL to the HackerNews story page for the given STORY-ID."
(format nil "https://news.ycombinator.com/item?id=~A" story-id))
(defun story-id (story) (aget story :id))
(defun story-title (story) (aget story :title))
(defun story-url (story)
(let ((url (aget story :url)))
(when url
(if (zerop (length url))
(hn-url id)
url))))
(defun format-story (story)
"Returns a single line message containing the story title and the story URL,
extracted from the give STORY a-list."
(let ((title (story-title story))
(url (story-url story))
(id (story-id story)))
(when (and title url)
(format nil "~A <~A>" title url))))
(defun monitor-hacker-news (send)
"Sends the new news message lines by calling the SEND function.
Updates the *LAST-STORY* ID."
(dolist (id (get-new-stories))
(let ((story (story id)))
(unless (blacklistedp story)
(let ((message (format-story story)))
(when message
(funcall send message)))))
(setf *last-story* id)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; (setf *nickname* "botihn-test" *channel* "#botihn-test")
(defun configure ()
(setf *server* (or (uiop:getenv "BOTIHN_SERVER") *server*)
*nickname* (or (uiop:getenv "BOTIHN_NICKNAME") *nickname*)
*channel* (or (uiop:getenv "BOTIHN_CHANNEL") *channel*)
*botpass* (or (uiop:getenv "BOTIHN_BOTPASS") *botpass*)))
(defun say (&rest args)
(format t "~&~{~A~^ ~}~%" args)
(force-output))
(defun answer (format-control &rest format-arguments)
(let ((text (apply (function format) nil format-control format-arguments)))
(say text)
(privmsg *connection* *requester-nick* text)))
(defun eliza (words)
(dolist (line (split-sequence #\newline (uiop:run-program "fortune" :output :string)
:remove-empty-subseqs t))
(answer line)))
(defun msg-hook (message)
"Answers to PRIVMSG sent directly to this bot."
(let ((arguments (arguments message))
(*requester-nick* (source message)))
(say arguments)
(when (string= *nickname* (first arguments))
(let ((words (split-sequence #\space (second arguments) :remove-empty-subseqs t)))
(scase (first words)
(("help")
(answer "Available commands: help version uptime sources blacklist")
(answer "Type: blacklist help for help on blacklist command."))
(("version")
(answer "Version: ~A" *version*))
(("uptime")
(answer "~A" (substitute #\space #\newline
(with-output-to-string (*standard-output*)
(date) (uptime)))))
(("reconnect")
(if (string= (second words) *botpass*)
(progn (answer "Reconnecting…")
(reconnect))
(answer "I'm not in the mood.")))
(("blacklist")
(process-blacklist-command words))
(("sources")
(answer "I'm an IRC bot forwarding HackerNews news to ~A; ~
under AGPL3 license, my sources are available at <~A>."
*channel*
*sources-url*))
(otherwise
(eliza words))))))
t)
(defun call-with-retry (delay thunk)
"Calls THUNK repeatitively, reporting any error signaled,
and calling the DELAY-ing thunk between each."
(loop
(handler-case (funcall thunk)
(error (err) (format *error-output* "~A~%" err)))
(funcall delay)))
(defmacro with-retry (delay-expression &body body)
"Evaluates BODY repeatitively, reporting any error signaled,
and evaluating DELAY-EXPRESSIONS between each iteration."
`(call-with-retry (lambda () ,delay-expression)
(lambda () ,@body)))
(defun exit ()
"Breaks the main loop and exit."
(throw :gazongues nil))
(defun reconnect ()
"Disconnect and reconnect to the IRC server."
(throw :petites-gazongues nil))
(defparameter *allow-print-backtrace* t)
(defun print-backtrace (&optional (output *error-output*))
#+ccl (when *allow-print-backtrace*
(let ((*allow-print-backtrace* nil))
(format output "~&~80,,,'-<~>~&~{~A~%~}~80,,,'-<~>~&"
(ccl::backtrace-as-list)))))
(defun main ()
"The main program of the botihn IRC bot.
We connect and reconnect to the *SERVER* under the *NICKNAME*,
and join to the *CHANNEL* where HackerNews are published."
(let ((*package* (load-time-value (find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIHN"))))
(configure)
(load-blacklist)
(with-simple-restart (quit "Quit")
(catch :gazongues
(with-retry (sleep (+ 10 (random 30)))
(with-simple-restart (reconnect "Reconnect")
(catch :petites-gazongues
(unwind-protect
(progn
(setf *connection* (connect :nickname *nickname* :server *server*))
(add-hook *connection* 'irc::irc-privmsg-message 'msg-hook)
(join *connection* *channel*)
(monitor-initialize)
(loop
:with next-time = (+ *period* (get-universal-time))
:for time = (get-universal-time)
:do (if (<= next-time time)
(progn
(handler-bind
((error (lambda (err)
(print-backtrace)
(format *error-output* "~%~A~%" err))))
(monitor-hacker-news (lambda (message) (privmsg *connection* *channel* message))))
(incf next-time *period*))
(read-message *connection*) #|there's a 10 s timeout in here.|#)))
(when *connection*
(quit *connection*)
(setf *connection* nil))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
| 14,957 | Common Lisp | .lisp | 331 | 36.758308 | 128 | 0.577044 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 75c649470f7a2328f4217fad086592f957d684139faee53d9db13b4487f030d0 | 4,853 | [
-1
] |
4,854 | swap.lisp | informatimago_lisp/small-cl-pgms/sedit/swap.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(progn (defmacro comment (&rest ignore)
(declare (ignore ignore))
(values))
(comment "
This file demonstrate how one can add a command
dynamically to sedit, thus demonstrating how sedit
is an emacs. ;-)
")
(defun previous-cell (list cell)
(loop :for current :on list
:until (eq (cdr current) cell)
:finally (return current)))
(defun sedit-swap (buffer)
"swaps the expression before the selection with the selection."
(with-buffer (buffer root selection)
(let ((parent
(selection-parent-list selection))
(selection-cell
(sedit-find-object root selection)))
(if (eq (car selection-cell) selection)
(let ((previous-cell
(previous-cell
parent
selection-cell)))
(when
(and previous-cell selection-cell)
(rotatef
(car previous-cell)
(car selection-cell))))
(progn (comment "selection is a cdr.")
(rotatef
(car selection-cell)
(cdr selection-cell)))))))
(add-command 'w
'swap
'sedit-swap
"swaps the expression before with the selection."))
| 1,814 | Common Lisp | .lisp | 39 | 25.435897 | 74 | 0.430908 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a5ad0c0ed2d4469ee947e5b7773e356226a98a2a2f2f79023cc05682c59af5c0 | 4,854 | [
-1
] |
4,855 | sedit.lisp | informatimago_lisp/small-cl-pgms/sedit/sedit.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: sedit.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A simple sexp editor.
;;;;
;;;; It is invoked as (sedit sexp), and returns the modified sexp.
;;;; (The sexp is modified destructively).
;;;;
;;;; (sedit (copy-tree '(an example)))
;;;;
;;;; At each interaction loop, it prints the whole sexp, showing
;;;; the selected sub-sexp, and query a command. Use the help
;;;; command to get the list of commands.
;;;;
;;;; Notice: it uses the unicode characters LEFT_BLACK_LENTICULAR_BRACKET
;;;; and RIGHT_BLACK_LENTICULAR_BRACKET to show the selected sub-sexp.
;;;; This could be changed easily modifying SEDIT-PRINT-SELECTION.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-10-15 <PJB> Abstracted away BUFFER. Added bindings, loading and saving.
;;;; 2010-09-08 <PJB> Created.
;;;;BUGS
;;;;
;;;; Command table and bindings is implemented quick & dirty.
;;;;
;;;; There's some new code in sedit2.lisp; a diff3 should be done
;;;; with the previous version and new commands merged in.
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT"
(:use "COMMON-LISP")
(:export "SEDIT"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT")
#|
The buffer is represented by two objects: a root cell, and a selection
structure.
The root cell is a list containing the edited sexp as single element.
The selection structure is present inside the root sexp, and contain a
reference to the list where it is present in, and the sub-sexp that is
selected. (Note when the whole sexp is selected, then the selection
structure is the element of the root cell).
|#
(defstruct selection
parent-list
sexp)
(defstruct (buffer (:constructor %make-buffer))
root selection)
(defvar *clipboard* nil)
(defun make-buffer (contents)
(let* ((root (list contents))
(selection (make-selection)))
(select selection root 0)
(setf (first root) selection)
(%make-buffer :root root
:selection selection)))
(defmacro with-buffer ((buffer rootvar selectionvar) &body body)
`(with-accessors ((,rootvar buffer-root)
(,selectionvar buffer-selection))
,buffer
,@body))
(defun find-cell (object list)
(cond
((eq (car list) object) list)
((null (cdr list)) nil)
((and (atom (cdr list))
(eq (cdr list) object)) list)
(t (find-cell object (cdr list)))))
(defun unselect (selection)
(let ((cell (find-cell selection (selection-parent-list selection))))
(when cell
(if (eq (car cell) selection)
(setf (car cell) (selection-sexp selection))
(setf (cdr cell) (selection-sexp selection))))))
(defun nth-cdr (n list)
(cond
((not (plusp n)) list)
((atom list) list)
(t (nth-cdr (1- n) (cdr list)))))
(defun select (selection parent index)
(cond
((atom parent)
(error "Cannot select from an atom."))
(t
(let ((cell (nth-cdr index parent)))
(cond
((null cell) (error "cannot select so far"))
((atom cell) (setf (selection-parent-list selection) parent
(selection-sexp selection) (cdr cell)
(cdr cell) selection))
(t (setf (selection-parent-list selection) parent
(selection-sexp selection) (car cell)
(car cell) selection)))))))
(defun sedit-find-object (sexp object)
"Return the cons cell of SEXP where the OBJECT is."
(cond
((atom sexp) nil)
((eq sexp object) nil)
((or (eq (car sexp) object)
(eq (cdr sexp) object)) sexp)
(t (or (sedit-find-object (car sexp) object)
(sedit-find-object (cdr sexp) object)))))
(defmethod print-object ((selection selection) stream)
(princ "【" stream)
(prin1 (selection-sexp selection) stream)
(princ "】" stream)
selection)
(defun sedit-print (buffer)
(pprint (first (buffer-root buffer)))
(finish-output))
(defun unselected-sexp (list selection)
"Return a copy of the lisp sexp with the selection removed."
(cond
((consp list)
(cons (unselected-sexp (car list) selection)
(unselected-sexp (cdr list) selection)))
((eq list selection)
(unselected-sexp (selection-sexp selection) selection))
(t
list)))
(defmacro reporting-errors (&body body)
`(handler-case
(progn ,@body)
(simple-condition (err)
(format *error-output* "~&~A:~%~?~&"
(class-name (class-of err))
(simple-condition-format-control err)
(simple-condition-format-arguments err))
(finish-output *error-output*))
(condition (err)
(format *error-output* "~&~A:~%~A~%"
(class-name (class-of err))
err)
(finish-output *error-output*))))
(defun sedit-eval (buffer)
(with-buffer (buffer root selection)
(let ((sexp (selection-sexp selection)))
(reporting-errors
(format *query-io* "~& --> ~{~S~^ ;~% ~}~%"
(let ((*package* *package*)
(*readtable* *readtable*))
(multiple-value-list (eval sexp)))))
(finish-output *query-io*)
(finish-output))))
(defun sedit-down (buffer)
(with-buffer (buffer root selection)
(if (atom (selection-sexp selection))
(progn (princ "Cannot enter an atom.") (terpri))
(progn
(unselect selection)
(select selection (selection-sexp selection) 0)))))
(defun sedit-up (buffer)
(with-buffer (buffer root selection)
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(when gparent
(unselect selection)
(select selection gparent 0)))))
(defun sedit-forward (buffer)
(with-buffer (buffer root selection)
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index)
(<= (length (selection-parent-list selection)) (1+ index)))
(sedit-up buffer)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1+ index)))))))
(defun sedit-backward (buffer)
(with-buffer (buffer root selection)
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index) (<= index 0))
(sedit-up buffer)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1- index)))))))
(defun sedit-cut (buffer)
(with-buffer (buffer root selection)
(setf *clipboard* (selection-sexp selection))
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (delete selection (selection-parent-list selection)))
(setf (cdr gparent) (delete selection (selection-parent-list selection))))
(select selection gparent 0))))
(defun sedit-copy (buffer)
(with-buffer (buffer root selection)
(declare (ignore root))
(setf *clipboard* (copy-tree (selection-sexp selection)))))
(defun sedit-paste (buffer)
(with-buffer (buffer root selection)
(declare (ignore root))
(setf (selection-sexp selection) (copy-tree *clipboard*))))
(defun sedit-replace (buffer)
(with-buffer (buffer root selection)
(declare (ignore root))
(princ "replacement sexp: " *query-io*)
(finish-output *query-io*)
(setf (selection-sexp selection) (read *query-io*))))
(defun insert (object list where reference)
(ecase where
((:before)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq reference (car list))
(setf (cdr list) (cons (car list) (cdr list))
(car list) object))
(t (insert object (cdr list) where reference))))
((:after)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(push object (cdr list)))
(t (insert object (cdr list) where reference))))))
(defun sedit-insert (buffer)
(with-buffer (buffer root selection)
(princ "sexp to be inserted before: " *query-io*)
(finish-output *query-io*)
(let ((new-sexp (read *query-io*)))
(cond
((eq selection (first root))
;; The whole expression is selected. To insert before it we
;; need to wrap it in a new list.
(setf (car root) (list new-sexp selection)
(selection-parent-list selection) (car root)))
((eq selection (first (selection-parent-list selection)))
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(setf (selection-parent-list selection)
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (cons new-sexp (selection-parent-list selection)))
(setf (cdr gparent) (cons new-sexp (selection-parent-list selection)))))))
(t
(insert new-sexp (selection-parent-list selection) :before selection))))))
(defun sedit-add (buffer)
(with-buffer (buffer root selection)
(princ "sexp to be inserted after: " *query-io*)
(finish-output *query-io*)
(let ((new-sexp (read *query-io*)))
(if (eq selection (first root))
;; The whole expression is selected. To insert after it we
;; need to wrap it in a new list.
(setf (car root) (list selection new-sexp)
(selection-parent-list selection) (car root))
(insert new-sexp (selection-parent-list selection) :after selection)))))
(defun sedit-replace (buffer)
(with-buffer (buffer root selection)
(declare (ignore root))
(princ "replacement sexp: " *query-io*)
(finish-output *query-io*)
(setf (selection-sexp selection) (read *query-io*))))
(defun sedit-save (buffer)
(with-buffer (buffer root selection)
(princ "Save buffer to file: " *query-io*)
(finish-output *query-io*)
(let ((path (read-line *query-io*)))
(with-open-file (out path :direction :output
:if-does-not-exist :create
:if-exists :supersede)
(pprint (unselected-sexp (first root) selection) out)
(terpri out)))))
(defun sedit-load (buffer)
(with-buffer (buffer root selection)
(princ "Load file: " *query-io*)
(finish-output *query-io*)
(let* ((path (read-line *query-io*))
(new (make-buffer (with-open-file (inp path :direction :input)
(read inp)))))
(setf root (buffer-root new)
selection (buffer-selection new)))))
(defun sedit-quit (buffer)
(throw 'gazongue buffer))
;;; Quick and dirty command table and bindings:
;;; TODO: make it better.
(defparameter *command-map*
'((q quit sedit-quit "return the modified sexp from sedit.")
(d down sedit-down "enter inside the selected list.")
(u up sedit-up "select the list containing the selection.")
(f forward sedit-forward "select the sexp following the selection (or up).")
(n next sedit-forward "select the sexp following the selection (or up).")
(b backward sedit-backward "select the sexp preceding the selection (or up).")
(p previous sedit-backward "select the sexp preceding the selection (or up).")
(i insert sedit-insert "insert a new sexp before the selection.")
(r replace sedit-replace "replace the selection with a new sexp.")
(a add sedit-add "add a new sexp after the selection.")
(x cut sedit-cut "cut the selection into a *clipboard*.")
(c copy sedit-copy "copy the selection into a *clipboard*.")
(y paste sedit-paste "paste the *clipboard* replacing the selection.")
(e eval sedit-eval "evaluate the selection")
(s save sedit-save "save the buffer to a file.")
(l load sedit-load "load a file into the buffer.")
(h help sedit-help "print this help.")))
(defvar *bindings* (make-hash-table))
(defun bind (command function)
(setf (gethash command *bindings*) function))
(defun unbind (command)
(remhash command *bindings*))
(defun binding (command)
(gethash command *bindings*))
(defun add-command (short long function help)
(setf *command-map* (append *command-map*
(list (list short long function help))))
(bind short function)
(bind long function))
(defun sedit-help (buffer)
(declare (ignore buffer))
(format t "~:{~A) ~10A ~*~A~%~}" *command-map*))
(defun initialize-bindings ()
(loop :for (short long function) :in *command-map*
:do (bind short function)
(bind long function)))
;;; The core:
(declaim (notinline sedit-core))
(defun sedit-core (buffer)
(with-buffer (buffer root selection)
(sedit-print buffer)
(terpri *query-io*)
(princ "> " *query-io*)
(finish-output *query-io*)
(let* ((command (let ((*package*
(load-time-value
(find-package
"COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT"))))
(read *query-io*)))
(function (binding command)))
(if function
(funcall function buffer)
(format *query-io* "~%Please use one of these commands:~%~
~:{~<~%~1,40:;~A (~A)~>~^, ~}.~2%"
*command-map*)))))
(defun sedit (&optional sexp)
(terpri)
(princ "Sexp Editor:")
(terpri)
(initialize-bindings)
(let ((buffer (make-buffer sexp)))
(unwind-protect
(catch 'gazongue (loop (reporting-errors
(sedit-core buffer))))
(unselect (buffer-selection buffer)))
(first (buffer-root buffer))))
;;;; THE END ;;;;
| 15,023 | Common Lisp | .lisp | 361 | 35.32964 | 95 | 0.622055 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | edd3b67d997b1bd73894de6dee2f9d981ec7668c5ee079b2ca19d41f04278f4d | 4,855 | [
-1
] |
4,856 | sedit2.lisp | informatimago_lisp/small-cl-pgms/sedit/sedit2.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: sedit.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A simple sexp editor.
;;;;
;;;; It is invoked as (sedit sexp), and returns the modified sexp.
;;;; (The sexp is modified destructively).
;;;;
;;;; (sedit (copy-tree '(an example)))
;;;;
;;;; At each interaction loop, it prints the whole sexp, showing the selected
;;;; sub-sexp, and query a command. The list of commands are:
;;;;
;;;; q quit to return the modified sexp from sedit.
;;;; i in to enter inside the selected list.
;;;; o out to select the list containing the selection.
;;;; f forward n next to select the sexp following the selection (or out).
;;;; b backward p previous to select the sexp preceding the selection (or out).
;;;; s insert to insert a new sexp before the selection.
;;;; r replace to replace the selection with a new sexp.
;;;; a add to add a new sexp after the selection.
;;;; x cut to cut the selection into a *clipboard*.
;;;; c copy to copy the selection into a *clipboard*.
;;;; y paste to paste the *clipboard* replacing the selection.
;;;;
;;;; Notice: it uses the unicode characters LEFT_BLACK_LENTICULAR_BRACKET
;;;; and RIGHT_BLACK_LENTICULAR_BRACKET to show the selected sub-sexp.
;;;; This could be changed easily modifying SEDIT-PRINT-SELECTION.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-09-08 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2"
(:use "COMMON-LISP")
(:export "SEDIT"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.SEDIT.2")
(eval-when (:compile-toplevel :load-toplevel :execute)
(when (= char-code-limit 1114112)
(pushnew :unicode *features*)))
(defstruct selection
parent-list
sexp)
(defmethod print-object ((selection selection) stream)
(format stream #+unicode " 【~S】 "
#-unicode " [~S] "
(selection-sexp selection))
selection)
(defvar *clipboard* nil)
(defun find-cell (object list)
(cond
((eq (car list) object) list)
((null (cdr list)) nil)
((and (atom (cdr list))
(eq (cdr list) object)) list)
(t (find-cell object (cdr list)))))
(defun unselect (selection)
(let ((cell (find-cell selection (selection-parent-list selection))))
(when cell
(if (eq (car cell) selection)
(setf (car cell) (selection-sexp selection))
(setf (cdr cell) (selection-sexp selection))))))
(defun nth-cdr (n list)
(cond
((not (plusp n)) list)
((atom list) list)
(t (nth-cdr (1- n) (cdr list)))))
(defun select (selection parent index)
(cond
((atom parent)
(error "Cannot select from an atom."))
(t
(let ((cell (nth-cdr index parent)))
(cond
((null cell) (error "cannot select so far"))
((atom cell) (setf (selection-parent-list selection) parent
(selection-sexp selection) cell
(cdr (nth-cdr (1- index) parent)) selection))
(t (setf (selection-parent-list selection) parent
(selection-sexp selection) (car cell)
(car cell) selection)))))))
(defun sedit-find-object (sexp object)
"Return the cons cell of SEXP where the OBJECT is."
(cond
((atom sexp) nil)
((eq sexp object) nil)
((or (eq (car sexp) object)
(eq (cdr sexp) object)) sexp)
(t (or (sedit-find-object (car sexp) object)
(sedit-find-object (cdr sexp) object)))))
(defun sedit-in (root selection)
"When a non-empty list is selected, change the selection to the first element of the list."
(declare (ignore root))
(if (atom (selection-sexp selection))
(progn (princ "Cannot enter an atom.") (terpri))
(progn
(unselect selection)
(select selection (selection-sexp selection) 0))))
(defun sedit-out (root selection)
"Change the selection to the parent list of the current selection."
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(when gparent
(unselect selection)
(select selection gparent 0))))
(defun sedit-forward (root selection)
"Change the selection to the element following the current selection, or the parent if it's the last."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index)
(<= (length (selection-parent-list selection)) (1+ index)))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1+ index))))))
(defun sedit-backward (root selection)
"Change the selection to the element preceeding the current selection, or the parent if it's the first."
(let ((index (position selection (selection-parent-list selection))))
(if (or (null index) (<= index 0))
(sedit-out root selection)
(progn (unselect selection)
(select selection (selection-parent-list selection) (1- index))))))
(defun sedit-enlist (root selection)
"Put the selection in a new list."
(declare (ignore root))
(setf (selection-sexp selection) (list (selection-sexp selection))))
(defun ensure-list (x)
(if (listp x) x (list x)))
(defun sedit-splice (root selection)
"Splice the elements of the selection in the parent."
(let* ((parent (selection-parent-list selection))
(selected (selection-sexp selection))
(index (position selection parent)))
(sedit-out root selection)
(setf (selection-sexp selection)
(append (subseq parent 0 index)
(ensure-list selected)
(subseq parent (1+ index))))))
(defun sedit-slurp (root selection)
"Append to the selection the element following it."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index
(< (1+ index) (length (selection-parent-list selection))))
(setf (selection-sexp selection)
(append (ensure-list (selection-sexp selection))
(list (pop (cdr (nth-cdr index (selection-parent-list selection))))))))))
(defun sedit-barf (root selection)
"Split out the last element of the selection."
(declare (ignore root))
(let ((index (position selection (selection-parent-list selection))))
(when (and index (consp (selection-sexp selection)))
(let ((barfed (first (last (selection-sexp selection)))))
(setf (selection-sexp selection) (butlast (selection-sexp selection)))
(insert barfed (selection-parent-list selection) :after selection)))))
(defun sedit-cut (root selection)
"Save the selection to the *CLIPBOARD*, and remove it."
(setf *clipboard* (selection-sexp selection))
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (delete selection (selection-parent-list selection)))
(setf (cdr gparent) (delete selection (selection-parent-list selection))))
(select selection gparent 0)))
(defun sedit-copy (root selection)
"Save the selection to the *CLIPBOARD*."
(declare (ignore root))
(setf *clipboard* (copy-tree (selection-sexp selection))))
(defun sedit-paste (root selection)
"Replace the selection by the contents of teh *CLIPBOARD*."
(declare (ignore root))
(setf (selection-sexp selection) (copy-tree *clipboard*)))
(defun sedit-replace (root selection)
"Replace the selection by the expression input by the user."
(declare (ignore root))
(princ "replacement sexp: " *query-io*)
(setf (selection-sexp selection) (read *query-io*)))
(defun insert (object list where reference)
(ecase where
((:before)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(setf (cdr list) (cons (car list) (cdr list))
(car list) object))
(t (insert object (cdr list) where reference))))
((:after)
(cond
((null list) (error "Cannot insert in an empty list."))
((eq (car list) reference)
(push object (cdr list)))
(t (insert object (cdr list) where reference))))))
(defun sedit-insert (root selection)
"Insert the expression input by the user before the selection."
(princ "sexp to be inserted before: " *query-io*)
(let ((new-sexp (read *query-io*)))
(if (eq (first (selection-parent-list selection)) selection)
(let ((gparent (sedit-find-object root (selection-parent-list selection))))
(setf (selection-parent-list selection)
(if (eq (car gparent) (selection-parent-list selection))
(setf (car gparent) (cons new-sexp (selection-parent-list selection)))
(setf (cdr gparent) (cons new-sexp (selection-parent-list selection))))))
(insert new-sexp (selection-parent-list selection) :before selection))))
(defun sedit-add (root selection)
"Insert the expression input by the user after the selection."
(declare (ignore root))
(princ "sexp to be inserted after: " *query-io*)
(let ((new-sexp (read *query-io*)))
(insert new-sexp (selection-parent-list selection) :after selection)))
(defun sedit (sexp)
"Edit the SEXP; return the new sexp."
(terpri)
(princ "Sexp Editor:")
(terpri)
(let* ((root (list sexp))
(selection (make-selection)))
(select selection root 0)
(setf (first root) selection)
(unwind-protect
(loop
(pprint root)
(terpri) (princ "> " *query-io*)
(let ((command (read *query-io*)))
(case command
((q quit) (return))
((i in) (sedit-in root selection))
((o out) (sedit-out root selection))
((f forward n next) (sedit-forward root selection))
((b backward p previous) (sedit-backward root selection))
((s insert) (sedit-insert root selection)) ; before
((r replace) (sedit-replace root selection)) ; in place
((a add) (sedit-add root selection)) ; after
((x cut) (sedit-cut root selection))
((c copy) (sedit-copy root selection))
((y paste) (sedit-paste root selection))
((l enlist) (sedit-enlist root selection))
((e splice) (sedit-splice root selection))
((u slurp) (sedit-slurp root selection))
((v barf) (sedit-barf root selection))
(otherwise
(princ "Please use one of these commands:")
(terpri)
(princ "quit, in, out, forward, backward, insert, replace, add, cut, copy, paste, slurp, barf.")
(terpri)))))
(unselect selection))
(first root)))
;;;; THE END ;;;;
| 12,364 | Common Lisp | .lisp | 269 | 39.973978 | 112 | 0.617803 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 25e8ab185a00384060762d95f07c6e369aa033951a8ab1e206b34e9a44e2a71c | 4,856 | [
-1
] |
4,857 | example-lisp.lisp | informatimago_lisp/small-cl-pgms/rdp/example-lisp.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: example-lisp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; An example grammar for the recusive descent parser generator.
;;;; The actions are written in Lisp, to generate a lisp parser.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2011-07-19 <PJB> Updated regexps, now we use extended regexps.
;;;; 2011-07-19 <PJB> Added defpackage forms. Added parsing example sources.
;;;; 2006-09-10 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.RDP.EXAMPLE"
(:use "COMMON-LISP" "COM.INFORMATIMAGO.RDP")
(:export "PARSE-EXAMPLE"))
(in-package "COM.INFORMATIMAGO.RDP.EXAMPLE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Example Language
;;; taken from: http://en.wikipedia.org/wiki/Recursive_descent_parser
;;;
(defgrammar example
:terminals ((ident "[A-Za-z][A-Za-z0-9]*")
;; real must come first to match the longest first.
(real "[-+]?[0-9]+\\.[0-9]+([Ee][-+]?[0-9]+)?")
(integer "[-+]?[0-9]+"))
:start program
:rules ((--> factor
(alt ident
number
(seq "(" expression ")" :action $2))
:action $1)
(--> number (alt integer real) :action $1)
(--> term
factor (rep (alt "*" "/") factor)
:action `(,$1 . ,$2))
(--> expression
(opt (alt "+" "-"))
term
(rep (alt "+" "-") term :action `(,$1 ,$2))
:action `(+ ,(if $1 `(,$1 ,$2) $2) . ,$3))
(--> condition
(alt (seq "odd" expression
:action `(oddp ,$2))
(seq expression
(alt "=" "#" "<" "<=" ">" ">=")
expression
:action `(,$2 ,$1 ,$3)))
:action $1)
(--> statement
(opt (alt (seq ident ":=" expression
:action `(setf ,$1 ,$3))
(seq "call" ident
:action `(call ,$2))
(seq "begin" statement
(rep ";" statement
:action $2)
"end"
:action `(,$2 . ,$3))
(seq "if" condition "then" statement
:action `(if ,$2 ,$4))
(seq "while" condition "do" statement
:action `(while ,$2 ,$4))))
:action $1)
(--> block
(opt "const" ident "=" number
(rep "," ident "=" number
:action `(,$2 ,$4))
";"
:action `((,$2 ,$4) . ,$5))
(opt "var" ident
(rep "," ident :action $2)
";"
:action `(,$2 . ,$3))
(rep "procedure" ident ";" block ";"
:action `(procedure ,$2 ,$4))
statement
:action `(block ,$1 ,$2 ,$3 ,$4))
(--> program
block "." :action $1)))
(assert (equal (com.informatimago.rdp.example:parse-example
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
'(block (((ident "abc" 11) (integer "123" 17)) ((ident "pi" 32) (real "3.141592e+0" 35))) ((ident "a" 57) (ident "b" 59) (ident "c" 61)) ((procedure (ident "gcd" 79) (block nil nil nil ((while (("#" "#" 112) (+ ((ident "a" 110))) (+ ((ident "b" 114)))) ((if (("<" "<" 151) (+ ((ident "a" 150))) (+ ((ident "b" 152)))) (setf (ident "b" 159) (+ ((ident "b" 162)) (("-" "-" 163) ((ident "a" 164)))))) (if ((">" ">" 186) (+ ((ident "a" 185))) (+ ((ident "b" 187)))) (setf (ident "a" 194) (+ ((ident "a" 197)) (("-" "-" 198) ((ident "b" 199)))))))))))) ((setf (ident "a" 235) (+ ((integer "42" 238)))) (setf (ident "b" 246) (+ ((real "30.0" 249)))) (call (ident "gcd" 264))))))
(defpackage "COM.INFORMATIMAGO.RDP.EXAMPLE-WITHOUT-ACTION"
(:use "COMMON-LISP" "COM.INFORMATIMAGO.RDP")
(:export "PARSE-EXAMPLE-WITHOUT-ACTION"))
(in-package "COM.INFORMATIMAGO.RDP.EXAMPLE-WITHOUT-ACTION")
(defgrammar example-without-action
:terminals ((ident "[A-Za-z][A-Za-z0-9]*")
;; real must come first to match the longest first.
(real "[-+]?[0-9]+\\.[0-9]+([Ee][-+]?[0-9]+)?")
(integer "[-+]?[0-9]+"))
:start program
:rules ((--> factor
(alt ident
number
(seq "(" expression ")")))
(--> number (alt integer real))
(--> term
factor (rep (alt "*" "/") factor))
(--> expression
(opt (alt "+" "-"))
term
(rep (alt "+" "-") term))
(--> condition
(alt (seq "odd" expression)
(seq expression
(alt "=" "#" "<" "<=" ">" ">=")
expression)))
(--> statement
(opt (alt (seq ident ":=" expression)
(seq "call" ident)
(seq "begin" statement
(rep ";" statement)
"end")
(seq "if" condition "then" statement)
(seq "while" condition "do" statement))))
(--> block
(opt "const" ident "=" number
(rep "," ident "=" number) ";")
(opt "var" ident (rep "," ident) ";")
(rep "procedure" ident ";" block ";")
statement)
(--> program
block ".")))
(assert (equal (com.informatimago.rdp.example-without-action:parse-example-without-action
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
'(program (block (("const" "const" 5) (ident "abc" 11) ("=" "=" 15) (number (integer "123" 17)) ((("," "," 20) (ident "pi" 32) ("=" "=" 34) (number (real "3.141592e+0" 35)))) (";" ";" 46)) (("var" "var" 53) (ident "a" 57) ((("," "," 58) (ident "b" 59)) (("," "," 60) (ident "c" 61))) (";" ";" 62)) ((("procedure" "procedure" 69) (ident "gcd" 79) (";" ";" 82) (block nil nil nil (statement (("begin" "begin" 89) (statement (("while" "while" 104) (condition ((expression nil (term (factor (ident "a" 110)) nil) nil) ("#" "#" 112) (expression nil (term (factor (ident "b" 114)) nil) nil))) ("do" "do" 116) (statement (("begin" "begin" 128) (statement (("if" "if" 147) (condition ((expression nil (term (factor (ident "a" 150)) nil) nil) ("<" "<" 151) (expression nil (term (factor (ident "b" 152)) nil) nil))) ("then" "then" 154) (statement ((ident "b" 159) (":=" ":=" 160) (expression nil (term (factor (ident "b" 162)) nil) ((("-" "-" 163) (term (factor (ident "a" 164)) nil)))))))) (((";" ";" 166) (statement (("if" "if" 182) (condition ((expression nil (term (factor (ident "a" 185)) nil) nil) (">" ">" 186) (expression nil (term (factor (ident "b" 187)) nil) nil))) ("then" "then" 189) (statement ((ident "a" 194) (":=" ":=" 195) (expression nil (term (factor (ident "a" 197)) nil) ((("-" "-" 198) (term (factor (ident "b" 199)) nil)))))))))) ("end" "end" 210))))) nil ("end" "end" 219)))) (";" ";" 222))) (statement (("begin" "begin" 224) (statement ((ident "a" 235) (":=" ":=" 236) (expression nil (term (factor (number (integer "42" 238))) nil) nil))) (((";" ";" 240) (statement ((ident "b" 246) (":=" ":=" 247) (expression nil (term (factor (number (real "30.0" 249))) nil) nil)))) ((";" ";" 253) (statement (("call" "call" 259) (ident "gcd" 264))))) ("end" "end" 268)))) ("." "." 271))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
| 9,679 | Common Lisp | .lisp | 187 | 39.502674 | 1,809 | 0.444878 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bcbbd82ddd69585a286c3ce6cef7861d3c81009d501ce834211f77e1d6c95fed | 4,857 | [
-1
] |
4,858 | scratch.lisp | informatimago_lisp/small-cl-pgms/rdp/scratch.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(com.informatimago.rdp.example:parse-example
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
(com.informatimago.rdp.example-without-action:parse-example-without-action
"
const abc = 123,
pi=3.141592e+0;
var a,b,c;
procedure gcd;
begin
while a # b do
begin
if a<b then b:=b-a ;
if a>b then a:=a-b
end
end;
begin
a:=42;
b:=30.0;
call gcd
end.")
| 761 | Common Lisp | .lisp | 38 | 13.894737 | 74 | 0.545328 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f126241d5f4144c6da5f311d5d4f6d63307be1827148d88d08842f32734f549a | 4,858 | [
-1
] |
4,860 | geek-day.lisp | informatimago_lisp/small-cl-pgms/geek-day/geek-day.lisp | ;;;;****************************************************************************
;;;;FILE: geek-day.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: UNIX
;;;;USER-INTERFACE: UNIX
;;;;DESCRIPTION
;;;; This programs plays geek-day
;;;; http://ars.userfriendly.org/cartoons/?id=20021215
;;;;USAGE
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon
;;;;MODIFICATIONS
;;;; 2002-12-15 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; Copyright Pascal J. Bourguignon 2002 - 2002
;;;;
;;;; This script is free software; you can redistribute it and/or
;;;; modify it under the terms of the GNU General Public
;;;; License as published by the Free Software Foundation; either
;;;; version 2 of the License, or (at your option) any later version.
;;;;
;;;; This script 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 library; see the file COPYING.LIB.
;;;; If not, write to the Free Software Foundation,
;;;; 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(ql:quickload "split-sequence")
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.GEEK-DAY"
(:nicknames "GEEK-DAY")
(:use "COMMON-LISP" "SPLIT-SEQUENCE")
(:documentation "This programs plays geek-day.
<http://ars.userfriendly.org/cartoons/?id=20021215>")
(:export
"PLAY-GEEK-DAY" "MAIN"
;; low-level:
"PLAYER" "LOST" "UPDATE-SANITY" "UPDATE-POPULARITY" "HAVE-BREAKFAST"
"HAVE-SHOWER" "CHOOSE-BACKWARD-OR-FORWARD" "RANDOMIZER" "*SQUARE-LIST*"
"GEEK-DAY" "INITIALIZE" "PLAY"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.GEEK-DAY")
(defgeneric lost (a))
(defgeneric update-sanity (a b))
(defgeneric update-popularity (a b))
(defgeneric have-breakfast (a))
(defgeneric have-shower (a))
(defgeneric choose-backward-or-forward (a))
(defgeneric play (a))
(defgeneric landing (a b c d))
(defgeneric take-off (a b c d))
(defgeneric initialize (a))
(defclass player ()
((name
:initform "Unnamed Player"
:initarg :name
:accessor name
:type string
:documentation "This player's name.")
(popularity
:initform 5
:initarg :popularity
:accessor popularity
:type integer
:documentation "This player's popularity.")
(sanity
:initform 5
:initarg :sanity
:accessor sanity
:type integer
:documentation "This player's sanity.")
(have-had-breakfast
:initform nil
:initarg :have-had-breakfast
:accessor have-had-breakfast
:type (or nil t)
:documentation "This player have had a breakfast.")
(have-had-shower
:initform nil
:initarg :have-had-shower
:accessor have-had-shower
:type (or nil t)
:documentation "This player have had a shower."))
(:documentation "A Player at Geek-Day."))
(defmethod lost ((self player))
(or (<= (popularity self) 0)
(<= (sanity self) 0)))
(defmethod update-sanity ((self player) increment)
(setf (sanity self) (+ (sanity self) increment))
(format t " Your sanity is ~[increased~;decreased~] by ~A.~%"
(if (< increment 0) 1 0) (abs increment))
(if (<= (sanity self) 0)
(format t " YOU GO POSTAL AND LOSE!~%~%")))
(defmethod update-popularity ((self player) increment)
(setf (popularity self) (+ (popularity self) increment))
(format t " Your popularity is ~[increased~;decreased~] by ~A.~%"
(if (< increment 0) 1 0) (abs increment))
(if (<= (popularity self) 0)
(format t " YOU'RE FIRED!~%~%")))
(defmethod have-breakfast ((self player))
(setf (have-had-breakfast self) t))
(defmethod have-shower ((self player))
(setf (have-had-shower self) t))
(defmethod choose-backward-or-forward ((self player))
(format t "~%~A, please choose backward or forward? " (name self))
(finish-output *standard-output*)
(do ((rep (read-line) (read-line)))
((or (string-equal rep "backward")
(string-equal rep "forward"))
(string-equal rep "backward"))
(format t "~%Becareful! Next time, pop-1!~&~A, ~
please choose backward or forward? "
(name self))))
(defvar random-state (make-random-state t))
(defun randomizer ()
(1+ (random 6 random-state)))
;;("title" (before) (after))
(defparameter *square-list*
'(
("Starting blocks."
nil
(lambda (square dice player)
(declare (ignore player))
(format t "~& Therefore ~A."
(if (<= 5 dice) "get out of bed" "keep sleeping"))
(if (<= 5 dice)
(+ dice square)
square)))
("Ungum your eyes." ( (popularity +1) ) nil)
("Get a hot shower." ( (popularity +3)
(lambda (player)
(have-shower player)) ) nil)
("Depilate." ( (popularity +1) ) nil)
("Get a breakfast." ( (sanity +3)
(lambda (player)
(have-breakfast player)) ) nil)
("Catch the bus." ( (sanity -1) (popularity -1) ) nil)
("Oooh... Brain Engages."
nil
(lambda (square dice player)
(if (choose-backward-or-forward player)
(- square dice)
(+ square dice))))
("Arrive \"late\"." ( (popularity +1) (sanity -1) ) nil)
("First problem of the day." ( (popularity -2) (sanity -3) ) nil)
("Called into meeting." ( (sanity -4) ) nil)
("Boss in bad mood." ( (popularity -2) ) nil)
("Water cooler break." ( (lambda (player)
(unless (have-had-shower player)
(update-popularity player -3))) ) nil)
("Caffeine break!" ( (sanity +3) ) nil)
("Caffeine break!" ( (sanity +3) ) nil)
("Co-worker gives you the blame."
( (popularity +2) ) nil)
("Nap." ( (sanity +4) (popularity -2) ) nil)
("Wooo! A thought!"
nil
(lambda (square dice player)
(if (choose-backward-or-forward player)
(- square dice)
(+ square dice))))
("Chair breaks." ( (popularity +2) (sanity -1) ) nil)
("Machine locks up." ( (sanity -2) ) nil)
("Power outage." ( "It's okay, you're safe here." ) nil)
("Munchies!" ( (lambda (player)
(unless (have-had-breakfast player)
(update-sanity player -2))) ) nil)
("Caffeine run." ( (popularity +1) ) nil)
("Sugar run." ( (sanity +1) ) nil)
("Co-worker takes credit." ( (sanity -3) ) nil)
("Run to the loo." ( (sanity +1) ) nil)
("Collapse on the couch at home."
("It's over. Start again tomorrow.")
(lambda (square dice player)
(declare (ignore square dice player))
0))))
(defclass geek-day nil
((board
:initform (make-array (length *square-list*) :initial-contents *square-list*)
:initarg :board
:accessor board
:documentation "The array of square compounding the game.")
(players
:initform nil
:initarg :players
:accessor players
:documentation "The list of Player objects.")
(markers
:initform nil
:accessor markers
:documentation "A list of cons (player . square-index)."))
(:documentation "A Geek-Day game."))
(defmethod play ((self geek-day))
(do ()
((null (markers self)))
;; let's run a turn.
(dolist (marker (markers self))
;; let's run a player.
(let* ((player (car marker))
(square (cdr marker))
(square-data (aref (board self) square))
)
(setf (cdr marker) (take-off self player square square-data))
(setq square (cdr marker))
(setq square-data (aref (board self) square))
(landing self player square square-data)
)) ;;dolist
(setf (markers self)
(delete-if (lambda (item) (lost (car item))) (markers self)))
(let ((lineform "~:(~20A~) ~16A ~16A ~16A~%"))
(format t "~%~%")
(format t lineform "--------------------"
"----------------" "----------------" "----------------")
(format t lineform "Name" "Popularity" "Sanity" "Square")
(format t lineform "--------------------"
"----------------" "----------------" "----------------")
(dolist (player (players self))
(format t lineform (name player) (popularity player) (sanity player)
(if (lost player) "Lost" (cdr (assoc player (markers self)))))
) ;;dolist
(format t lineform "--------------------"
"----------------" "----------------" "----------------"))))
(defmacro square-name (square-data) `(car ,square-data))
(defmacro square-in (square-data) `(cadr ,square-data))
(defmacro square-out (square-data) `(caddr ,square-data))
(defun lambdap (item)
(and (consp item) (eq 'lambda (car item))))
(defmacro lamcall (lambda-expr &rest arguments)
`(funcall (coerce ,lambda-expr 'function) ,@arguments))
(defmethod landing ((self geek-day) player square square-data)
(declare (ignore square))
(format t "~%~%~:(~A~): ~A~%"
(name player) (square-name square-data))
(dolist (action (square-in square-data))
(cond
((null action))
((stringp action) (format t " ~A~%" action) )
((lambdap action) (lamcall action player) )
((eq 'popularity (car action)) (update-popularity player (cadr action)) )
((eq 'sanity (car action)) (update-sanity player (cadr action)) )
(t (error "Invalid action in square-in ~W." action)))))
(defmethod take-off ((self geek-day) player square square-data)
(let ((dice (randomizer))
(out (square-out square-data)))
(format t "~%~%~:(~A~), you roll" (name player))
(finish-output)
(sleep 2)
(format t " and get ~A.~%" dice)
(finish-output)
(min (1- (length (board self)))
(if out (lamcall out square dice player)
(+ square dice)))))
(defmethod initialize ((self geek-day))
(unless (players self)
(error "Please give me some player with make-instance!"))
(setf (markers self)
(mapcar (lambda (player) (cons player 0)) (players self)))
(dolist (marker (markers self))
;; let's run a player.
(let* ((player (car marker))
(square (cdr marker))
(square-data (aref (board self) square)))
(landing self player square square-data))))
(defun play-geek-day (&rest player-names)
(let ((game (make-instance 'geek-day
:players (mapcar (lambda (name)
(make-instance 'player :name name))
player-names))) )
(declare (type geek-day game))
(initialize game)
(play game)))
(defun main (&rest args)
"
DO: Ask for the names of the players from the terminal
and call PLAY-GEEK-DAY.
"
(declare (ignore args))
(format t "~24%+----------------------------------+~&~
| G E E K - D A Y |~&~
+----------------------------------+~&~
~4%~
Please enter the names of the players, ~
or an empty line to abort: ~&")
(let ((names (split-sequence #\space (read-line) :remove-empty-subseqs t)))
(when names
(apply (function play-geek-day) names))))
;;;; THE END ;;;;
| 12,015 | Common Lisp | .lisp | 293 | 34.641638 | 81 | 0.557546 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a348c4491c203c087e0949ed6f14473220f2ad522eb69beaad19ea2dc22ce19d | 4,860 | [
-1
] |
4,861 | irclog.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/irclog.lisp | (defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.IRCLOG"
(:use "COMMON-LISP")
(:documentation "This package fetches new lines from irclogs.")
(:export "GET-NEW-MESSAGES"
"*IRCLOG-BASE-URL*"
"*CHANNELS*"
"*IGNORE-COMMANDS*"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.IRCLOG")
(defvar *irclog-base-url* "https://ccl.clozure.com/irc-logs/")
(defvar *channels* '("lisp") #|'("lisp" "scheme")|#
"A list of channels to fetch from the irclog server.")
(defparameter *ignore-commands* '("joined" "left" "quit"))
(defun log-url (channel)
;; https://ccl.clozure.com/irc-logs/lisp/lisp-2020-10.txt
(multiple-value-bind (se mi ho da month year)
(decode-universal-time (get-universal-time) 0)
(declare (ignore se mi ho da))
(format nil "~A~A/~:*~A-~4,'0D-~2,'0D.txt"
*irclog-base-url* channel year month)))
(defclass cached-resource ()
((url :initarg :url :reader cached-resource-url)
(previous-length :initform 0 :accessor cached-resource-previous-length)
(contents :initform nil :accessor cached-resource-contents)
(headers :initform '() :accessor cached-resource-headers)
(last-modified :initform 0 :accessor cached-resource-last-modified)))
(defmethod fetch-resource ((resource cached-resource))
(multiple-value-bind (contents status headers uri stream do-close reason)
(drakma:http-request (cached-resource-url resource)
:external-format-in :latin-1)
(declare (ignore uri))
(unwind-protect
(if (= status 200)
(setf (cached-resource-previous-length resource) (length (cached-resource-contents resource))
(cached-resource-contents resource) contents
(cached-resource-headers resource) headers)
(error "Could not fetch the resource ~S for ~D ~A~%"
(cached-resource-url resource) status reason))
(when do-close (close stream)))))
(defvar *cached-resources* nil
"maps the channel to the cached resources.")
(defun initialize-cached-resources ()
(let ((table (make-hash-table :test (function equal))))
(dolist (channel *channels* (setf *cached-resources* table))
(fetch-resource
(setf (gethash channel table)
(make-instance 'cached-resource
:url (log-url channel)))))))
(defun third-word (line)
(ignore-errors
(let* ((start (1+ (position #\space line :start (1+ (position #\space line)))))
(end (position #\space line :start start)))
(subseq line start end))))
(defun get-new-messages ()
(unless *cached-resources*
(setf *cached-resources* (initialize-cached-resources)))
(mapcan (lambda (channel)
(let ((resource (gethash channel *cached-resources*)))
(fetch-resource resource)
(let ((lines (subseq (cached-resource-contents resource) (cached-resource-previous-length resource))))
(when (plusp (length lines))
(let ((messages (remove-if
(lambda (line)
(or (zerop (length line))
(member (third-word line) *ignore-commands*
:test (function equal))))
(split-sequence:split-sequence #\newline lines))))
(when messages (list (list channel messages))))))))
*channels*))
;;;; THE END ;;;;
| 3,539 | Common Lisp | .lisp | 69 | 41.202899 | 116 | 0.605894 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f80281d9faf7b515be64fbc6a171808dbe07c206bdd5aeed09b84f608202bcc5 | 4,861 | [
-1
] |
4,862 | scratch.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/scratch.lisp | (install-prompt-functions)
(progn
(let ((resource (gethash "lisp" *cached-resources*)))
(let ((url (cached-resource-url resource))
(start (cached-resource-previous-length resource)))
(multiple-value-bind (contents status headers uri stream do-close reason)
(drakma:http-request url
:external-format-in :latin-1
:keep-alive t :close nil
:range '(0 0))
(declare (ignorable uri))
(let ((end (ignore-errors
(let ((content-range (cdr (assoc :content-range headers))))
(parse-integer content-range :start (1+ (position #\/ content-range)))))))
(if (and (= 206 status) end)
(progn
(multiple-value-setq (contents status headers uri stream do-close reason)
(drakma:http-request url
:external-format-in :latin-1
:range (list start end)))
(unwind-protect
(if (= status 200)
(setf (cached-resource-previous-length resource) end
(cached-resource-headers resource) headers
(cached-resource-contents resource) contents)
(error "Could not fetch the resource ~S for ~D ~A~%"
(cached-resource-url resource) status reason))
(when do-close (close stream))))
(error "Could not fetch length of resource ~S for ~D ~A~%"
(cached-resource-url resource) status reason))))))
(cached-resource-contents (gethash "lisp" *cached-resources*))
(initialize-cached-resources)
(get-new-messages))
(initialize-cached-resources)
(install-prompt-functions)
(cached-resource-contents (gethash "lisp" *cached-resources*))
(get-new-messages)
| 1,952 | Common Lisp | .lisp | 37 | 36.918919 | 95 | 0.54963 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | abed44d06651d49651a9bddef89fc059f76dc61427ae62d27501cf6d388ca9c9 | 4,862 | [
-1
] |
4,863 | swank-slime.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/swank-slime.lisp | (defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.SLIME"
(:use "COMMON-LISP")
(:documentation "This package exports functions to evaluate expressions in emacs thru swank/slime.")
(:export "EVAL-IN-EMACS"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.SLIME")
(defparameter *emacs-readtable*
(let ((rt (copy-readtable)))
(setf (readtable-case rt) :preserve)
(set-syntax-from-char #\> #\) rt)
(set-dispatch-macro-character
#\# #\<
(lambda (stream subchar dispchar)
`(emacs-unreadable ,@(read-delimited-list #\> stream t)))
rt)
;; Probably more readtable patching would be in order.
rt))
;; We could define CLOS proxies for emacs objects for a more seamless
;; integration. swank::eval-in-emacs process the CL form to make it
;; "emacs" (eg. downcase symbols, etc). It could convert CLOS proxies
;; to emacs lisp forms returning the corresponding emacs object.
(defun eval-in-emacs (form &optional nowait)
(let ((result #+swank (swank::eval-in-emacs `(format "%S" ,form) nowait)
#-swank (error "Swank not available"))
(*readtable* *emacs-readtable*))
(with-input-from-string (in result)
(let ((result (read in nil in)))
result))))
;;;; THE END ;;;;
| 1,246 | Common Lisp | .lisp | 28 | 39.785714 | 102 | 0.679636 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7ce285d7e9d0a42d6054fb6307f973e9aa358bdcfe25d1b8d9392a9fb8a8d382 | 4,863 | [
-1
] |
4,864 | main.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/main.lisp | (defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.IRCLOG.MAIN"
(:use "COMMON-LISP")
(:use "COM.INFORMATIMAGO.SMALL-CL-PGMS.IRCLOG"
"COM.INFORMATIMAGO.SMALL-CL-PGMS.PROMPTER")
(:documentation "This package fetches new lines from irclogs,
and displays them before the next prompt.")
(:export "START"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.IRCLOG.MAIN")
(defun display-new-irc-messages ()
(let ((messages (get-new-messages)))
(when messages
(fresh-line)
(loop :for (channel messages) :in messages
:do (loop :for message :in messages
:do (format t "#~A: ~A~%" channel message)))
(force-output))))
(defun start ()
(install-prompt-functions)
(add-prompt-function 'display-new-irc-messages)
(values))
;;;; THE END ;;;;
| 799 | Common Lisp | .lisp | 21 | 33.095238 | 66 | 0.670968 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 87d02d6079e0710466e7852396459f4616079cea45a95ed765fb9f76b0b86218 | 4,864 | [
-1
] |
4,865 | prompter.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/prompter.lisp | (defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.PROMPTER"
(:use "COMMON-LISP")
(:use "COM.INFORMATIMAGO.SMALL-CL-PGMS.SLIME")
(:documentation "This package installs functions to be called before the REPL prompt is displayed.")
(:export "ADD-PROMPT-FUNCTION"
"REMOVE-PROMPT-FUNCTION"
"LIST-PROMPT-FUNCTIONS"
"PROMPT-FUNCTION-ERRORS"
"INSTALL-PROMPT-FUNCTIONS"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.PROMPTER")
(defvar *prompt-functions* '()
"A list of functions to be run before printing the promtp.")
(defvar *prompt-function-errors* '())
(defun ADD-PROMPT-FUNCTION (function)
"Add at the end of the prompt functions list, a new function to be called each time before the prompt is printed."
(setf *prompt-functions* (nconc *prompt-functions* (list function)))
function)
(defun REMOVE-PROMPT-FUNCTION (function)
"Remove an old function from the list of prompt functions."
(setf *prompt-functions* (delete function *prompt-functions*))
function)
(defun LIST-PROMPT-FUNCTIONS ()
"A fresh-list of prompt functions, in the order they're called."
(copy-list *prompt-functions*))
(defun run-prompt-functions (stream)
"Calls each prompt function in turn, with *STANDARD-OUTPUT* bound to STREAM..
Errors are handled and printed.
STREAM is flushed."
(let ((*standard-output* stream))
(dolist (pfun *prompt-functions*)
(handler-case
(funcall pfun)
(error (err)
(force-output *standard-output*)
(format *error-output* "Error while running prompt function ~S:~% ~A~%" pfun err)
(force-output *error-output*)
(remove-prompt-function pfun)
(push (list pfun err) *prompt-function-errors*))))
(finish-output))
(values))
(defun prompt-function-errors ()
(prog1 *prompt-function-errors*
(setf *prompt-function-errors* nil)))
(defvar *prompt-functions-installed* nil)
(defun install-prompt-functions ()
"Installs the prompt functions hook into the implamentation."
(unless *prompt-functions-installed*
;; Note: when using slime/swank, the REPL is implemented by emacs,
;; and the prompt is displayed by emacs.
;; Therefore this feature must be implemented in emacs.
#+swank (progn
(eval-in-emacs
(quote
(defadvice slime-repl-insert-prompt
(before slime-repl-insert-prompt/run-prompt-functions last () activate)
(let ((form (ignore-errors
(car (read-from-string
"(cl:let ((rpf (cl:ignore-errors (cl:find-symbol \"RUN-PROMPT-FUNCTIONS\" \"COM.INFORMATIMAGO.SMALL-CL-PGMS.PROMPTER\")))) (cl:when rpf (cl:funcall rpf cl:*standard-output*)))"
)))))
(when form
(slime-eval form))))
)))
;; We still hook in the prompt for *inferior-lisp*,
;; and for the normal case (terminal):
;; For ccl, we cannot use the *read-loop-function* since once we're
;; inside the loop, this hook is not used anymore (it's used when
;; starting a new REPL). Therefore we have to patch print-listener-prompt.
#+ccl (let ((ccl::*warn-if-redefine-kernel* nil))
(eval
'(defun ccl::print-listener-prompt (stream &optional (force t))
(unless ccl::*quiet-flag*
(when (or force (not (eq ccl::*break-level* ccl::*last-break-level*)))
(run-prompt-functions stream)
(let ((ccl::*listener-indent* nil))
(fresh-line stream)
(format stream ccl::*listener-prompt-format* ccl::*break-level*))
(setf ccl::*last-break-level* ccl::*break-level*)))
(force-output stream))))
#+sbcl (let ((old-prompt-fun sb-int:*repl-prompt-fun*))
(setf sb-int:*repl-prompt-fun*
(lambda (stream)
(if (null stream)
old-prompt-fun
(progn
(run-prompt-functions stream)
(force-output stream)
(funcall old-prompt-fun stream)
(finish-output stream))))))
#-(or ccl sbcl)
(error "~S is not implemented yet for ~A"
'install-prompt-functions (lisp-implementation-type))
(setf *prompt-functions-installed* t)))
#-(and)
(progn
(setf *prompt-functions-installed* nil
#+sbcl sb-int:*repl-prompt-fun* #+sbcl (function com.informatimago.pjb::prompt))
(install-prompt-functions))
#-(and)
(progn
(pop (LIST-PROMPT-FUNCTIONS))
(REMOVE-PROMPT-FUNCTION 'com.informatimago.small-cl-pgms.irclog.main::display-new-irc-messages)
(REMOVE-PROMPT-FUNCTION 'common-lisp-user::date)
(add-PROMPT-FUNCTION 'com.informatimago.small-cl-pgms.irclog.main::display-new-irc-messages)
(add-PROMPT-FUNCTION 'common-lisp-user::date))
;;;; THE END ;;;;
| 5,053 | Common Lisp | .lisp | 105 | 38.371429 | 213 | 0.620024 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | fcff6102f6756c4b1bc5bdea9ce3db3853b68fe1feec484bd8619e7bd68366e3 | 4,865 | [
-1
] |
4,866 | loader.lisp | informatimago_lisp/small-cl-pgms/irclog-prompter/loader.lisp |
(pushnew #P"~/src/public/lisp/small-cl-pgms/irclog-prompter/" asdf:*central-registry* :test (function equalp))
(ql:quickload "com.informatimago.small-cl-pgms.irclog")
(require :cocoa)
| 185 | Common Lisp | .lisp | 3 | 60.333333 | 110 | 0.767956 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 9a38a9ed2795be4228989d90e46a37b7303bac8412ff6e4ba408c66a99c92f7f | 4,866 | [
-1
] |
4,867 | m-expression.lisp | informatimago_lisp/small-cl-pgms/m-expression/m-expression.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: m-expression.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Here is a M-expression parser.
;;;;
;;;; A lot of lisp newbies ask for more conventionnal syntax for lisp.
;;;; Since day one, lisp was intended to have such a syntax: M-expressions.
;;;;
;;;; Let's newbies play with them, and realize how impractical they are.
;;;; Note for example, that we cannot use macros anymore because
;;;; their syntax would need to be known by the M-expression parser,
;;;; like it's the case for lambda[[...];...].
;;;; Macros were added later in lisp history.
;;;;
;;;;
;;;; Note that S-expressions can still be entered, as literal objects,
;;;; but using comma instead of space to separate the items in lists.
;;;;
;;;;
;;;; http://www.informatimago.com/develop/lisp/small-cl-pgms/aim-8/
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-09-28 <PJB> Created.
;;;;BUGS
;;;;
;;;; Symbols are restricted to alphanumeric characters.
;;;; This prevents using a lot of Common Lisp symbols.
;;;; A more modern syntax for M-expressions could be designed,
;;;; but this wasn't the point of the exercise.
;;;;
;;;; In my old transcription of AIM-8, I've used two characters to write
;;;; the arrows: ⎯⟶, but in this parser, the first is not accepted,
;;;; and arrows must be written either as: ⟶ or as ->.
;;;; A new version of the transcription only uses ⟶.
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.COMMON-LISP.M-EXPRESSION"
(:nicknames "M-EXPR")
(:use "COMMON-LISP")
(:export "READ-M-EXPRESSION" "PARSE-M-EXPRESSION" "LABEL" "COMBINE"
"*LOAD-STREAM*" "M-EXPRESSION"
"DRIVER" "DEFINE-M-FUNCTION"
"M-REPL"
"QUIT" "EXIT" "CONTINUE"))
(defpackage "M-LISP-USER"
(:use "COMMON-LISP")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.M-EXPRESSION"
"LABEL" "COMBINE" "QUIT" "EXIT" "CONTINUE"))
(in-package "COM.INFORMATIMAGO.COMMON-LISP.M-EXPRESSION")
;; To load this utf-8 file, specify the utf-8 external format:
;; (load"m-expression.lisp" :external-format #+clisp charset:utf-8 #+sbcl :utf-8)
;; or convert it first to ASCII...
;; The S-functions have been described by a class of expres-
;; sions which has been informally introduced. Let us call these
;; expressions F-expressions. If we provide a way of translating
;; F-expressions into S-expressions, we can use S-functions to
;; repreent certain functions and predicates of S-expressions.
;; First we shall describe this translation.
;; 3.1 Representation of S-functions as S-expressions.
;; The representation is determined by the following rules.
;; 1. Constant S-expressions can occur as parts of the
;; F-expressions representing S-functions. An S-expression ℰ is
;; represented by the S-expression. (QUOTE,ℰ)
;; 2. Variables and function names which were represented
;; by strings of lower case letters are represented by the cor-
;; responding strings of the corresponding upper case letters.
;; Thus we have FIRST, REST and COMBINE, and we shall use X,Y
;; etc. for variables.
;; 3. A form is represented by an S-expression whose first
;; term is the name of the main funcntion and whose remaining terms
;; are the argumetns of the function. Thus combin[first[x];
;; rest[x]] is represented by (COMBINE,(FIRST,X),(REST,X))
;; 4. The null S-expression ⋀ is named NIL.
;; 5. The truth values 1 and 0 are denoted by T and F.
;; The conditional expressoin
;; write[p₁⎯⟶e₁,p₂⎯⟶e₂,...pk⎯⟶ek]
;; is repersented by
;; (COND,(p₁,e₁),(p₂,e₂),...(pk,ek))
;; 6. λ[[x;..;s];ℰ] is represented by (LAMBDA,(X,...,S),ℰ)
;; 7. label[α;ℰ] is represented by (LABEL,α,ℰ)
;; 8. x=y is represented by (EQ,X,Y)
;; With these conventions the substitution function mentioned
;; earlier whose F-expression is
;; label[subst;λ[[x;y;s];[null[s]⎯⟶⋀;atom[s]⎯⟶
;; [y=s⎯⟶x;1⎯⟶s];1⎯⟶combine[subst[x;y;first[s]];
;; subst[x;y;rest[s]]]]]]
;; is represented by the S-expression.
;; (LABEL,SUBST,(LAMBDA,(X,Y,Z),(COND,((NULL,
;; Z),NIL),((ATOM,Z),(COND)((EQ,Y,Z),X),(1,Z))),
;; (1,(COMBINE,(SUBST,X,Y,(FIRST,Z)),
;; (SUBST,X,Y,(REST,Z))))))
(defun read-s-number (stream)
(let ((sign +1)
(int 0)
(ch (read-char stream nil nil)))
(case ch
((#\+) (setf ch (read-char stream nil nil)))
((#\-) (setf ch (read-char stream nil nil)) (setf sign -1)))
(loop
:while (and ch (digit-char-p ch))
:do (setf int (+ (* 10 int) (digit-char-p ch))
ch (read-char stream nil nil)))
(case ch
((nil) `(:s-integer ,(* sign int)))
((#\.) (let ((frac 0.0)
(weight 0.1))
(loop
:initially (setf ch (read-char stream nil nil))
:while (and ch (digit-char-p ch))
:do (setf frac (+ frac (* weight (digit-char-p ch)))
weight (/ weight 10)
ch (read-char stream nil nil)))
(case ch
((nil) `(:s-float ,(* sign (+ int frac))))
((#\E) (let ((exps +1)
(expo 0))
(setf ch (read-char stream nil nil))
(case ch
((#\+)
(setf ch (read-char stream nil nil)))
((#\-)
(setf ch (read-char stream nil nil))
(setf exps -1)))
(loop
:while (and ch (digit-char-p ch))
:do (setf expo (+ (* 10 expo) (digit-char-p ch))
ch (read-char stream nil nil)))
(when ch (unread-char ch stream))
`(:s-float ,(* sign
(+ int frac)
(expt 10.0 (* exps expo))))))
(otherwise (unread-char ch stream)
(if (alpha-char-p ch)
(error "Invalid token at ~S"
(read-line stream nil nil))
`(:s-float ,(* sign (+ int frac))))))))
(otherwise
(unread-char ch stream)
(if (alpha-char-p ch)
(error "Invalid token at ~S" (read-line stream nil nil))
`(:s-integer ,(* sign int)))))))
(defun m-sym-first-char-p (ch)
(find ch "abcdefghijklmnopqrstuvwxyz" :test (function char=)))
(defun m-sym-follow-char-p (ch)
(find ch "abcdefghijklmnopqrstuvwxyz0123456789" :test (function char=)))
(defun s-sym-first-char-p (ch)
(find ch "ABCDEFGHIJKLMNOPQRSTUVWXYZ" :test (function char=)))
(defun s-sym-follow-char-p (ch)
(find ch "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" :test (function char=)))
(defun read-m-symbol (stream)
(loop
:with buffer = (make-array 16 :adjustable t :fill-pointer 0
:element-type 'character)
:for ch = (read-char stream nil nil)
:while (and ch (m-sym-follow-char-p ch))
:do (vector-push-extend ch buffer)
:finally (when ch (unread-char ch stream))
(return `(:m-symbol ,(intern buffer "M-LISP-USER")))))
(defun read-s-symbol (stream)
(loop
:with buffer = (make-array 16 :adjustable t :fill-pointer 0
:element-type 'character)
:for ch = (read-char stream nil nil)
:while (and ch (s-sym-follow-char-p ch))
:do (vector-push-extend ch buffer)
:finally (when ch (unread-char ch stream))
(return `(:s-symbol ,(intern buffer "M-LISP-USER")))))
(defun skip-spaces (stream)
(loop
:with ch = (read-char stream nil nil)
:while (and ch (find ch #(#\space #\newline #\tab
#\return #\linefeed
;; #\vt
)))
:do (setf ch (read-char stream nil nil))
:finally (when ch (unread-char ch stream))))
(defun get-token (stream)
(skip-spaces stream)
(let ((ch (read-char stream nil nil)))
(case ch
((nil) '(:eof))
((#\[) '(:m-open))
((#\]) '(:m-close))
((#\⟶) '(:m-arrow))
((#\⋀) '(:m-symbol |nil|))
((#\λ) '(:m-symbol |lambda|))
((#\;) '(:m-sep))
((#\=) '(:m-equal))
((#\() '(:s-open))
((#\)) '(:s-close))
((#\,) '(:s-sep))
((#\+) (read-s-number stream))
((#\-)
(let ((ch (peek-char nil stream nil nil)))
(case ch
((nil) (error "Invalid character '-' at ~S"
(read-line stream nil nil)))
((#\>)
(read-char stream)
'(:m-arrow))
((#\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(unread-char ch stream)
(read-s-number stream))
(otherwise (error "Invalid character '-' at ~S"
(read-line stream nil nil))))))
(otherwise
(unread-char ch stream)
(cond
((digit-char-p ch)
(read-s-number stream))
((m-sym-first-char-p ch) (let ((sym (read-m-symbol stream)))
(case (second sym)
((m-lisp-user::|nil|) '(:m-nil))
((m-lisp-user::|t|) '(:m-true))
((m-lisp-user::|f|) '(:m-false))
(otherwise sym))))
((s-sym-first-char-p ch) (read-s-symbol stream))
(t (error "Invalid character '~C' at ~S"
ch (read-line stream nil nil))))))))
(defvar *test-source* "")
(defun test-scanner ()
(with-input-from-string (input *test-source*)
(loop
:for token = (get-token input)
:do (print token)
:until (eq :eof (first token)))))
;; (test-scanner)
(defstruct parser current-token stream)
(defun advance (parser)
(setf (parser-current-token parser) (get-token (parser-stream parser))))
(defun token-p (token parser)
(eql token (first (parser-current-token parser))))
;; m-expr ::= m-eq | m-term .
;; m-eq ::= m-term m-equal m-term .
;; m-term ::= m-var | m-call | m-cond | s-expr | m-lambda-list .
;; m-lambda-list ::= m-lambda '[' '[' m-pars ']' ';' m-expr ']' .
;; m-pars ::= | m-pars-items .
;; m-pars-items ::= m-symbol | m-symbol ';' m-pars-items .
;; m-var ::= m-symbol .
;; m-function ::= m-symbol | m-lambda-list .
;; m-call ::= m-function '[' m-args ']' .
;; m-args ::= | m-arg-item .
;; m-arg-items ::= m-expr | m-expr ' ;' m-args .
;; m-cond ::= '[' m-clauses ']' .
;; m-clauses ::= | m-clause-items .
;; m-clause-items ::= m-clause | m-clause ';' m-clauses .
;; m-clause ::= m-expr m-arrow m-expr .
;; s-expr ::= s-atom | '(' s-list ')' .
;; s-list ::= | s-list-items .
;; s-list-items ::= s-expr | s-expr ',' s-list-items .
;; s-atom ::= s-symbol | s-integer | s-float | s-string .
;; m-lambda ::= 'lambda' .
;; m-nil ::= 'nil' .
;; m-true ::= 't' .
;; m-false ::= 'f' .
;; m-equal ::= '=' .
;; m-arrow ::= '->' .
;; m-symbol ::= "[a-z][a-z0-9]*" .
;; s-symbol ::= "[A-Z][A-Z0-9]*" .
;; s-integer ::= "[-+]?[0-9]+" .
;; s-float ::= "[-+]?[0-9]+.[0-9]+(E[-+]?[0-9]+)?" .
(defun parse-m-expr (parser)
;; m-expr ::= m-eq | m-term .
;; m-eq ::= m-term m-equal m-term .
(if (token-p :eof parser)
:eof
(let ((term1 (parse-m-term parser)))
(if (token-p :m-equal parser)
(progn (advance parser)
(let ((term2 (parse-m-term parser)))
`(equal ,term1 ,term2)))
term1))))
(defun m-to-s-symbol (m-symbol)
(intern (string-upcase (second m-symbol)) "M-LISP-USER"))
(defun parse-m-args (parser)
;; m-args ::= | m-arg-item .
;; m-arg-items ::= m-expr | m-expr ' ;' m-args .
(unless (token-p :m-close parser)
(loop
:collect (parse-m-expr parser)
:while (token-p :m-sep parser)
:do (advance parser))))
(defun parse-m-pars (parser)
;; m-pars ::= | m-pars-items .
;; m-pars-items ::= m-symbol | m-symbol ';' m-pars-items .
(unless (token-p :m-close parser)
(loop
:collect (parse-m-expr parser)
:while (token-p :m-sep parser)
:do (advance parser))))
(defun parse-m-clause (parser)
;; m-clause ::= m-expr m-arrow m-expr .
(let ((antecedent (parse-m-expr parser))
(consequent (progn
(if (token-p :m-arrow parser)
(advance parser)
(error "Expected an arrow in m-clause, not ~S~% at ~S~
(check your brackets)"
(parser-current-token parser)
(read-line (parser-stream parser) nil nil)))
(parse-m-expr parser))))
`(,antecedent ,consequent)))
(defun parse-m-clauses (parser)
;; m-clauses ::= m-clause | m-clause ';' m-clauses .
(loop
:collect (parse-m-clause parser)
:while (token-p :m-sep parser)
:do (advance parser)))
(defmacro with-parens ((parser open close) &body body)
(let ((vparser (gensym)) (vopen (gensym)) (vclose (gensym)))
`(let ((,vparser ,parser)
(,vopen ,open)
(,vclose ,close))
(unless (token-p ,vopen ,vparser)
(error "Expected ~A, not ~S~% at ~S" ,vopen
(parser-current-token ,vparser)
(read-line (parser-stream ,vparser) nil nil)))
(advance ,vparser)
(prog1 (progn ,@body)
(if (token-p ,vclose ,vparser)
(advance ,vparser)
(error "Expected ~A, not ~S~% at ~S" ,vclose
(parser-current-token ,vparser)
(read-line (parser-stream ,vparser) nil nil)))))))
(defun parse-m-term (parser)
;; m-term ::= m-var | m-call | m-cond | s-expr | m-lambda-list .
(cond
((token-p :m-open parser) ; m-cond
(with-parens (parser :m-open :m-close)
`(cond ,@(parse-m-clauses parser))))
((token-p :s-open parser) ; S-expr
`(quote ,(parse-s-expr parser)))
((or (token-p :s-symbol parser)
(token-p :s-integer parser)
(token-p :s-float parser)
(token-p :s-string parser))
(prog1
`(quote ,(second (parser-current-token parser)))
(advance parser)))
((or (token-p :m-symbol parser) ; M-expr
(token-p :m-nil parser)
(token-p :m-true parser)
(token-p :m-false parser)) ; m-var or m-call
(let* ((name (parser-current-token parser))
(sname (cond
((or (token-p :m-false parser)
(token-p :m-nil parser)) 'nil)
((token-p :m-true parser) 't)
(t (m-to-s-symbol name)))))
(advance parser)
(if (token-p :m-open parser)
(with-parens (parser :m-open :m-close)
(if (eql 'lambda sname)
`(lambda ,(with-parens (parser :m-open :m-close)
(parse-m-pars parser))
,(progn (unless (token-p :m-sep parser)
(error "Expected a semi-colon, not ~S~% at ~S"
(parser-current-token parser)
(read-line (parser-stream parser) nil nil)))
(advance parser)
(parse-m-expr parser)))
`(,sname ,@(parse-m-args parser))))
sname)))
(t (error "Unexpected token in m-term: ~S~% at ~S"
(parser-current-token parser)
(read-line (parser-stream parser) nil nil)))))
(defun parse-s-list (parser)
;; s-list ::= | s-list-items .
;; s-list-items ::= s-expr | s-expr [','] s-list-items .
;; We make comma optional since later m-expression programs (like AIM-16)
;; didn't use it...
(unless (token-p :s-close parser)
(loop
:until (token-p :s-close parser)
:collect (parse-s-expr parser)
:do (when (token-p :s-sep parser) (advance parser)))))
(defun parse-s-expr (parser)
;; s-expr ::= s-atom | '(' s-list ')' .
;; s-atom ::= s-symbol | s-integer | s-float | s-string .
(cond
((token-p :s-open parser)
(with-parens (parser :s-open :s-close)
(parse-s-list parser)))
((or (token-p :s-symbol parser)
(token-p :s-integer parser)
(token-p :s-float parser)
(token-p :s-string parser))
(prog1 (second (parser-current-token parser))
(advance parser)))
(t (error "Unexpected token in a s-expr: ~S~% at ~S"
(parser-current-token parser)
(read-line (parser-stream parser) nil nil)))))
(defparameter *test-source* "
label[subst;λ[[x;y;s];[null[s]->nil;atom[s]⟶
[y=s->x;1->s];1->combine[subst[x;y;first[s]];
subst[x;y;rest[s]]]]]]
=
(LABEL,SUBST,(LAMBDA,(X,Y,Z),(COND,((NULL,
Z),NIL),((ATOM,Z),(COND,((EQ,Y,Z),X),(1,Z))),
(1,(COMBINE,(SUBST,X,Y,(FIRST,Z)),
(SUBST,X,Y,(REST,Z)))))))")
(defmacro handling-errors (&body body)
`(handler-case (progn ,@body)
(simple-condition
(err)
(format *error-output* "~&~A: ~%" (class-name (class-of err)))
(apply (function format) *error-output*
(simple-condition-format-control err)
(simple-condition-format-arguments err))
(format *error-output* "~&")
(finish-output))
(condition
(err)
(format *error-output* "~&~A: ~% ~S~%"
(class-name (class-of err)) err)
(finish-output))))
(defun m-repl (&key ((input *standard-input*) *standard-input*)
((output *standard-output*) *standard-output*))
(let ((parser (make-parser :stream *standard-input*))
(*package* (find-package "M-LISP-USER")))
(loop
:named repl
:for history :from 1
:do (progn
(format t "~%~A[~D]M-REPL> " (package-name *package*) history)
(finish-output)
(handling-errors
(advance parser)
(setf - (parse-m-expr parser))
(unless (token-p :m-sep parser)
(error "Please terminate your m-expressions with a semi-colon, ~
not ~S" (parser-current-token parser)))
(when (or (eq - :eof) (member - '((quit)(exit)(continue))
:test (function equalp)))
(return-from repl))
(let ((results (multiple-value-list (eval -))))
(setf +++ ++ ++ + + -
/// // // / / results
*** ** ** * * (first /)))
(format t "~& --> ~{~S~^ ;~% ~}~%" /)
(finish-output))))))
(defun test-parser ()
(assert (eql :eof (with-input-from-string (src "")
(let ((parser (make-parser :stream src)))
(advance parser)
(parse-m-expr parser)))))
(with-input-from-string (src *test-source*)
(let ((parser (make-parser :stream src)))
(advance parser)
(parse-m-expr parser))))
(defun read-m-expression (&optional (*standard-input* *standard-input*))
(let ((parser (make-parser :stream *standard-input*)))
(advance parser)
(parse-m-expr parser)))
(defun parse-m-expression (text &key (start 0) (end nil))
(let ((index nil))
(values
(with-input-from-string (src text :index index :start start :end end)
(read-m-expression src))
index)))
(defmacro label (name lambda-expression)
`(defun ,name ,(cadr lambda-expression) ,@(cddr lambda-expression)))
(defun combine (a d) (cons a d))
(defmacro define-m-function (mexp &optional docstring)
(let ((sexp (parse-m-expression mexp)))
(if (and (consp sexp)
(eq 'equal (first sexp)))
`(defun ,(first (second sexp)) ,(rest (second sexp))
,@(when docstring (list docstring))
,@(rest (rest sexp)))
(progn
(error "M-exp is not a definition: ~%~A~%~S~%" mexp sexp)))))
(defun driver (&optional (*standard-input* *standard-input*))
(loop
:for form = (read-m-expression)
:until (eq :eof form)
:do (print (eval
(if (and (consp form) (eq 'equal (car form)))
(if (consp (second form))
`(defun ,(first (second form)) ,(rest (second form))
,@(rest (rest form)))
`(defparameter ,(second form) ,(third form)))
form))))
(values))
(defvar *load-stream* nil
"A string of m-expressions, while loaded by M-EXPRESSION.")
(defun m-expression (mexp)
(with-input-from-string (*load-stream* mexp)
(driver *load-stream*)))
;; (load "/net/users/pjb/src/public/small-cl-pgms/m-expression/m-expression.lisp" :external-format charset:utf-8) (use-package :com.informatimago.common-lisp.m-expression)
| 22,928 | Common Lisp | .lisp | 516 | 35.389535 | 171 | 0.52128 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c2be5e2cb57e1de55bafe33a253c814f768487048b32d1ce26a99852e93211aa | 4,867 | [
-1
] |
4,868 | brainfuck.lisp | informatimago_lisp/small-cl-pgms/brainfuck/brainfuck.lisp | ;;;; -*- mode:lisp; coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: bf.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Brainfuck emulator
;;;; -1- A Brainfuck Virtual Machine COMPLETE
;;;; -2- A Brainfuck to Lisp *optimizing* compiler COMPLETE
;;;; -3- Implementing a lisp in Brainfuck sketches
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2005-09-11 <PJB> Created
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2005 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BRAINFUCK"
(:use "COMMON-LISP")
#+mocl (:shadowing-import-from "COM.INFORMATIMAGO.MOCL.KLUDGES.MISSING"
"*TRACE-OUTPUT*"
"*LOAD-VERBOSE*"
"*LOAD-PRINT*"
"ARRAY-DISPLACEMENT"
"CHANGE-CLASS"
"COMPILE"
"COMPLEX"
"ENSURE-DIRECTORIES-EXIST"
"FILE-WRITE-DATE"
"INVOKE-DEBUGGER" "*DEBUGGER-HOOK*"
"LOAD"
"LOGICAL-PATHNAME-TRANSLATIONS"
"MACHINE-INSTANCE"
"MACHINE-VERSION"
"NSET-DIFFERENCE"
"RENAME-FILE"
"SUBSTITUTE-IF"
"TRANSLATE-LOGICAL-PATHNAME"
"PRINT-NOT-READABLE"
"PRINT-NOT-READABLE-OBJECT")
(:export "BFVM" "MAKE-BFVM" "BFVM-MEM" "BFVM-MC" "BFVM-PGM" "BFVM-PC")
(:export "BFLOAD" "BFVM-RUN")
(:export "BFCOMPILE-FILE" "BFCOMPILE" "*BFCOMPILE*")
(:export "BFEVAL"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BRAINFUCK")
;;;----------------------------------------------------------------------
;;; -1- A Brainfuck Virtual Machine
;;;----------------------------------------------------------------------
(defconstant +bfsize+ 30000)
(defstruct bfvm
(mem (make-array +bfsize+ :element-type '(unsigned-byte 8) :initial-element 0))
(mc 0)
(pgm "" :type string)
(pc 0))
(defun find-matching-close (pgm pc inc opn cls)
(incf pc inc)
(loop
with level = 0
until (and (zerop level)
(or (< pc 0)
(<= (length pgm) pc)
(char= cls (char pgm pc))))
do
;; (print `(level ,level pc ,pc @pc ,(char pgm pc)))
(cond ((char= opn (char pgm pc)) (incf level))
((char= cls (char pgm pc)) (decf level)))
(incf pc inc)
finally (return pc)))
(defun bfload (file)
"Return a string containing the file"
(with-open-file (in file)
(let ((pgm (make-string (file-length in))))
(subseq pgm 0 (read-sequence pgm in)))))
(defun bfvm-run (vm &key verbose)
(let* ((mem (bfvm-mem vm))
(mc (bfvm-mc vm))
(pgm (bfvm-pgm vm))
(pc (bfvm-pc vm))
(lpgm (length pgm))
(lmem (length mem)))
(macrolet ((in-range-p (counter limit) `(< -1 ,counter ,limit)))
(unwind-protect
(loop while (and (in-range-p pc lpgm) (in-range-p mc lmem)) do
(when verbose
(format *trace-output*
"PC:~5,'0D IR:~C M[~5,'0D]:~2,'0X ~:*~4@A ~4@A ~C~%"
pc
(if (char= (char pgm pc) #\newline)
#\space
(char pgm pc))
mc
(aref mem mc)
(if (<= 128 (aref mem mc))
(- (aref mem mc) 256)
(aref mem mc))
(if (graphic-char-p (code-char (aref mem mc)))
(code-char (aref mem mc))
#\space))
(force-output *trace-output*))
(case (char pgm pc)
(#\> (incf mc)
(incf pc))
(#\< (decf mc)
(incf pc))
(#\+ (setf (aref mem mc) (mod (1+ (aref mem mc)) 256))
(incf pc))
(#\- (setf (aref mem mc) (mod (1- (aref mem mc)) 256))
(incf pc))
(#\. (princ (code-char (aref mem mc)))
(incf pc))
(#\, (setf (aref mem mc) (mod (char-code (read-char)) 256))
(incf pc))
(#\[ (if (zerop (aref mem mc))
(setf pc (find-matching-close pgm pc +1 #\[ #\]))
(incf pc)))
(#\] (if (zerop (aref mem mc))
(incf pc)
(setf pc (find-matching-close pgm pc -1 #\] #\[))))
(otherwise (incf pc))))
(setf (bfvm-mc vm) mc
(bfvm-pc vm) pc))))
(values))
(defun test-vm ()
(time (bfvm-run (make-bfvm :pgm (bfload "99botles.bf")) :verbose nil)))
;;;----------------------------------------------------------------------
;;; -2- A Brainfuck to Lisp *optimizing* compiler
;;;----------------------------------------------------------------------
(defun bfparse (pgm)
(loop
with result = '()
with stack = '()
for ch across pgm
do (case ch
(#\> (push '(%forward 1) result))
(#\< (push '(%backward 1) result))
(#\+ (push '(%inc 1 0) result))
(#\- (push '(%dec 1 0) result))
(#\, (push '(%readc 0) result))
(#\. (push '(%princ 0) result))
(#\[ (push result stack)
(setf result (list '%while-nz)))
(#\] (setf result (cons (nreverse result) (pop stack)))))
finally (progn (when stack (error "Missing closing brackets"))
(return-from bfparse (nreverse result)))))
(defmacro %forward (offset)
`(incf mc ,offset))
(defmacro %backward (offset)
`(decf mc ,offset))
(defmacro %inc (value offset)
`(setf (aref mem (+ mc ,offset))
(mod (+ (aref mem (+ mc ,offset)) ,value) 256)))
(defmacro %dec (value offset)
`(setf (aref mem (+ mc ,offset))
(mod (- (aref mem (+ mc ,offset)) ,value) 256)))
(defmacro %readc (offset)
`(setf (aref mem (+ mc ,offset)) (mod (char-code (read-char)) 256)))
(defmacro %princ (offset)
`(princ (code-char (aref mem (+ mc ,offset)))))
(defmacro %while-nz (&body body)
(let ((lbeg (gensym "LOOP"))
(lend (gensym "ENDL")))
`(tagbody (when (zerop (aref mem mc)) (go ,lend))
,lbeg
,@body
(unless (zerop (aref mem mc)) (go ,lbeg))
,lend)))
(defun bfoptimize-1 (tgm)
(cond
((null tgm) tgm)
((equalp (first tgm) '(%while-nz (%dec 1 0)))
(cons '(%zero 0) (bfoptimize-1 (rest tgm))))
((and (consp (first tgm))
(member (first (first tgm)) '(%forward %backward %inc %dec))
(consp (second tgm))
(eq (first (first tgm)) (first (second tgm))))
(loop
for rtgm on (rest tgm)
with sum = (second (first tgm))
while (and (consp (first rtgm))
(eq (first (first tgm)) (first (first rtgm))))
do (incf sum (second (first rtgm)))
finally (return (cons (list (first (first tgm)) sum)
(bfoptimize-1 rtgm)))))
((and (consp (first tgm)) (eq (first (first tgm)) '%while-nz))
(cons (cons '%while-nz (bfoptimize-1 (rest (first tgm))))
(bfoptimize-1 (rest tgm))))
(t (cons (first tgm) (bfoptimize-1 (rest tgm))))))
(defmacro %zero (offset)
`(setf (aref mem (+ mc ,offset)) 0))
(defun bfoptimize-2 (tgm)
(cond
((null tgm) tgm)
((equal (first tgm) '(%zero 0))
(cond
((and (consp (second tgm))
(eq (first (second tgm)) '%inc))
(cons (list '%set (second (second tgm))) (bfoptimize-2 (cddr tgm))))
((and (consp (second tgm))
(eq (first (second tgm)) '%dec))
(cons (list '%set (- (second (second tgm)))) (bfoptimize-2 (cddr tgm))))
(t (cons '(%set 0) (bfoptimize-2 (cdr tgm))))))
((and (consp (first tgm))
(eq (first (first tgm)) '%dec))
(cons (list '%inc (- (second (first tgm)))) (bfoptimize-2 (rest tgm))))
((and (consp (first tgm))
(eq (first (first tgm)) '%backward))
(cons (list '%offset (- (second (first tgm)))) (bfoptimize-2 (rest tgm))))
((and (consp (first tgm))
(eq (first (first tgm)) '%forward))
(cons (list '%offset (second (first tgm))) (bfoptimize-2 (rest tgm))))
((and (consp (first tgm)) (eq (first (first tgm)) '%while-nz))
(cons (cons '%while-nz (bfoptimize-2 (rest (first tgm))))
(bfoptimize-2 (rest tgm))))
(t (cons (first tgm) (bfoptimize-2 (rest tgm))))))
(defmacro %set (value offset)
`(setf (aref mem (+ mc ,offset)) (mod ,value 256)))
(defmacro %offset (offset)
`(incf mc ,offset))
(defun bfoptimize-3-offset (tgm)
(loop
with result = '()
with offset = 0
for item in tgm
do (case (first item)
((%offset)
(incf offset (second item)))
((%inc %set)
(push `(,(first item) ,(second item) ,offset) result))
((%readc %princ)
(push `(,(first item) ,(+ (second item) offset)) result))
(otherwise (error "unexpected item ~A" item)))
finally
(unless (zerop offset) (push `(%offset ,offset) result))
(return (nreverse result))))
(defun bfoptimize-3 (tgm)
(let ((end (position '%while-nz tgm :key (function first))))
(if end
(nconc (bfoptimize-3-offset (subseq tgm 0 end))
(cons (cons '%while-nz (bfoptimize-3 (rest (elt tgm end))))
(bfoptimize-3 (subseq tgm (1+ end)))))
(bfoptimize-3-offset tgm))))
;;; Uncomment these macros to trace the compiled forms:
;;
;; (defmacro %forward (offset)
;; `(progn (incf mc ,offset)
;; (print `(forward ,,offset --> mc = ,mc))))
;;
;; (defmacro %backward (offset)
;; `(progn (decf mc ,offset)
;; (print `(backward ,,offset --> mc = ,mc))))
;;
;; (defmacro %inc (value offset)
;; `(progn (setf (aref mem (+ mc ,offset))
;; (mod (+ (aref mem (+ mc ,offset)) ,value) 256))
;; (print `(inc ,,value ,,offset --> (aref mem ,(+ mc ,offset)) = ,(aref mem (+ mc ,offset))))))
;;
;; (defmacro %dec (value offset)
;; `(progn (setf (aref mem (+ mc ,offset))
;; (mod (- (aref mem (+ mc ,offset)) ,value) 256))
;; (print `(dec ,,value ,,offset --> (aref mem ,(+ mc ,offset)) = ,(aref mem (+ mc ,offset))))))
;;
;; (defmacro %readc (offset)
;; `(progn (setf (aref mem (+ mc ,offset)) (mod (char-code (read-char)) 256))
;; (print `(readc ,,offset --> (aref mem ,(+ mc ,offset)) = ,(aref mem (+ mc ,offset))))))
;;
;; (defmacro %princ (offset)
;; `(progn (princ (code-char (aref mem (+ mc ,offset))))
;; (print `(princ ,,offset --> (aref mem ,(+ mc ,offset)) = ,(aref mem (+ mc ,offset))))))
;;
;; (defmacro %while-nz (&body body)
;; (let ((lbeg (gensym "LOOP"))
;; (lend (gensym "ENDL")))
;; `(tagbody
;; (print `(while-nz ,',lbeg begin (aref mem ,mc) = ,(aref mem mc)))
;; (when (zerop (aref mem mc)) (go ,lend))
;; ,lbeg
;; ,@body
;; (print `(while-nz ,',lbeg loop (aref mem ,mc) = ,(aref mem mc)))
;; (unless (zerop (aref mem mc)) (go ,lbeg))
;; ,lend)))
;;
;; (defmacro %zero (offset)
;; `(progn (setf (aref mem (+ mc ,offset)) 0)
;; (print `(zero ,offset --> (aref mem ,(+ mc offset)) = ,(aref mem (+ mc offset))))))
;;
;; (defmacro %set (value offset)
;; `(progn (setf (aref mem (+ mc ,offset)) (mod ,value 256))
;; (print `(set ,,value ,,offset --> (aref mem ,(+ mc ,offset)) = ,(aref mem (+ mc ,offset))))))
;;
;; (defmacro %offset (offset)
;; `(progn (incf mc ,offset)
;; (print `(offset ,,offset --> mc = ,mc))))
(defvar *bfcompile* nil
"When true, bfcompile compiles also the generated Lisp code.")
(defun bfcompile (pgm &key name ((:compile *bfcompile*) *bfcompile*))
"
PGM: a string containing the source of a Brainfuck program.
RETURN: a lisp function taking a virtual machine
(only the memory and MC register are used),
and realizing the same program.
"
(flet ((do-compile (lambda-form) (compile name lambda-form))
(do-eval (lambda-form) (eval (if name
`(defun ,name (vm) (,lambda-form vm))
lambda-form))))
(funcall (if *bfcompile*
(function do-compile)
(function do-eval))
`(lambda (vm)
(let ((mem (bfvm-mem vm))
(mc (bfvm-mc vm)))
(unwind-protect
(progn
,@(bfoptimize-3
(bfoptimize-2
(bfoptimize-1
(bfparse pgm)))))
(setf (bfvm-mc vm) mc)))))))
(defun bfcompile-file (file &key ((:compile *bfcompile*) *bfcompile*))
"Combines bfcompile and bfload."
(bfcompile (bfload file) :compile *bfcompile*))
(defun test-compiler ()
(time (funcall (bfcompile-file "99botles.bf")
(make-bfvm)))
(time (funcall (bfcompile-file "99botles.bf" :compile t)
(make-bfvm))))
;;;----------------------------------------------------------------------
;;; -3- Implementing a lisp in Brainfuck
;;;----------------------------------------------------------------------
;; lisp primitives:
;; () eq cons car cdr atom quote cond lambda
;;
;; lisp registers stored in brainfuck memory:
;; | 0 , sph , spl , sph , spl | 1 , hph , hpl , hph , hpl |
;; | 2 , ach , acl , ach , acl |
(defconstant +max-addr+ (1- (truncate +bfsize+ 5)))
(defconstant +sc+ 1)
(defconstant +sp+ 2 "stack pointer")
(defconstant +hp+ 3 "heap pointer")
(defconstant +ix+ 4 "")
(defconstant +ac+ 5 "accumulator a")
(defconstant +bc+ 6 "accumulator b")
(defconstant +ts+ 7)
(defconstant +cn+ 8)
(defconstant +min-addr+ 9)
(defun store-imm-to-car (n)
(format nil ">[-]~A>[-]~A<<"
(make-string (truncate n 256) :initial-element #\+)
(make-string (mod n 256) :initial-element #\+)))
(defun store-imm-to-cdr (n)
(format nil ">>>[-]~A>[-]~A<<<<"
(make-string (truncate n 256) :initial-element #\+)
(make-string (mod n 256) :initial-element #\+)))
(defun move-from-to (from to)
(if (< to from)
(make-string (* 5 (- from to)) :initial-element #\<)
(make-string (* 5 (- to from)) :initial-element #\>)))
;; sp = (car 0) ; initially = 5999 = +max-addr+ = bfsize/5-1
;; hp = (cdr 0) ; initially = 2
;; ac = 1
(defvar *simplify* t)
(defun simplify (bf)
;; delete all occurences of "><" "<>" "+-" "-+"
;;(print `(simplify ,bf))
(if *simplify*
(loop
with changed = t
while changed
do (labels
((simplify-couple (couple start)
(let ((pos (search couple bf :start2 start)))
(cond
(pos
(loop
with l = (1- pos)
with r = (+ pos (length couple))
while (and (< start l)
(< r (length bf))
(char= (char couple 0) (char bf l))
(char= (char couple (1- (length couple)))
(char bf r)))
do (setf changed t) (decf l) (incf r)
finally
(incf l)
;; (print `(delete ,(subseq bf l r)))
;; (print `(left ,(subseq bf start l)))
(return (concatenate 'string
(subseq bf start l)
(simplify-couple couple r)))))
((zerop start)
;; (print `(result ,bf))
bf)
(t
;; (print `(right ,(subseq bf start)))
(subseq bf start))))))
(setf changed nil)
(setf bf (simplify-couple "<>" 0))
(setf bf (simplify-couple "><" 0))
(setf bf (simplify-couple "+-" 0))
(setf bf (simplify-couple "-+" 0))
)
finally (return bf))
bf))
(defmacro defbf (name args &body body)
"
Defines a lisp function that will generate brainfuck code translated
from the body. The body itself consists in other functions defined
with defbf, or strings containing brainfuck instructions.
"
(let ((vout (gensym)))
`(defun ,name ,args
(simplify (with-output-to-string (,vout)
,@(mapcar (lambda (item) `(princ ,item ,vout)) body))))))
(defmacro repeat (repcnt &body body)
(let ((vout (gensym)))
`(with-output-to-string (,vout)
(loop :repeat ,repcnt
:do ,@(mapcar (lambda (item) `(princ ,item ,vout)) body)))))
(defmacro while-nz (&body body)
(let ((vout (gensym)))
`(with-output-to-string (,vout)
(princ "[" ,vout)
,@(mapcar (lambda (item) `(princ ,item ,vout)) body)
(princ "]" ,vout))))
(defmacro progbf (&body body)
(let ((vout (gensym)))
`(with-output-to-string (,vout)
,@(mapcar (lambda (item) `(princ ,item ,vout)) body))))
(defmacro letbf (bindings &body body)
(let ((vout (gensym)))
`(with-output-to-string (,vout)
(let ,bindings
,@(mapcar (lambda (item) `(princ ,item ,vout)) body)))))
(defbf previous () "<<<<<")
(defbf next () ">>>>>")
(defbf rewind () (while-nz (previous)))
(defbf backward-0 () (while-nz (previous)))
(defbf forward-0 () (while-nz (next)))
(defbf backward-1 () "-" (while-nz "+" (previous) "-") "+")
(defbf forward-1 () "-" (while-nz "+" (next) "-") "+")
(defbf forward-1-set () "-" (while-nz "++" (next) "-") "+")
(defbf goto (dst) (rewind) (move-from-to 0 dst))
(defbf clear-byte () (while-nz "-"))
(defbf set-byte () (while-nz "-") "+")
(defbf clear-cons ()
">" (clear-byte) ">" (clear-byte) ">" (clear-byte) ">" (clear-byte) "<<<<")
(defbf format-memory ()
(rewind) (clear-byte)
(repeat +max-addr+ (next) "+")
(rewind) (next)
(store-imm-to-car 0) (store-imm-to-car 0) (next) ; sc
(store-imm-to-car +max-addr+) (store-imm-to-cdr 0) (next) ; sp
(store-imm-to-car +min-addr+) (store-imm-to-cdr 0) (next) ; hp
(rewind))
(defun dump-memory (vm)
(loop
with mem = (bfvm-mem vm)
for addr to +max-addr+
do (when (zerop (mod addr 5)) (format t "~%~4,'0X: " addr))
(format t "~2,'0X ~2,'0X~2,'0X ~2,'0X~2,'0X "
(aref mem (+ (* 5 addr) 0))
(aref mem (+ (* 5 addr) 1))
(aref mem (+ (* 5 addr) 2))
(aref mem (+ (* 5 addr) 3))
(aref mem (+ (* 5 addr) 4)))
finally (format t "~%")))
(defbf move-cdr-to-car ()
">>>" (while-nz "-<<+>>") ">" (while-nz "-<<+>>") "<<<<")
(defbf copy-reg-byte (src dst)
(while-nz "-"
(move-from-to src +sc+) "+" ; copy src to +sc+
(move-from-to +sc+ dst) "+" ; copy src to dst
(move-from-to dst src)) ; and back to src
(move-from-to src +sc+)
(while-nz "-"
(move-from-to +sc+ src) "+" ; copy +sc+ to src
(move-from-to src +sc+))
(move-from-to +sc+ src))
(defbf copy-reg (src dst)
(goto +sc+) (clear-cons)
(move-from-to +sc+ dst) (clear-cons)
(move-from-to dst src)
">" (copy-reg-byte src dst)
">" (copy-reg-byte src dst)
">" (copy-reg-byte src dst)
">" (copy-reg-byte src dst)
"<<<<") ; back to src position
(defbf null-car (reg)
(copy-reg reg +ts+)
(goto +ts+)
">" (while-nz "<" (clear-byte) ">" (clear-byte)) ; set mark if nz
">" (while-nz "<<" (clear-byte) ">>" (clear-byte)) ; set mark if nz
"<<" (while-nz ">>+<<-") ; move flag to lsb of car
"+") ; set mark
(defbf not-null-car (reg)
(copy-reg reg +ts+)
(goto +ts+)
(clear-byte)
">" (while-nz "<" (set-byte) ">" (clear-byte)) ; set mark if nz
">" (while-nz "<<" (set-byte) ">>" (clear-byte)) ; set mark if nz
"<<" (while-nz ">>+<<-") ; move flag to lsb of car
"+") ; set mark
(defbf increment-car (reg)
(goto reg)
">>+" ; increment lsb of car
(while-nz ; if lsb is nz
"<<" (clear-byte) ; clear mark
(previous) (goto 1) ">>" (clear-byte))
"<<" ; goto mark
(previous) ; move away from cleared mark
(goto reg) ; come back
;; mark = 0 <=> lsb is nz ; mark = 1 <=> lsb is z
(while-nz ; mark = 1 ==> lsb is z
">+" ; increment msb of car
"<" (clear-byte)) ; clear mark
"+") ; set mark
(defbf decrement-car (reg)
(goto reg)
">>" ; goto lsb of car
(while-nz ; if lsb is nz
"-" ; decrement it
"<<" (clear-byte) ; clear mark
(previous) (goto +sc+) ">>" (clear-byte))
"<<" ; goto mark
(previous) ; move away from cleared mark
(goto reg) ; come back
;; mark = 0 <=> lsb was nz ; mark = 1 <=> lsb is z
(while-nz ; mark = 1 ==> lsb is z
">->-<<" ; roll over lsb; decrement msb
(clear-byte)) ; clear mark
"+") ; set mark
#-(and)
(defbf goto-indirect (reg)
;; move to address pointed to by (car reg)
(copy-reg reg +cn+)
(repeat +min-addr+
(decrement-car +cn+))
(not-null-car +cn+) ; at +ts+
">>"
(while-nz
"<<" (move-from-to +ts+ +min-addr+)
(forward-1)
"-"
(backward-1)
(decrement-car +cn+)
(not-null-car +cn+) ; at +ts+
">>")
"<<" (move-from-to +ts+ +min-addr+)
(forward-1-set))
(defbf goto-indirect (reg)
;; move to address pointed to by (car reg)
(copy-reg reg +cn+)
(repeat +min-addr+
(decrement-car +cn+))
(goto +cn+)
">>" ;; lsb of cn
(while-nz
"<<" (move-from-to +cn+ +min-addr+)
(forward-1)
"-"
(backward-1)
(goto +cn+) ">>-")
"<" ; msb of cn
(while-nz
"<" (move-from-to +cn+ +min-addr+)
(forward-1)
(repeat 256 "-" (next))
(previous) (backward-1)
(goto +cn+) ">-")
"<" (move-from-to +cn+ +min-addr+)
(forward-1-set) "-")
(defbf copy-byte-forward (offset)
(repeat offset ">")
(while-nz
(repeat offset "<")
(next)
(forward-0)
(repeat offset ">")
"+"
(repeat offset "<")
(previous)
(backward-0)
(repeat offset ">")
"-")
(repeat offset "<"))
(defbf copy-byte-backward (offset)
(repeat offset ">")
(while-nz
(repeat offset "<")
(previous)
(backward-0)
(repeat offset ">")
"+"
(repeat offset "<")
(next)
(forward-0)
(repeat offset ">")
"-")
(repeat offset "<"))
(defbf store-ac (reg)
;; store ac to cons at (car reg)
(goto-indirect reg) (clear-cons) "-" ; clear mark
(previous)
(copy-reg +ac+ +cn+)
(goto +cn+) "-" ; clear mark
(copy-byte-forward 1)
(copy-byte-forward 2)
(copy-byte-forward 3)
(copy-byte-forward 4)
"+" (forward-0) "+") ; set marks.
(defbf load-ac (reg)
;; load ac from cons at (car reg)
(goto-indirect reg) "-" ; clear mark
(previous)
(goto +ac+) (clear-cons) "-" ; clear mark
(next) (forward-0)
(copy-byte-backward 1)
(copy-byte-backward 2)
(copy-byte-backward 3)
(copy-byte-backward 4)
(previous)
(backward-0)
"+" ; set mark
(copy-reg +ac+ +cn+)
(goto +cn+) "-" ; clear mark
(copy-byte-forward 1)
(copy-byte-forward 2)
(copy-byte-forward 3)
(copy-byte-forward 4)
"+" (forward-0) "+") ; set marks.
(defbf push-ac ()
(decrement-car +sp+)
(store-ac +sp+))
(defbf pop-ac ()
(load-ac +sp+)
(increment-car +sp+))
;;;---------------------------------------------------------------------
(defbf test1 (n a d)
(format-memory)
(goto +ac+)
(store-imm-to-car a)
(store-imm-to-cdr d)
(goto +cn+)
(store-imm-to-car n)
(decrement-car +sp+)
(decrement-car +sp+)
(store-ac +sp+)
;;(repeat n (push-ac))
)
(defbf test2 ()
(format-memory)
(goto +ac+)
(store-imm-to-car #x0030)
(store-imm-to-cdr #xbeef)
(goto-indirect +ac+))
;; (copy-reg +sp+ +cn+)
;; (repeat +min-addr+
;; (decrement-car +cn+))
;; (not-null-car +cn+)
;; ">>"
;; ;;(while-nz
;; "<<" (move-from-to +ts+ +min-addr+)
;; (forward-1)
;; "-"
;; (backward-1)
;; (decrement-car +cn+)
;; (not-null-car +cn+) ; at +ts+
;; ">>"
;;
;; "<<" (move-from-to +ts+ +min-addr+)
;; (forward-1)
;; "-"
;; (backward-1)
;; (decrement-car +cn+)
;; (not-null-car +cn+) ; at +ts+
;; ">>"
;; )
;;
;; "<<" (move-from-to +ts+ +min-addr+)
;; (forward-1-set))
;;
;;
;;
;; (goto-indirect reg) (clear-cons) "-" ; clear mark
;; ))
;; (previous)
;; (copy-reg +ac+ +cn+)
;; (goto +cn+) "-" ; clear mark
;; ))
#||
(progn (bfcompile '%test1 (test1 3 #xdead #xbeef))
(setf vm (make-bfvm)) (%test1 vm) (dump-memory vm))
(progn (bfcompile '%test1 (store-ac +sp+)
(setf vm (make-bfvm)) (%test1 vm) (dump-memory vm))
||#
(defvar *vm* nil)
(defun test-lisp/bf-vm ()
(progn (setf *vm* (make-bfvm :pgm (format-memory)))
(bfvm-run *vm* :verbose nil)
(dump-memory *vm*)
(setf (bfvm-pc *vm*) 0
(bfvm-pgm *vm*) (progbf
(goto +ac+)
(store-imm-to-car #xdead)
(store-imm-to-cdr #xbeef)
(push-ac)
(goto +ac+)
(store-imm-to-car #xcafe)
(store-imm-to-cdr #xbabe)
(push-ac)))
(bfvm-run *vm* :verbose nil)
(dump-memory *vm*)))
;; (defun bfeval (sexp env)
;; (cond
;; ((atom sexp) sexp)
;; ((eq (car sexp) 'apply)
;; (apply (function bfapply) (mapcar (function bfeval) (cdr sexp))))
;; ((eq (car sexp) 'define)
;; (
;; (eval '(apply (lambda ()
;; (define sym definition)
;; (define sym definition)
;; (define sym definition)
;; (sym))) ())
;;
;;
;; (defmacro my-defun (name arg-list &body body)
;; `(progn (setf (symbol-function ',name) (lambda ,arg-list (progn ,@body)))
;; ',name))
;;
;;
;; (defun my-apply (fun &rest effective-arg-list)
;; (let* ((lambda-exp (function-lambda-expression fun))
;; (formal-arg-list (cadr lambda-exp))
;; (sexp (caddr lambda-exp)))
;; (if (eq 'lambda (car lambda-exp))
;; ;; let's skip the argument binding
;; (my-eval sexp)
;; ;; a primive function
;; (funcall (function apply) fun effective-arg-list))));;my-apply
;;
;;
;; (defun symbol-value (symbol env)
;; (cond ((null env) :unbound)
;; ((eq symbol (car (car env))) (cdr (car env)))
;; (t (symbol-value symbol (cdr env)))))
;;
;;
;; (defun my-eval (sexp env)
;; (cond
;; ((symbolp sexp) (symbol-value sexp env))
;; ((atom sexp) sexp)
;; ((eq (car sexp) 'quote) (car (cdr sexp)))
;; ((eq (car sexp) 'if) (if (my-eval (car (cdr sexp)))
;; (my-eval (car (cdr (cdr sexp))))
;; (my-eval (car (cdr (cdr (cdr sexp)))))))
;; ((setq) (setf (symbol-value (cadr sexp)) (my-eval (caddr sexp))))
;; ((rplaca) (rplaca (my-eval (cadr sexp)) (my-eval (caddr sexp))))
;; ((progn)
;; (my-eval (cadr sexp))
;; (if (cddr sexp) (my-eval (cons 'progn (cddr sexp)))))
;; (otherwise
;; (my-apply (symbol-function (car sexp))
;; (mapcar (function my-eval) (cdr sexp))))))));;my-eval
;;
;;
;; (my-defun a-fun () (setq x '(1 2 3)) (print x) (rplaca x 0) (print x))
;; (bfcompile(bfload "99botles.bf") :name '99b) (|99B| (make-bfvm))
#||
(test-vm)
(test-compiler)
(test-lisp/bf-vm)
||#
(defun bfeval (bfcode)
(check-type bfcode string)
(funcall (com.informatimago.small-cl-pgms.brainfuck:bfcompile bfcode)
(com.informatimago.small-cl-pgms.brainfuck:make-bfvm)))
;; Local Variables:
;; eval: (cl-indent 'defbf 2)
;; End:
| 30,416 | Common Lisp | .lisp | 801 | 30.730337 | 107 | 0.482975 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 059a8de64722ec2813de10734124e9508a94ff77e02af9233e485e3752dd2a12 | 4,868 | [
-1
] |
4,869 | brainfuck-test.lisp | informatimago_lisp/small-cl-pgms/brainfuck/brainfuck-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: bf-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Test bf.lisp
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-02-23 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BRAINFUCK.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.SMALL-CL-PGMS.BRAINFUCK")
(:export "TEST/ALL"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BRAINFUCK.TEST")
(define-test test/all ()
:success)
;;;; THE END ;;;;
| 1,756 | Common Lisp | .lisp | 44 | 38.318182 | 83 | 0.608187 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 28ab12eb855f06fa8513afd8432b6d5ee3e661321fd747624aca2a643252586d | 4,869 | [
-1
] |
4,870 | simple-symbol.lisp | informatimago_lisp/small-cl-pgms/brainfuck/simple-symbol.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defparameter bf$symbols '())
(defun bf$intern (name)
(let ((ass (assoc name bf$symbols :test (function equal))))
(if ass
(cdr ass)
(let ((sym (cons :$symbol (list :pname name))))
(setf bf$symbols (cons (cons name sym) bf$symbols))
sym))))
(defun bf$set (sym value)
(let ((slot (member :value (cdr sym))))
(if slot
(setf (cadr slot) value)
(setf (cdr sym) (list* :value value (cdr sym))))
value))
(defun bf$symbol-value (sym)
(let ((slot (member :value (cdr sym))))
(when slot
(cadr slot))))
(bf$intern "CAR")
(bf$intern "ASSOC")
(bf$set (bf$intern "X") 42)
(bf$symbol-value (bf$intern "X"))
(bf$symbol-value (bf$intern "ASSOC"))
(bf$symbol-value (bf$intern "Y"))
(bf$set (bf$intern "X") 24)
(bf$symbol-value (bf$intern "X"))
bf$symbols
| 927 | Common Lisp | .lisp | 29 | 27.724138 | 61 | 0.617117 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | ea5c44017c947ddd2cb78a55c2e551d4aa0be94347937eb345e4447fe2e72897 | 4,870 | [
-1
] |
4,871 | generate-application.lisp | informatimago_lisp/small-cl-pgms/botil/generate-application.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: generate-application.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Save the botil executable.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-04-27 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2015
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(progn (format t "~%;;; Loading quicklisp.~%") (finish-output) (values))
(load #P"~/quicklisp/setup.lisp")
(progn (format t "~%;;; Loading botil.~%") (finish-output) (values))
(push (make-pathname :name nil :type nil :version nil
:defaults *load-truename*) asdf:*central-registry*)
(ql:quickload :com.informatimago.small-cl-pgms.botil)
#+ccl (pushnew 'com.informatimago.common-lisp.interactive.interactive:initialize
ccl:*restore-lisp-functions*)
(progn (format t "~%;;; Saving hotihn.~%") (finish-output) (values))
;; This doesn't return.
#+ccl (ccl::save-application
"botil"
:mode #o755 :prepend-kernel t
:toplevel-function (function com.informatimago.small-cl-pgms.botil:main)
:init-file nil ;; "~/.botil.lisp"
:error-handler :quit)
| 2,288 | Common Lisp | .lisp | 52 | 41.519231 | 83 | 0.61828 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e9a60a86b3eb37907604251a0489e78e031f915b8ff08ddde23caeb94c4612ad | 4,871 | [
-1
] |
4,872 | botil.lisp | informatimago_lisp/small-cl-pgms/botil/botil.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: botil.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: IRC
;;;;DESCRIPTION
;;;;
;;;; Botil: an IRC bot monitoring Hacker News.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-07-17 <PJB> Added commands: help uptime version sources; added restarts.
;;;; 2015-04-27 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2015
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COMMON-LISP-USER")
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(declaim (declaration also-use-packages))
(declaim (also-use-packages "UIOP" "CL-IRC" "MONTEZUMA"))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL"
(:use "COMMON-LISP"
"CL-JSON" "DRAKMA" "SPLIT-SEQUENCE" "BORDEAUX-THREADS"
"CL-DATE-TIME-PARSER" "CL-PPCRE" "CL-SMTP"
"COM.INFORMATIMAGO.RDP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SEQUENCE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.LISP-SEXP.SOURCE-FORM"
"COM.INFORMATIMAGO.CLEXT.QUEUE")
(:shadow "LOG")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.INTERACTIVE.INTERACTIVE"
"DATE" "UPTIME")
(:export
"MAIN"
;; -- admin commands
"*INITIAL-SERVER*" "INITIALIZE-DATABASE")
(:documentation "
Botil is a simple IRC logging and log querying bot.
It is run with:
(com.informatimago.small-cl-pgms.botil:main)
Copyright Pascal J. Bourguignon 2016 - 2016
Licensed under the AGPL3.
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL")
(defparameter *version* "1.0.0")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Configuration:
;;;
(defvar *smtp-server* "hubble.informatimago.com")
(defvar *smtp-port* 2526)
(defvar *botil-email* "[email protected]")
(defvar *external-format* :utf-8
"External format used for all files (database files, log files).")
(defvar *initial-server* "irc.freenode.org"
"Only used when creating the database the first time.")
(defvar *default-nickname* "botil"
"The nickname of the botil user.")
(defvar *default-password* "1234"
"The nickname of the botil user.")
(defun find-database ()
(find-if (lambda (dir)
(probe-file (merge-pathnames #P"botil.database" dir nil)))
#(#P"/data/databases/irc/"
#P"/mnt/data/databases/irc/"
#P"/Users/pjb/Documents/irc/")))
(defvar *database* (find-database)
"The pathname to the botil database.")
(defvar *index* nil
"The montezuma index.")
(defvar *sources-url*
"https://gitlab.com/com-informatimago/com-informatimago/tree/master/small-cl-pgms/botil/"
"The URL where the sources of this ircbot can be found.")
(defun index-pathname ()
(make-pathname :name "index" :type "montezuma" :version nil
:defaults *database*))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun compute-deadline (timeout)
(+ (get-internal-real-time)
(* timeout internal-time-units-per-second)))
;; Taken from swank:
(defun format-iso8601-time (time-value &optional include-timezone-p)
"Formats a universal time TIME-VALUE in ISO 8601 format, with
the time zone included if INCLUDE-TIMEZONE-P is non-NIL"
;; Taken from http://www.pvv.ntnu.no/~nsaa/ISO8601.html
;; Thanks, Nikolai Sandved and Thomas Russ!
(flet ((format-iso8601-timezone (zone)
(if (zerop zone)
"Z"
(multiple-value-bind (h m) (truncate (abs zone) 1.0)
;; Tricky. Sign of time zone is reversed in ISO 8601
;; relative to Common Lisp convention!
(format nil "~:[+~;-~]~2,'0D:~2,'0D"
(> zone 0) h (round (* 60 m)))))))
(multiple-value-bind (second minute hour day month year dow dst zone)
(decode-universal-time time-value)
(declare (ignore dow))
(format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0D~:[~*~;~A~]"
year month day hour minute second
include-timezone-p (format-iso8601-timezone
(if dst (+ zone 1) zone))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass server ()
((hostname :initarg :hostname
:initform (error "A server needs a :hostname")
:reader hostname
:type string)
(botnick :initarg :botnick
:initform *default-nickname*
:accessor botnick
:type string
:documentation "The nick of the bot on this server.")
(botpass :initarg :botpass
:initform *default-password*
:accessor botpass
:type (or null string)
:documentation "The password of the bot on this server.")
(enabled :type boolean
:initarg :enabled
:initform t
:accessor enabled
:documentation "Set to false to prevent this server to connect.")
(request-id :initform 0
:initarg :request-id
:type integer)
(channels :initarg :channels
:initform '()
:accessor channels
:type list)
(users :initarg :users
:initform '()
:accessor users
:type list)
(request-index :initform (make-request-index)
:reader request-index)
(last-update :initform (get-universal-time)
:accessor last-update
:type integer)
(connection :initarg :connection
:initform nil
:accessor connection
:type (or null connection))))
(defmethod print-object ((server server) stream)
(print-unreadable-object (server stream :identity nil :type t)
(format stream "~S :enabled ~S :nick ~S :channels ~S :requests-count ~A"
(hostname server)
(enabled server)
(botnick server)
(mapcar (function name) (channels server))
(length (requests server))))
server)
(defclass channel ()
((server :initarg :server
:initform (error "A channel needs a :server")
:reader server
:type server)
(name :initarg :name
:initform (error "A channel needs a :name")
:reader name
:type string)
(log-stream :initform nil
:accessor log-stream
:type (or null file-stream))
(log-stream-write-time :initform (get-universal-time)
:accessor log-stream-write-time
:type integer)
(log-month :initform nil
:accessor log-month
:type (or null integer))))
(defmethod initialize-instance :after ((channel channel) &key &allow-other-keys)
(pushnew channel (channels (server channel))
:key (function name)
:test (function string-equal))) ; channel names are case insensitive.
(defmethod print-object ((channel channel) stream)
(print-unreadable-object (channel stream :identity nil :type t)
(format stream "~A" (name channel)))
channel)
(defclass user ()
((server :initarg :server
:initform (error "A channel needs a :server")
:reader server
:type server)
(name :initarg :name
:initarg :nickname
:initform (error "A user needs a :name")
:reader name
:type string)
(password :initarg :password
:initform nil
:accessor password
:type (or null string))
(email :initarg :email
:initform nil
:accessor email
:type (or null email))
(verified :initarg :verified
:initform nil
:accessor verified
:type boolean)
(key :initarg :key
:initform nil
:accessor key
:type (or null string)
:documentation "Verification key when verified is false;
password setting token when verified is true.")
(identified :initarg :identified
:initform nil
:accessor identified
:type boolean)))
(defmethod print-object ((user user) stream)
(print-unreadable-object (user stream :identity nil :type t)
(format stream "~a@~a~@[ ~A~]~:[~; verified~]"
(name user) (hostname (server user))
(email user) (verified user)))
user)
(defclass request ()
((id :initform 0
:initarg :id
:reader id
:type integer
:documentation "A persistent ID for the request to let the users refer to them easily.
cf. command: cancel log $ID")
(channel :initarg :channel
:initform (error "A log needs a :channel")
:reader channel
:type channel)
(owner :initarg :owner
:initform (error "A request-request needs a :owner")
:reader owner
:type user)
(start-date :initarg :start-date
:initform (get-universal-time)
:reader start-date
:type integer)
(end-date :initarg :end-date
:initform nil
:reader end-date
:type (or null integer))))
(defmethod print-object ((request request) stream)
(print-unreadable-object (request stream :identity nil :type t)
(format stream ":channel ~S :owner ~S :start-date ~A~@[ :end-date ~A~]"
(name (channel request))
(name (owner request))
(format-iso8601-time (start-date request) t)
(and (end-date request) (format-iso8601-time (end-date request) t))))
request)
(defclass message ()
((source :accessor source
:initarg :source
:type (or null string))
(user :accessor user
:initarg :user
:type (or null string))
(host :accessor host
:initarg :host
:type (or null string))
(command :accessor command
:initarg :command
:type (or null string))
(arguments :accessor arguments
:initarg :arguments
:type list)
(received-time :accessor received-time
:initarg :received-time)
(raw-message-string :accessor raw-message-string
:initarg :raw-message-string
:type string)))
(defclass query ()
((owner :initarg :owner
:initform (error "A query needs a :owner")
:reader owner
:type user
:documentation "Who made the request and will receive the results.")
(sender :initarg :sender
:initform nil
:reader sender
:type (or null string))
(channel :initarg :channel
:initform nil
:reader channel
:type (or null channel))
(start-date :initarg :start-date
:initform nil
:reader start-date
:type (or null integer))
(end-date :initarg :end-date
:initform nil
:reader end-date
:type (or null integer))
(criteria :initarg :criteria
:initform nil
:accessor criteria)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *servers* '())
;; (setf *servers* nil)
;; /Users/pjb/Documents/irc/
;; |-- botil.database
;; `-- servers
;; `-- irc.freenode.org
;; |-- channels
;; | `-- #lisp
;; | |-- logs
;; |-- server.sexp
;; |-- requests.sexp
;; `-- users
;; |-- ogam.sexp
;; `-- tbot`.sexp
;;; --------
(defgeneric server-pathname (object)
(:method ((server-name string))
(merge-pathnames (make-pathname :directory (list :relative "servers" server-name)
:name nil :type nil :version nil
:defaults *database*)
*database*))
(:method ((server-name (eql :wild)))
(merge-pathnames (make-pathname :directory (list :relative "servers" :wild)
:name nil :type nil :version nil
:defaults *database*)
*database*))
(:method ((server server))
(server-pathname (hostname server))))
(defgeneric server-datafile-pathname (object)
(:method ((server-name string))
(make-pathname :name "server" :type "sexp" :version nil
:defaults (server-pathname server-name)))
(:method ((server server))
(server-datafile-pathname (hostname server))))
(defgeneric user-pathname (object &optional server)
(:method ((name t) &optional server)
(check-type name (or string (member :wild)))
(assert server (server) "SERVER is needed when calling USER-PATHNAME with a string.")
(let ((serverdir (server-pathname server)))
(merge-pathnames (make-pathname :directory '(:relative "users")
:name name :type "sexp" :version nil
:defaults serverdir)
serverdir nil)))
(:method ((user user) &optional server)
(when server
(assert (eq server (server user))))
(user-pathname (name user) (server user))))
(defgeneric channel-pathname (channel &optional server)
(:method ((channel t) &optional server)
(check-type channel (or string (member :wild)))
(assert server (server) "SERVER is needed when calling USER-PATHNAME with a string.")
(let ((serverdir (server-pathname server)))
(merge-pathnames (make-pathname :directory (list :relative "channels" channel)
:name nil :type nil :version nil
:defaults serverdir)
serverdir)))
(:method ((channel channel) &optional server)
(when server
(assert (eq server (server channel))))
(channel-pathname (name channel) (server channel))))
(defgeneric log-file-pathname (channel &optional month)
(:method ((channel channel) &optional (month (log-month channel)))
(let ((channel-pathname (channel-pathname channel)))
(merge-pathnames (make-pathname :directory '(:relative "logs")
:name (format nil "~6,'0D" month) :type "log" :version nil
:defaults channel-pathname)
channel-pathname nil))))
(defun requests-pathname (server)
(let ((server-pathname (server-pathname server)))
(merge-pathnames (make-pathname :name "requests" :type "sexp" :version nil
:defaults server-pathname)
server-pathname nil)))
;;; --------------------
(defgeneric save (object)
(:method (object) object))
;;; --------------------
;;; server
;;; --------------------
(defun server-data (pathname)
(sexp-file-contents (server-datafile-pathname pathname)
:external-format *external-format*
:if-does-not-exist nil))
(defmethod save ((server server))
(let ((pathname (server-datafile-pathname (hostname server))))
(ensure-directories-exist pathname)
(setf (sexp-file-contents pathname
:external-format *external-format*
:if-does-not-exist :create
:if-exists :supersede)
(list :botnick (botnick server)
:botpassword (botpass server)
:enabled (enabled server)
:request-id (slot-value server 'request-id)
:hostname (hostname server)))
(save-requests server)
server))
(defun create-server (hostname &optional (nick "botil") (password nil))
(check-type hostname string)
(check-type nick string)
(check-type password (or null string))
(let ((server (make-instance 'server
:hostname hostname
:botnick nick
:botpass password
:enabled nil)))
(push server *servers*)
(save server)))
(defgeneric load-channels (server)
(:method ((server server))
(dolist (pathname (directory (channel-pathname :wild server)))
(make-instance 'channel
:server server
:name (first (last (pathname-directory pathname)))))))
(defgeneric save-requests (server)
(:method ((server server))
(setf (sexp-file-contents (requests-pathname server)
:external-format *external-format*)
(mapcar (lambda (request)
(list :id (id request)
:channel (name (channel request))
:owner (name (owner request))
:start-date (start-date request)
:end-date (end-date request)
:server (hostname (server (channel request)))))
(requests server)))))
(defgeneric load-requests (server)
(:method ((server server))
(mapcar (lambda (data)
(request-index-add
(make-instance
'request
:id (getf data :id)
:channel (ensure-channel server
(or (getf data :channel)
(error "Missing channel in request data.")))
:owner (ensure-user server
(or (getf data :owner)
(error "Missing owner in request data.")))
:start-date (getf data :start-date (get-universal-time))
:end-date (getf data :end-date nil))))
(sexp-file-contents (requests-pathname server)
:if-does-not-exist nil
:external-format *external-format*))))
(defun load-server (hostname)
(let ((server (or (find-server hostname)
(let ((data (server-data hostname)))
(make-instance 'server
:hostname hostname
:botnick (getf data :botnick)
:botpass (getf data :botpass)
:enabled (getf data :enabled)
:request-id (getf data :request-id))))))
(load-channels server)
(load-requests server)
server))
(defun load-server-database ()
(setf *servers*
(mapcar (lambda (pathname)
(load-server (first (last (pathname-directory pathname)))))
(directory (server-pathname :wild)))))
(defgeneric find-server (name))
(defmethod find-server ((name string))
(find name *servers* :key (function hostname)
:test (function string-equal)))
(defmethod next-request-id ((server server))
(prog1 (incf (slot-value server 'request-id))
(save server)))
;;; --------------------
;;; channel
;;; --------------------
(defgeneric find-channel (server name)
(:method ((hostname string) (name string))
(find-channel (find-server hostname) name))
(:method ((server server) (name string))
(find name (channels server)
:key (function name)
:test (function string-equal))))
(defgeneric ensure-channel (server name)
(:method ((hostname string) (name string))
(ensure-channel (find-server hostname) name))
(:method ((server server) (name string))
(assert (char= #\# (aref name 0)))
(or (find-channel server name)
(let ((channel (make-instance 'channel :server server :name name)))
(ensure-directories-exist (log-file-pathname channel 201601))
channel))))
(defmethod ensure-log-stream ((channel channel) time)
(multiple-value-bind (se mi ho da mo ye) (decode-universal-time time 0)
(declare (ignore se mi ho da))
(let ((month (+ (* ye 100) mo)))
(unless (eql month (log-month channel))
(when (log-stream channel)
(close (log-stream channel))
(setf (log-stream channel) nil))
(setf (log-month channel) month))
(unless (log-stream channel)
;; TODO: add an open file counter, and when too many, close least recent log file written.
(setf (log-stream channel) (open (log-file-pathname channel)
:external-format *external-format*
:direction :output
:if-does-not-exist :create
:if-exists :append)
(log-stream-write-time channel) (get-universal-time)))))
(log-stream channel))
(defun message-index-add (channel message log-file filepos)
(let ((doc (make-instance 'montezuma:document))
(date (format-iso8601-time (irc:received-time message))))
(montezuma:add-field doc (montezuma:make-field "server" (hostname (server channel)) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "channel" (name channel) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "raw" (irc:raw-message-string message) :stored T :index :tokenized))
(montezuma:add-field doc (montezuma:make-field "source" (irc:source message) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "user" (irc:user message) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "host" (irc:host message) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "command" (irc:command message) :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "contents" (second (irc:arguments message)) :stored T :index :tokenized))
(montezuma:add-field doc (montezuma:make-field "received-time" date :stored T :index :untokenized))
(montezuma:add-field doc (montezuma:make-field "log-file" log-file :stored T :index nil))
(montezuma:add-field doc (montezuma:make-field "log-position" (prin1-to-string filepos) :stored T :index nil))
(montezuma:add-document-to-index *index* doc)))
(defmethod create-message ((channel channel) (ircmsg irc:irc-message))
(ensure-log-stream channel (irc:received-time ircmsg))
(let ((stream (log-stream channel)))
(prin1 (list :source (irc:source ircmsg)
:user (irc:user ircmsg)
:host (irc:host ircmsg)
:command (irc:command ircmsg)
:arguments (irc:arguments ircmsg)
:received-time (irc:received-time ircmsg)
:raw-message-string (irc:raw-message-string ircmsg))
stream)
(terpri stream)
(force-output stream)
(setf (log-stream-write-time channel) (get-universal-time))
(message-index-add channel ircmsg
(enough-namestring (pathname stream) *database*)
(file-position stream))))
;; (setf (log-month (first (channels (first *servers*)))) 201601)
;; (log-file-pathname (first (channels (first *servers*))))
;; (values (first (channels (first *servers*)))
;; (log-month (first (channels (first *servers*))))
;; (log-stream (first (channels (first *servers*))))
;; (ensure-log-stream (first (channels (first *servers*)))
;; (get-universal-time)))
;;; --------------------
;;; user
;;; --------------------
(defmethod save ((user user))
(let ((pathname (user-pathname user)))
(ensure-directories-exist pathname)
(setf (sexp-file-contents pathname
:if-does-not-exist :create
:if-exists :supersede
:external-format *external-format*)
(list :name (name user)
:password (password user)
:email (email user)
:key (key user)
:verified (verified user))))
user)
(defgeneric find-user (server name)
(:method ((hostname string) (name string))
(find-user (find-server hostname) name))
(:method ((server server) (name string))
(or (find name (users server)
:key (function name)
:test (function string-equal))
(let ((data (sexp-file-contents (user-pathname name server)
:if-does-not-exist nil
:external-format *external-format*)))
(when data
(let ((user (apply (function make-instance) 'user
:server server :name name
data)))
(push user (users server))
user))))))
(defgeneric ensure-user (server name)
(:method ((hostname string) (name string))
(ensure-user (find-server hostname) name))
(:method ((server server) (name string))
(assert (and (plusp (length name)) (char/= #\# (aref name 0))))
(or (find-user server name)
(let ((user (apply (function make-instance) 'user
:server server :name name
(sexp-file-contents (user-pathname name server)
:if-does-not-exist nil
:external-format *external-format*))))
(push user (users server))
(save user)))))
;;; --------------------
;;; requests
;;; --------------------
;; [channel]-1------*-[request]-*--------1-[user]
(defclass request-index ()
((all-requests :initform '() :accessor all-requests)
(channel-index :initform (make-hash-table :test (function equalp)) :reader channel-index)
(owner-index :initform (make-hash-table :test (function equalp)) :reader owner-index)))
(defun make-request-index ()
(make-instance 'request-index))
(defun request-index-add (request)
(let ((index (request-index (server (channel request)))))
(push request (all-requests index))
(let* ((name (name (channel request)))
(index (channel-index index))
(serie (or (gethash name index) (setf (gethash name index) (list nil)))))
(push request (cdr serie)))
(let* ((name (name (owner request)))
(index (owner-index index))
(serie (or (gethash name index) (setf (gethash name index) (list nil)))))
(push request (cdr serie)))
request))
(defun request-index-remove (request)
(let ((index (request-index (server (channel request)))))
(deletef (all-requests index) request)
(deletef (cdr (gethash (name (channel request)) (channel-index index) (list nil))) request)
(deletef (cdr (gethash (name (owner request)) (owner-index index) (list nil))) request)
request))
(defmethod create-request ((channel channel) (owner user) &optional start-date end-date)
(let ((request (make-instance 'request :id (next-request-id (server channel))
:channel channel
:owner owner
:start-date (or start-date (get-universal-time))
:end-date end-date)))
(request-index-add request)
(save-requests (server (channel request)))
request))
(defmethod delete-request ((request request))
(request-index-remove request)
(save-requests (server (channel request)))
request)
(defun sorted-serie (serie)
(if (car serie)
(cdr serie)
(setf (car serie) t
(cdr serie) (sort (cdr serie)
(function <)
:key (function start-date)))))
(defgeneric requests (object)
(:method ((server server))
(all-requests (request-index server)))
(:method ((channel channel))
(sorted-serie (gethash (name channel) (channel-index (request-index (server channel))) (list t))))
(:method ((owner user))
(sorted-serie (gethash (name owner) (owner-index (request-index (server owner))) (list t)))))
(defun channel-active-p (channel &optional (date (get-universal-time)))
(check-type channel channel)
(loop :for r :in (requests channel)
:while (and (end-date r) (< (end-date r) date))
:finally (return (and r (<= (start-date r) date)))))
(defun channel-next-start-log-date (channel &optional (date (get-universal-time)))
(check-type channel channel)
(loop :for r :in (requests channel)
:do (cond
((and (end-date r) (< (end-date r) date)))
((and (<= (start-date r) date)
(null (end-date r)))
(return t))
((<= date (start-date r))
(return (start-date r))))
:finally (return nil)))
(defun channel-next-stop-log-date (channel &optional (date (get-universal-time)))
(check-type channel channel)
(loop :for r :in (requests channel)
:do (if (<= (start-date r) date)
(if (end-date r)
(when (<= date (end-date r))
(return (end-date r)))
(return t))
(return nil))
:finally (return nil)))
;;; --------------------
;;; channel display
;;; --------------------
(defgeneric joined-channels (server)
(:method ((server server))
(mapcar (function irc:normalized-name)
(hash-table-values (irc:channels (connection server))))))
(defgeneric wanted-channels (server)
(:method ((server server))
(mapcar (function name)
(remove-if-not (function channel-active-p) (channels server)))))
(defvar *update-period* 20)
(defvar *max-chunk* 5)
(defun at-most (n seq)
(subseq seq 0 (min n (length seq))))
(defun update-channels (server)
(when (< (+ *update-period* (last-update server)) (get-universal-time))
(setf (last-update server) (get-universal-time))
(let* ((wanted (wanted-channels server))
(joined (joined-channels server))
(to-join (at-most *max-chunk* (set-difference wanted joined :test (function string-equal))))
(to-part (at-most *max-chunk* (set-difference joined wanted :test (function string-equal)))))
(when to-join (join server to-join))
(when to-part (part server to-part)))))
;;; --------------------
;;; initialization
;;; --------------------
(defun initialize-database (dbdir-pathname)
"This initialize the empty directory at pathname DBDIR-PATHNAME as a
botil database, and creates the initial server named
*INITIAL-SERVER*.
This should be used only once to create a virgin empty database, and
configure an initial IRC server to which to connect to receive
commands."
(let ((dbfile (merge-pathnames #P"botil.database" dbdir-pathname nil)))
(ensure-directories-exist dbfile)
(when (probe-file dbfile)
(error "A botil database already exists at ~S" dbdir-pathname))
(setf *database* dbdir-pathname)
(with-open-file (out dbfile
:if-does-not-exist :create
:external-format *external-format*)
(write-line ";; -*- mode:lisp -*-" out)
(write-line ";; This directory holds the local botil database." out))
(create-server *initial-server* *default-nickname* *default-password*)))
;;;-----------------------------------------------------------------------------
;;;
;;; Workers
;;;
(defstruct worker
input-queue
send
thread)
(defun send-worker (worker &rest message)
(funcall (worker-send worker) message))
(defun kill-worker (worker)
(funcall (worker-send worker) 'die))
(defmacro make-worker-thread (name message-lambda-list &body body)
(check-type name symbol)
(check-type message-lambda-list list)
(let* ((vmessage (gensym))
(vinput-queue (gensym))
(sname (string name))
(ll (parse-lambda-list message-lambda-list :destructuring))
(pl (make-parameter-list ll)))
`(let ((,vinput-queue (make-queue ,sname)))
(make-worker
:input-queue ,vinput-queue
:send (lambda (,vmessage)
(enqueue ,vinput-queue
(if (eql ,vmessage 'die)
,vmessage
(destructuring-bind ,message-lambda-list ,vmessage
(declare (ignorable ,@pl))
,vmessage))))
:thread (make-thread
(lambda ()
(loop
:for ,vmessage := (dequeue ,vinput-queue)
:until (eql ,vmessage 'die)
:do (handler-bind
((error (lambda (err)
(format *error-output* "~&~A: ~A~%"
',sname err)
#+ccl
(format *error-output*
"~&~80,,,'-<~>~&~{~A~%~}~80,,,'-<~>~&"
(ccl::backtrace-as-list))
nil)))
(flet ((terminate-worker () (loop-finish)))
(block ,name
(destructuring-bind ,message-lambda-list ,vmessage
(declare (ignorable ,@pl))
,@body))))
#-(and) (handler-case
(flet ((terminate-worker () (loop-finish)))
(block ,name
(destructuring-bind ,message-lambda-list ,vmessage
(declare (ignorable ,@pl))
,@body)))
(error (err)
(format *error-output* "~&~A: ~A~%"
',sname err)))))
:name ,sname)))))
;;;-----------------------------------------------------------------------------
;;; Workers
;;;
(defvar *botil*)
(defvar *command-processor*)
(defvar *query-processor*)
(defvar *sender*)
(defvar *logger*)
(defun todo (what)
(format *trace-output* "~&TODO: ~S~%" what))
;;;-----------------------------------------------------------------------------
;;; Sender
;;;-----------------------------------------------------------------------------
(defun send-irc (recipient text)
(check-type recipient (or user channel))
(check-type text string)
(let ((connection (connection (server recipient))))
(when connection
(irc:privmsg connection (name recipient) text))))
(defun send (server recipient message &rest arguments)
(format *trace-output* "~&SENDER :server ~S~%" server)
(format *trace-output* "~&SENDER :recipient ~S~%" recipient)
(format *trace-output* "~&SENDER :message ~S~%" message)
(format *trace-output* "~&SENDER :arguments ~S~%" arguments)
;; TODO: we may want to do better throttling.
(etypecase message
(list
(ecase (first message)
((disconnect)
(sleep 0.5)
(irc:quit (connection server)
(format nil "~A ordered me to quit." (name recipient))))
((part)
(dolist (channel (second message))
(sleep 0.5)
(irc:part (connection server) channel)))
((join)
(dolist (channel (second message))
(sleep 0.5)
(irc:join (connection server) channel)))))
(string
(sleep 0.5)
(let ((message (format nil "~?" message arguments)))
(format *trace-output* "~&SENDER ~A <- ~A~%" recipient message)
(send-irc recipient message)))))
;; TODO: change answer to queue the message thru the *sender* worker.
(defun answer (recipient format-control &rest format-arguments)
(apply (function send-worker) *sender* (server recipient)
recipient format-control format-arguments))
(defun disconnect (server sender)
;; TODO: queue a message for the (server sender) thru the *sender*
;; worker, to disconnect the server when it processes it.
(send-worker *sender* server sender (list 'disconnect)))
(defun join (server channels)
(send-worker *sender* server nil (list 'join channels)))
(defun part (server channels)
(send-worker *sender* server nil (list 'part channels)))
;;;-----------------------------------------------------------------------------
;;; Query processor
;;;-----------------------------------------------------------------------------
(defvar *max-query-results* 10)
(defun query-processor (server sender query)
(check-type server server)
(check-type sender user)
(check-type query string)
(let ((result-no 0))
(block :results
(montezuma:search-each
*index* query
(lambda (num score)
(incf result-no)
(let ((doc (montezuma:get-document *index* num)))
(answer sender "~3D) ~4,2F ~A > ~A : ~A"
result-no score
(montezuma:document-value doc "channel")
(montezuma:document-value doc "source")
(montezuma:document-value doc "contents")))
(when (<= *max-query-results* result-no)
(return-from :results)))))
(when (zerop result-no)
(answer sender "No match."))))
;;;-----------------------------------------------------------------------------
;;; Logger
;;;-----------------------------------------------------------------------------
(defun logger (server message)
(check-type server server)
(check-type message irc:irc-message)
(typecase message
((or irc:irc-privmsg-message
irc:irc-join-message
irc:irc-part-message)
;; irc:irc-privmsg-message
(create-message (find-channel server (first (irc:arguments message))) message))
(t
(format t "~&Will log: ~A~%" (irc:raw-message-string message))
(todo 'logger))))
;;;-----------------------------------------------------------------------------
;;; Command processor
;;;-----------------------------------------------------------------------------
;; nickname = ( letter / special ) *8( letter / digit / special / "-" )
;; letter = %x41-5A / %x61-7A ; A-Z / a-z
;; digit = %x30-39 ; 0-9
;; hexdigit = digit / "A" / "B" / "C" / "D" / "E" / "F"
;; special = %x5B-60 / %x7B-7D ; "[", "]", "\", "`", "_", "^", "{", "|", "}" ;
;;
;; channel = ( "#" / "+" / ( "!" channelid ) / "&" ) chanstring [ ":" chanstring ]
;; chanstring = %x01-07 / %x08-09 / %x0B-0C / %x0E-1F / %x21-2B
;; chanstring =/ %x2D-39 / %x3B-FF ; any octet except NUL, BELL, CR, LF, " ", "," and ":" ;
;; channelid = 5( %x41-5A / digit ) ; 5( A-Z / 0-9 )
;; servername = hostname
;; hostname = shortname *( "." shortname )
;; shortname = ( letter / digit ) *( letter / digit / "-" ) *( letter / digit ) ; as specified in RFC 1123 [HNAME] ;
(defun nicknamep (word)
(and (stringp word)
(scan "^[][\\`_^{|}A-Za-z][][\\`_^{|}A-Za-z0-9-]{0,8}$" word)))
(defun channel-name-p (word)
(and (stringp word)
(scan "^([#+&][!-+--9;-~]+|![0-9A-Z]{5})(:[!-+--9;-~]+)?$" word)))
(defun server-name-p (word)
(and (stringp word)
(scan "^([A-Za-z0-9][-A-Za-z0-9]*)(\\.([A-Za-z0-9][-A-Za-z0-9]*))*$" word)))
(defun emailp (word)
(and (stringp word)
(position #\@ word)
(< 0 (position #\@ word) (1- (length word)))))
(defmethod word-equal ((a string) (b token))
(word-equal b a))
(defmethod word-equal ((a token) (b string))
(string= (token-text a) b))
;; TODO: We need a command to create a new server before connecting it:
;; create server hostname nick botil password secret
;; (create-server hostname [botil-nick])
;;
;; TODO: A command to manage users right.
;; - server creation
;; - server enable/disable
;; - user banishment
(defun rhs-bnf (rhs)
(cond
((null rhs) "")
((symbolp rhs) (format nil "<~A>" rhs))
((atom rhs) rhs)
(t (case (first rhs)
((alt)
(if (null (cddr rhs))
(rhs-bnf (second rhs))
(format nil "(~{~A~^|~})" (mapcar (function rhs-bnf) (rest rhs)))))
((opt)
(format nil "[~{~A~^ ~}]" (mapcar (function rhs-bnf) (subseq rhs 1 (position :action rhs)))))
((seq)
(format nil "~{~A~^ ~}" (mapcar (function rhs-bnf) (subseq rhs 1 (position :action rhs)))))
((rep)
(format nil "{~{~A~^ ~}}" (mapcar (function rhs-bnf) (subseq rhs 1 (position :action rhs)))))
(otherwise
(rhs-bnf `(seq ,@rhs)))))))
(defgrammar botil
:terminals ((word "[^ ]+")
(string "\"[^\"]+\"|'[^']+'")
;; (montezuma ".+")
)
:skip-spaces t
:start command
:eof-symbol eol
:rules #1=(
(--> command
(alt ;; query
connect
log-request
cancel-log
list
set
server-commands
register identify reset
help version uptime sources)
:action $1)
(--> server word :action `(server ,(second word)))
(--> email word :action `(email ,(second word)))
(--> channel word :action `(channel ,(second word)))
(--> nick word :action `(nick ,(second word)))
(--> password word :action `(password ,(second word)))
(--> id word :action `(id ,(second word)))
(--> key word :action `(key ,(second word)))
(--> date word :action `(date ,(second word)))
;; (--> criteria
;; disjunction
;; :action `(criteria ,disjunction))
;;
;; (--> disjunction
;; conjunction (opt "or" disjunction :action disjunction)
;; :action (if $2
;; `(or ,conjunction ,$2)
;; conjunction))
;;
;; (--> conjunction
;; term (opt "and" conjunction :action conjunction)
;; :action (if $2
;; `(and ,term ,$2)
;; term))
;;
;; (--> term
;; (alt (seq "not" term :action `(not ,$2))
;; (seq selection :action selection)))
;; (--> selection
;; (alt
;; (seq "(" disjunction ")" :action disjunction)
;; (seq (rep string) :action `(keywords ,@$1))
;; (seq (opt "channel") channel :action channel)
;; (seq user nick :action nick)))
;; (--> query
;; "query" montezuma
;; :action `(query ,montezuma))
(--> user (alt "nick" "nickname" "user" "mr" "mrs" "miss" "dr" "pr"))
(--> connect
"connect" (opt "to") (opt "server") server
(opt (opt "as") user nick :action nick)
(opt (opt "with") "password" password :action password)
:action `(connect ,server ,$5 ,$6))
(--> server-commands
(alt (seq "enable" :action 'enable)
(seq "disable" :action 'disable))
(opt "server") server
:action `(,$1 ,server))
(--> register
"register" email password
:action `(register ,email ,password))
(--> identify
"identify" password
:action `(identify ,password))
(--> reset
"reset" (opt (opt user) nick :action nick)
:action `(reset ,$2))
(--> set
"set"
(alt
(seq "password" (opt user) nick (opt "key") key (opt "password") password
:action `(set-password ,nick ,key ,password)))
:action $2)
(--> requests
(alt (seq (alt "log" "logs") (opt (alt "request" "requests")) )
"request" "requests"))
(--> of-nick
"of" (opt user) nick
:action nick)
(--> for-channel
"for" (opt "channel") channel
:action channel)
(--> my-log-requests
"my" requests (opt for-channel :action for-channel)
:action `(nil ,$3 nil))
(--> request-selection
(alt my-log-requests
(seq "all" (alt my-log-requests
(seq requests
(opt of-nick :action $1)
(opt for-channel :action $1)
(opt "on" (opt "server") server :action server)
:action (list t $2 $3 $4)))
:action $2)))
(--> list
"list" (alt (seq request-selection
:action `(list-log-requests ,@request-selection))
(seq (alt "user" "users")
(opt "on" (opt "server") server :action server)
:action `(list-users ,$2))
(seq (alt "server" "servers")
:action `(list-servers)))
:action $2)
(--> cancel-log
"cancel" (alt
(seq request-selection
:action `(cancel-log-requests ,@request-selection))
(seq "log" id
:action `(cancel-log-id ,id)))
:action $2)
;; list my log requests (requests sender)
;; list my log requests for channel #lisp (of-channel channel (requests sender))
;; list all my log requests (requests sender)
;; list all log requests of mr foo (requests user)
;; list all log requests of mr foo for channel #lisp (of-channel channel (requests user))
;; list all log requests for channel #lisp (requests channel)
;; list all log requests (requests server)
(--> log-request
"log" (opt "channel") channel
(opt "on" (opt "server") server :action server)
(opt (alt (seq "from" date (opt "to" date :action date)
:action `(,date ,$3))
(seq "to" date :action `(nil ,date)))
:action $1)
:action `(log-request ,channel ,$4 ,@$5))
(--> help
"help" (opt (alt "query" "connect" "reconnect" "enable" "disable" "register" "identify"
"reset" "set" "list" "start" "stop" "log" "cancel" "help" "version" "uptime" "sources"
word)
:action (second $1))
:action `(help ,$2))
(--> version "version" :action '(version))
(--> uptime "uptime" :action '(uptime))
(--> sources (alt "sources" "source") :action '(sources))))
(defparameter *help*
'("query|q|search|s <montezuma-criteria>"
"connect [to] [server] <server> [[as] nick <nick>] [[with] password <password>]"
"enable [server] <server>"
"disable [server] <server>"
"register <email> <password>"
"identify <password>"
"reset [<nick>]"
"set password [nick] <nick> [key] <key> [password] <password>"
"list (server|servers)"
"list (user|users) [on [server] <server>]"
"log [channel] <channel> (from <date> [to <date>])|(to <date>)"
"list [all] my [log] requests [for [channel] <channel>]"
"list all [log] requests [of [nick] <nick>] [for [channel] <channel>] [on [server] <server>]"
"cancel all [log] requests [of [nick] <nick>] [for [channel] <channel>] [on [server] <server>]"
"cancel log <id>"
"help"
"version"
"uptime"
"sources"))
(defun reconnect (server)
(irc:quit (connection server) "Will reconnect...")
(setf (connection server) nil))
;;;-----------------------------------------------------------------------------
;;; Miscellaenous commands
;;;
(defparameter *disses*
#(
"You’ve baked a really lovely cake, but then you’ve used dog sh!t for frosting."
"You make some of the best products in the world — but you also make a lot of crap. Get rid of the crappy stuff."
"This company is in shambles, and I don’t have time to wet-nurse the board. So I need all of you to resign."
"Do you want to spend the rest of your life selling sugared water or do you want a chance to change the world?"
"Being the richest man in the cemetery doesn’t matter to me…"
"Be a yardstick of quality. Some people aren’t used to an environment where excellence is expected."
"The products suck! There's no sex in them anymore!"
"I’ve never known an HR person who had anything but a mediocre mentality."
"Everything you have done in your life is shit! So why don't you come work for me?"
"My job is to say when something sucks rather than sugarcoat it."
"Look, I don’t know who you are, but no one around here is too important to fire besides me. And you’re fired!"
"You think I'm an arrogant ass -- who thinks he's above the law, and I think you're a slime bucket who gets most of his facts wrong."
"That's the kind of Porsche that dentists drive."
"Sometimes when you innovate, you make mistakes. It is best to admit them quickly, and get on with improving your other innovations."))
(defun one-of (s) (elt s (random (length s))))
(defun diss (sender)
(answer sender (one-of *disses*)))
(defun help (sender what)
(let ((lines (mapcar (lambda (command)
(list (subseq command 0 (position #\space command)) command))
*help*)))
(if what
(loop :for (command line) :in lines
:when (string= what command)
:do (answer sender "~A" line))
(answer sender "Available commands: ~{~A~^ ~}"
(remove-duplicates (mapcar (function first) lines)
:test (function string=))))))
;; (help (find-user "irc.freenode.org" "pjb") "everything")
(defun version (sender)
(answer sender "Version: ~A" *version*))
(defun uptime-cmd (sender)
(answer sender "~A" (substitute #\space #\newline
(with-output-to-string (*standard-output*)
(date) (uptime)))))
(defun sources (sender)
(answer sender "I'm an IRC log bot, under AGPL3 license, ~
my sources are available at <~A>."
*sources-url*))
;;; -----------------------------------------------------------------------------
(defmacro when-null ((var default) &body otherwise)
`(if (null ,var)
,default
(progn ,@otherwise)))
(defmacro when-unwrap ((var tag &optional filter-expression) &body body)
`(cond
((and (consp ,var)
(consp (cdr ,var))
(null (cddr ,var))
(eq ',tag (car ,var)))
(let ((,var (cadr ,var)))
,(if filter-expression
`(if ,filter-expression
(progn ,@body)
(error "Invalid ~(~A~) argument: ~S" ',tag ,var))
`(progn ,@body))))
(t (error "Invalid ~(~A~) argument: ~S" ',tag ,var))))
(defun argument-server (sender server)
(when-null (server (server sender))
(when-unwrap (server server (server-name-p server))
(or (find-server server)
(error "Unknown server: ~S" (cadr server))))))
(defun argument-channel (sender channel &optional server)
(when-unwrap (channel channel (channel-name-p channel))
(ensure-channel (or server (server sender)) channel)))
(defun argument-nickname (nick)
"Just a string for a new nickname."
(when-null (nick nil)
(when-unwrap (nick nick (nicknamep nick))
nick)))
(defun argument-new-user (sender nick server)
(when-null (nick sender)
(when-unwrap (nick nick (nicknamep nick))
(ensure-user server nick))))
(defun argument-old-user (sender nick server)
(when-null (nick sender)
(when-unwrap (nick nick (nicknamep nick))
(or (find-user server nick)
(error "I have no user nicknamed ~A on ~A" nick (hostname server))))))
(defun argument-key (key)
(when-unwrap (key key (stringp key))
key))
(defun argument-id (id)
(when-unwrap (id id (stringp id))
(parse-integer id)))
(defun argument-email (email)
(when-unwrap (email email (emailp email))
email))
(defun argument-password (password)
(when-unwrap (password password (stringp password))
password))
(defun argument-date (date)
(when-unwrap (date date (stringp date))
(parse-date-time date)))
;;; -----------------------------------------------------------------------------
;;; credentials
;;;
(defvar *administrators* '("pjb" "tbot"))
(defun administratorp (user)
(member (name user) *administrators* :test (function string=)))
(defun has-server-credential (sender server)
;; TODO:
(declare (ignore server))
(administratorp sender))
(defun has-user-credentials (sender user)
;; TODO:
(and (or (administratorp sender)
(eql sender user))
(or (identified sender)
(answer sender "You're not identified.")
nil)))
;;; -----------------------------------------------------------------------------
;;; server commands
;;;
(defmacro with-server ((sender server) &body body)
`(let ((,server (argument-server ,sender ,server)))
(declare (ignorable ,server))
,@body))
(defun connect (sender server nickname password)
;; (connect (server "irc.freenode.org") (nick "botnick") (password "botpassword"))
(if (has-server-credential sender nil)
(with-server (sender server)
(if (find-server server)
(answer sender "The server ~A is already configured." server)
(let ((nick (or (argument-nickname nickname) "botil"))
(password (argument-password password)))
(create-server server nick password)
(answer sender "The server ~A has been created. enable it to connect."))))
(answer sender "You are not authorized to order me to connect to new servers.")))
;; (enable (find-user (first *servers*) "pjb") '(server "irc.freenode.org"))
(defun enable (sender server)
;; (enable (server "irc.freenode.org"))
(with-server (sender server)
(if (has-server-credential sender server)
(progn
(setf (enabled server) t)
(answer sender "~A is enabled, will connect." (hostname server)))
(answer sender "You are not authorized to enable the server ~A." (hostname server)))))
(defun disable (sender server)
;; (disable (server "irc.freenode.org"))
(with-server (sender server)
(if (has-server-credential sender server)
(if (= 1 (count-if (function enabled) *servers*))
(answer sender "Cannot disable the last server.")
(progn
(setf (enabled server) nil)
(if (eq server (server sender))
(answer sender "This server is disabled, will disconnect.")
(answer sender "~A is disabled, will disconnect." (hostname server)))
(disconnect server sender)))
(answer sender "You are not authorized to disable the server ~A." (hostname server)))))
;;; -----------------------------------------------------------------------------
;;; list commands
;;;
(defun list-servers (sender)
(dolist (server *servers*)
(answer sender "~A (~A) ~:[disabled~;~:[~;connected~]~] ~:[~;(this server)~]"
(hostname server) (botnick server)
(enabled server) (connection server)
(eq server (server sender)))))
(defmacro with-user ((sender nick server) &body body)
`(let ((,nick (argument-old-user ,sender ,nick ,server)))
,@body))
;; list my log requests (requests sender)
;; list my log requests for channel #lisp (of-channel channel (requests sender))
;; list all my log requests (requests sender)
;;
;; list all log requests of mr foo (requests user)
;; list all log requests of mr foo for channel #lisp (of-channel channel (requests user))
;; list all log requests for channel #lisp (requests channel)
;; list all log requests (requests server)
(defun of-channel (channel requests)
(remove channel requests :test-not (function eql) :key (function channel)))
(defun select-log-requests (sender allp user channel server)
(let* ((channel (when channel (argument-channel sender channel)))
(user (when user (argument-old-user sender user server))))
(if allp
(if user
(if (has-user-credentials sender user)
(values (if channel
(of-channel channel (requests user))
(requests user))
user)
(progn
(answer sender "You are not authorized to access the requests from the user ~A." (name user))
nil))
(if channel
(if (has-server-credential sender server)
(values (requests channel))
(values (of-channel channel (requests sender)) sender))
(if (has-server-credential sender server)
(values (requests (or server (server sender))))
(values (requests sender) sender))))
(if channel
(values (of-channel channel (requests sender)) sender)
(values (requests sender))))))
(defun list-log-requests (sender allp user channel &optional server)
;; (list-log-requests (server "irc.freenode.org") (nick "pjb"))
;; (list-log-requests nil nil)
(with-server (sender server)
(multiple-value-bind (requests owner) (select-log-requests sender allp user channel server)
(if requests
(dolist (request requests
(answer sender "~R request~:*~p." (length requests)))
(answer sender "~3D) ~9A requested ~15A from ~A~@[ to ~A~]"
(id request)
(name (owner request))
(name (channel request))
(format-iso8601-time (start-date request))
(when (end-date request)
(format-iso8601-time (end-date request)))))
(answer sender "~:[No log requests.~;~A has requested no logs.~]" owner (name owner))))))
(defun user-names (server)
(mapcar (function pathname-name)
(directory (user-pathname :wild server))))
(defun list-users (sender server)
;; (list-users (server "irc.freenode.org"))
;; (list-users nil)
(with-server (sender server)
(dolist (user
(if (has-server-credential sender server)
(user-names server)
(progn (answer sender "You are not authorized to list the users other than you.")
(list (name sender)))))
(let ((user (find-user server user)))
(answer sender "~16A ~:[ ~;I~]~:[ ~;V~] ~@[~A~]"
(name user) (identified user) (verified user) (email user))))))
;;; -----------------------------------------------------------------------------
;;; User identification commands
;;;
(defun sendmail (to subject message)
(send-email *smtp-server* *botil-email* to subject message :port *smtp-port*))
(defun generate-key ()
(substitute #\I #\1
(substitute-if #\O (lambda (ch) (find ch "0Q"))
(with-output-to-string (out)
(loop :repeat 4
:for sep = "" :then "-"
:do (format out "~A~36,4R" sep (random (expt 36 4))))))))
(defun send-verification-email (sender user)
(if (email user)
(progn
(setf (verified user) nil
(key user) (generate-key))
(save user)
(sendmail (email user)
"Verify your email with botil."
(format nil "Please let botil verify your email ~%~
by giving the following command ~%~
to irc://~A@~A :~%~
set password ~A ~A ~A~%"
(botnick (server sender))
(hostname (server sender))
(name user) (key user) "{your-new-password}")))
(answer sender "User has no email yet. Use the register command!")))
(defun send-password-change-email (sender user)
(if (email user)
(progn
(setf (verified user) nil
(key user) (generate-key))
(save user)
(sendmail (email user)
"Password change with botil."
(format nil "You may change your password ~%~
by giving the following command ~%~
to irc://~A@~A :~%~
set password ~A ~A ~A~%"
(botnick (server sender))
(hostname (server sender))
(name user) (key user) "{your-new-password}")))
(answer sender "User has no email yet. Use the register command!")))
(defun identify (sender password)
;; (identify (password "secret-password"))
(let ((password (argument-password password)))
(if (and (password sender)
(string= (password sender) password))
(progn
(setf (identified sender) t)
(answer sender "You're identified."))
(answer sender "Failed."))))
(defun register (sender email password)
;; TODO: register doesn't need the password.
;; (register (email "[email protected]") (password "secret-password"))
(let ((email (argument-email email))
(password (argument-password password)))
(if (and (null (email sender))
(null (password sender)))
(progn
(setf (email sender) email
(password sender) password
(verified sender) nil)
(send-verification-email sender sender)
(answer sender "You're registered."))
(answer sender "You are already registered. Use reset and set password to change your password."))))
(defun reset (sender nick)
;; (reset (nick "pjb"))
;; (reset nil)
(let ((user (argument-old-user sender nick (server sender))))
(if (has-user-credentials sender user)
(progn (send-password-change-email sender user)
(answer sender "Password change email sent to ~A" (email user)))
(answer sender "You are not authorized to ask for a password reset for ~A." (name user)))))
(defun set-password (sender nick key password)
;; (set-password (nick "pjb") (key "321545623f") (password "new-secret-password"))
(let ((user (argument-old-user sender nick (server sender)))
(key (argument-key key))
(password (argument-password password)))
(if (has-user-credentials sender user)
(cond
((string/= key (key user))
(answer sender "Invalid key, use the reset command and try with the new key."))
(t (setf (password user) password
(verified user) t
(key user) nil
(identified user) nil)
(save user)
(answer sender "Password set. Identify again!")))
(answer sender "You are not authorized to set the password of ~A." (name user)))))
;;; -----------------------------------------------------------------------------
;;; Log commands
;;;
(defun log-request (sender channel server
&optional (start-date (get-universal-time)) end-date)
;; (log-request (channel "#lisp") (server "irc.freenode.org") (date "2016-03-01") (date "2016-03-31"))
;; (log-request (channel "#lisp") (server "irc.freenode.org") (date "2016-06-01") nil)
;; (log-request (channel "#lisp") (server "irc.freenode.org") nil (date "2016-02-28"))
;; (log-request (channel "#lisp") nil (date "20160301T000000") (date "2016-03-31T00:00:00"))
;; (log-request (channel "#lisp") nil (date "20160601T000000") nil)
;; (log-request (channel "#lisp") nil nil (date "2016-02-28T00:00:00"))
;; TODO: mixup user from one server asking logs on another server.
(with-server (sender server)
(let ((channel (argument-channel sender channel))
(start-date (if (integerp start-date)
start-date
(argument-date (or start-date (get-universal-time)))))
(end-date (typecase end-date
(integer end-date)
(null nil)
(t (argument-date end-date)))))
(if (and end-date (<= end-date start-date))
(answer sender "End date must be after start date.")
(answer sender "Added ~A" (create-request channel sender start-date end-date))))))
(defun cancel-log-requests (sender allp user channel &optional server)
;; (cancel-log-requests (channel "#lisp") (server "irc.freenode.org"))
;; (cancel-log-requests (channel "#lisp") nil)
(with-server (sender server)
(let ((to-be-canceled (select-log-requests sender allp user channel server)))
(if to-be-canceled
(dolist (request to-be-canceled
(answer sender "~R request~:*~p deleted." (length to-be-canceled)))
(answer sender "Deleted ~A" (delete-request request)))
(answer sender "Found no request to be deleted.")))))
(defun cancel-log-id (sender id)
;; (cancel-log-id (id "42"))
(let ((id (argument-id id)))
(let* ((requests (requests sender))
(the-one (find id requests :key (function id))))
(if the-one
(answer sender "Deleted ~A" (delete-request the-one))
(answer sender "Found no request ID ~A" id)))))
;;; -----------------------------------------------------------------------------
;;; log querying
;;;
(defun query (sender criteria)
(declare (ignore criteria))
;; (query (criteria (and (channel "#lisp") (and (nick "pjb") (keywords "cl-all")))))
;; (query (criteria (and (keywords "\"cl\"") (and (or (keywords "all") (or (keywords "some") (keywords "any"))) (channel "#lisp")))))
(answer sender "Queries are not implemented yet, sorry."))
;;; -----------------------------------------------------------------------------
;;; Command interpreter.
(defun interpret (sender expression)
(ecase (first expression)
((help) (help sender (second expression)))
((version) (version sender))
((uptime) (uptime-cmd sender))
((sources) (sources sender))
;; ((query) (query sender (second expression)))
((connect) (connect sender (second expression) (third expression) (fourth expression)))
((disable) (disable sender (second expression)))
((enable) (enable sender (second expression)))
((list-servers) (list-servers sender))
((list-users) (list-users sender (second expression)))
((list-log-requests) (apply (function list-log-requests) sender (rest expression)))
((cancel-log-requests) (apply (function cancel-log-requests) sender (rest expression)))
((log-request) (apply (function log-request) sender (rest expression)))
((cancel-log-id) (cancel-log-id sender (second expression)))
((identify) (identify sender (second expression)))
((register) (register sender (second expression) (third expression)))
((reset) (reset sender (second expression)))
((set-password) (set-password sender (second expression) (third expression) (fourth expression)))))
(defun command-processor (server sender command)
(check-type server server)
(check-type sender user)
(check-type command string)
(format *trace-output* "~&~S~% ~S~% ~S~% ~S~%"
'command-processor server sender command)
(let* ((tcmd (string-trim " " command))
(cpos (position #\space tcmd))
(vcmd (subseq tcmd 0 cpos)))
(if (or (string= vcmd "query")
(string= vcmd "search")
(string= vcmd "s")
(string= vcmd "q"))
(send-worker *query-processor* server sender (subseq tcmd (1+ cpos)))
(let ((expression (handler-case
(parse-botil command)
(error ()
(let ((command (subseq command 0 (position #\space command))))
(answer sender "Syntax error.")
(help sender command)
(return-from command-processor))))))
(handler-case
(interpret sender expression)
(error (err)
(answer sender "~A" (substitute #\space #\newline (princ-to-string err)))))))))
(defun botil (server command)
(ecase command
((reconnect)
;; we've connected to server, let's rejoin the channels and go on logging.
(update-channels server))
((quit)
(exit))))
(defun initialize-index ()
(setf *index* (make-instance 'montezuma:index :path (index-pathname))))
(defvar *botil-workers* '())
(defun initialize-workers ()
(setf *sender* (make-worker-thread botil-sender (server recipient message &rest arguments)
(apply (function send) server recipient message arguments))
*query-processor* (make-worker-thread botil-query-processor (server sender message)
(format *trace-output* "~&QUERY ~A -> ~A~%" sender message)
(query-processor server sender message))
*logger* (make-worker-thread botil-logger (server message)
(format *trace-output* "~&LOGGER ~A -> ~A~%" (irc:source message) message)
(logger server message))
*command-processor* (make-worker-thread botil-command-processor (server sender message)
(format *trace-output* "~&COMMAND ~A -> ~A~%" sender message)
(command-processor server sender message))
*botil* (make-worker-thread botil-main (server command)
(format *trace-output* "~&BOTIL <- ~A~%" command)
(botil server command)))
(push *sender* *botil-workers*)
(push *query-processor* *botil-workers*)
(push *logger* *botil-workers*)
(push *command-processor* *botil-workers*)
(push *botil* *botil-workers*))
(defun kill-all-workers ()
(mapc (function kill-worker) *botil-workers*)
(setf *botil-workers* '()))
(defun botil-initialize ()
(setf *database* (find-database))
(initialize-index)
(initialize-workers)
(load-server-database))
;;;-----------------------------------------------------------------------------
;; source = "nickname" or "#channel"
;; user = "~t" "identified-user@host" etc
;; host = fqdn of user's host
;; command = "PRIVMSG"
;; arguments = ("command" "arguments"); for /msg botil hello world --> ("botil" "hello world")
;; #test-botil <test-botil> /msg botil hello how do you do?
;; (:sender "test-botil" :recipient "botil" :arguments ("botil" "hello how do you do?"))
;; #test-botil <test-botil> How do you do?
;; (:sender "test-botil" :recipient "#test-botil" :arguments ("#test-botil" "How do you do?"))
(defun msg-hook (server message)
(with-accessors ((sender irc:source)
(arguments irc:arguments)) message
(let ((recipient (first arguments)))
(format *trace-output* "~&msg-hook message = ~S~%"
(list :server server
:sender sender
:recipient recipient
:arguments arguments))
(if (string= (botnick server) recipient)
(let ((sender (ensure-user server sender)))
(send-worker *command-processor* server sender (second arguments)))
(send-worker *logger* server message)))))
(defun make-msg-hook (server)
(lambda (message)
"Answers to PRIVMSG."
(msg-hook server message)
t))
;; Note: we can track nick and quit only of users on the same
;; channels as we are on, so it's useless in general: we may
;; have to require passwords for all critical commands.
(defun svc-hook (server message)
(send-worker *logger* server message)
(format t "~&svc-hook message type = ~S~%" (type-of message))
(with-accessors ((sender irc:source)
(arguments irc:arguments)) message
(let ((recipient (first arguments)))
;; irc:irc-nick-message
;; irc:irc-quit-message
(format t "~&svc-hook message = ~S~%"
(list :server server
:sender sender
:recipient recipient
:command (irc:command message)
:arguments arguments)))))
(defun make-svc-hook (server)
(lambda (message)
"Answers to service messages."
(svc-hook server message)
t))
(defmethod connect-to-server ((server server))
(setf (connection server) (irc:connect :server (hostname server)
:nickname (botnick server)
:username (botnick server)
:password (botpass server)))
(let ((msg-hook (make-msg-hook server))
(svc-hook (make-svc-hook server)))
(irc:add-hook (connection server) 'irc:irc-privmsg-message msg-hook)
(mapc (lambda (class) (irc:add-hook (connection server) class svc-hook))
'(irc:irc-notice-message
irc:irc-topic-message
irc:irc-error-message
irc:irc-mode-message
;; -
irc:irc-nick-message
irc:irc-quit-message
irc:irc-join-message
irc:irc-part-message
irc:irc-kill-message
irc:irc-kick-message
irc:irc-invite-message))
(send-worker *botil* server 'reconnect)))
;;;-----------------------------------------------------------------------------
;;;
;;; The main loop.
;;;
(defun call-with-retry (delay thunk)
"Calls THUNK repeatitively, reporting any error signaled,
and calling the DELAY-ing thunk between each."
(loop
(handler-case (funcall thunk)
(error (err) (format *error-output* "~A~%" err)))
(funcall delay)))
(defmacro with-retry (delay-expression &body body)
"Evaluates BODY repeatitively, reporting any error signaled,
and evaluating DELAY-EXPRESSIONS between each iteration."
`(call-with-retry (lambda () ,delay-expression)
(lambda () ,@body)))
(defun exit ()
"Breaks the main loop and exit."
(throw :gazongues nil))
(defun main ()
"The main program of the botil IRC bot.
We connect and reconnect to the *SERVER* under the *NICKNAME*,
log the channels we're instructed to log,
and answer to search queries in those logs."
(let ((*package* (load-time-value
(find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL"))))
(botil-initialize)
(with-simple-restart (quit "Quit")
(catch :gazongues
(unwind-protect
(loop
(dolist (server *servers*)
(let ((connection (connection server)))
(if connection
(with-simple-restart (reconnect "Reconnect")
(catch :petites-gazongues
(irc:read-message connection) #| goes to msg-hook or svc-hook.|#
(update-channels server)))
(when (enabled server)
(connect-to-server server))))))
(kill-all-workers))))))
#-(and)
(progn
(send-worker *command-processor* (find-server "irc.freenode.org")
(ensure-user "irc.freenode.org" "pjb")
"list servers")
(send-worker *command-processor* (find-server "irc.freenode.org")
(ensure-user "irc.freenode.org" "pjb")
"enable irc.freenode.org")
*servers*
(setf (enabled (first *servers*)) t)
(save (first *servers*))
)
;;;;
;;;;
;;;; Tests
;;;;
;;;;
(in-package "COMMON-LISP-USER")
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")
(:import-from "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL"
"*BOTIL-EMAIL*" "*BOTIL-WORKERS*" "*DATABASE*"
"*DEFAULT-NICKNAME*" "*DEFAULT-PASSWORD*" "*DISSES*"
"*EXTERNAL-FORMAT*" "*INITIAL-SERVER*"
"*SERVERS*" "*SOURCES-URL*" "*VERSION*")
(:import-from "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL"
"CHANNEL-ACTIVE-P"
"CHANNEL-NEXT-START-LOG-DATE"
"CHANNEL-NEXT-STOP-LOG-DATE"
"AND" "ANSWER" "ARGUMENT-EMAIL" "ARGUMENT-KEY"
"ARGUMENT-PASSWORD" "ARGUMENT-SERVER" "ARGUMENT-OLD-USER" "ARGUMENT-NEW-USER"
"ARGUMENTS" "BOTIL" "BOTIL-INITIALIZE" "BOTNICK"
"BOTPASS" "CALL-WITH-RETRY" "CANCEL-LOG-REQUESTS"
"CANCEL-LOG-ID" "CHANNEL" "CHANNEL-PATHNAME"
"CHANNELS" "COMMAND" "COMMAND-PROCESSOR"
"COMPUTE-DEADLINE" "CONNECT" "CONNECT-TO-SERVER"
"CONNECTION" "COPY-WORKER" "CREATE-MESSAGE"
"CREATE-REQUEST" "CREATE-SERVER"
"CRITERIA" "DATE" "LOG-REQUEST" "DISABLE"
"DISCONNECT" "DISS" "EMAIL" "ENABLE" "ENABLED"
"END-DATE" "ENSURE-CHANNEL" "ENSURE-LOG-STREAM"
"ENSURE-USER" "EXIT" "FIND-CHANNEL" "FIND-SERVER"
"FIND-USER" "GENERATE-KEY" "HELP" "HOST" "HOSTNAME"
"ID" "IDENTIFIED" "IDENTIFY" "INITIALIZE-DATABASE"
"INTERPRET" "KEY"
"KILL-WORKER" "LIST-LOG-REQUESTS"
"LIST-SERVERS" "LIST-USERS"
"LOAD-REQUESTS" "LOAD-SERVER-DATABASE"
"LOG-FILE-PATHNAME" "LOG-MONTH" "LOG-STREAM"
"LOGGER" "MAIN" "MAKE-MSG-HOOK"
"MAKE-SVC-HOOK" "MAKE-WORKER" "MAKE-WORKER-THREAD"
"NAME" "NICK" "ONE-OF" "OR" "OWNER" "PARSE-BOTIL"
"PASSWORD" "QUERY" "QUERY-PROCESSOR"
"RAW-MESSAGE-STRING" "RECEIVED-TIME" "RECONNECT"
"REGISTER" "REQUESTS" "REQUESTS-PATHNAME" "RESET"
"SAVE" "SAVE-REQUESTS" "SEND-IRC"
"SEND-PASSWORD-CHANGE-EMAIL" "SEND-VERIFICATION-EMAIL"
"SEND-WORKER" "SENDER" "SERVER" "SERVER-DATA"
"SERVER-DATAFILE-PATHNAME" "SERVER-PATHNAME"
"SET-PASSWORD" "SOURCE" "SOURCES" "START-DATE"
"TODO" "UPTIME-CMD" "USER"
"USER-PATHNAME" "VERIFIED" "VERSION" "WITH-RETRY"
"WITH-SERVER" "WORKER-INPUT-QUEUE" "WORKER-P"
"WORKER-SEND" "WORKER-THREAD"
"SERVER-NAME-P" "CHANNEL-NAME-P" "NICKNAMEP")
(:export "TEST/ALL")
(:documentation "
Tests the botil program.
Copyright Pascal J. Bourguignon 2016 - 2016
Licensed under the AGPL3.
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL.TEST")
(defmacro with-temporary-database (&body body)
`(let ((*database* (pathname (format nil "/tmp/irc-~8,'0X/" (random (expt 2 32)))))
(*servers* '()))
(unwind-protect
(progn ,@body)
(uiop:run-program (format nil "rm -rf ~S" (namestring *database*))))))
(define-test test/botil-grammar ()
(map nil (lambda (test)
(destructuring-bind (sentence expected) test
(check equal (parse-botil sentence) expected
(sentence))))
'(
("query channel #lisp and nick pjb and \"cl-all\""
(query (criteria (and (channel "#lisp") (and (nick "pjb") (keywords "cl-all"))))))
("query \"cl\" and ( \"all\" or \"some\" or \"any\" ) and #lisp"
(query (criteria (and (keywords "\"cl\"")
(and (or (keywords "all") (or (keywords "some") (keywords "any")))
(channel "#lisp"))))))
("connect irc.freenode.org"
(connect (server "irc.freenode.org") nil nil))
("connect to irc.freenode.org"
(connect (server "irc.freenode.org") nil nil))
("connect server irc.freenode.org"
(connect (server "irc.freenode.org") nil nil))
("connect to server irc.freenode.org"
(connect (server "irc.freenode.org") nil nil))
("disable irc.freenode.org"
(disable (server "irc.freenode.org")))
("enable irc.freenode.org"
(enable (server "irc.freenode.org")))
("register [email protected] secret-password"
(register (email "[email protected]") (password "secret-password")))
("identify secret-password"
(identify (password "secret-password")))
("reset"
(reset nil))
("reset pjb"
(reset (nick "pjb")))
("set password pjb 321545623f new-secret-password"
(set-password (nick "pjb") (key "321545623f") (password "new-secret-password")))
("list users"
(list-users nil))
("list users on irc.freenode.org"
(list-users (server "irc.freenode.org")))
("list servers"
(list-servers))
;;
("list my log requests"
(list-log-requests nil nil nil nil))
("list my log requests for channel #lisp"
(list-log-requests nil nil (channel "#lisp") nil))
("list all my log requests"
(list-log-requests nil nil nil nil))
("list all log requests of mr foo"
(list-log-requests t (nick "foo") (channel "#lisp") nil))
("list all log requests of mr foo for channel #lisp"
(list-log-requests t (nick "foo") (channel "#lisp") nil))
("list all log requests for channel #lisp"
(list-log-requests t nil (channel "#lisp") nil))
("list all log requests"
(list-log-requests t nil (channel "#lisp") nil))
("list all log requests of mr foo on server irc.freenode.org"
(list-log-requests t (nick "foo") (channel "#lisp") (server "irc.freenode.org")))
("list all log requests of mr foo for channel #lisp on server irc.freenode.org"
(list-log-requests t (nick "foo") (channel "#lisp") (server "irc.freenode.org")))
("list all log requests for channel #lisp on server irc.freenode.org"
(list-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("list all log requests on server irc.freenode.org"
(list-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("list all channel logs on server irc.freenode.org"
(list-log-requests t nil nil (server "irc.freenode.org")))
("list all channels"
(list-log-requests t nil nil nil))
("list all logs on irc.freenode.org"
(list-log-requests t nil nil (server "irc.freenode.org")))
("list all logs"
(list-log-requests t nil nil nil))
;;
("cancel my log requests"
(cancel-log-requests nil nil nil nil))
("cancel my log requests for channel #lisp"
(cancel-log-requests nil nil (channel "#lisp") nil))
("cancel all my log requests"
(cancel-log-requests nil nil nil nil))
("cancel all log requests of mr foo"
(cancel-log-requests t (nick "foo") (channel "#lisp") nil))
("cancel all log requests of mr foo for channel #lisp"
(cancel-log-requests t (nick "foo") (channel "#lisp") nil))
("cancel all log requests for channel #lisp"
(cancel-log-requests t nil (channel "#lisp") nil))
("cancel all log requests"
(cancel-log-requests t nil (channel "#lisp") nil))
("cancel all log requests of mr foo on server irc.freenode.org"
(cancel-log-requests t (nick "foo") (channel "#lisp") (server "irc.freenode.org")))
("cancel all log requests of mr foo for channel #lisp on server irc.freenode.org"
(cancel-log-requests t (nick "foo") (channel "#lisp") (server "irc.freenode.org")))
("cancel all log requests for channel #lisp on server irc.freenode.org"
(cancel-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("cancel all log requests on server irc.freenode.org"
(cancel-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("cancel all channel logs on server irc.freenode.org"
(cancel-log-requests t nil nil (server "irc.freenode.org")))
("cancel all channels"
(cancel-log-requests t nil nil nil))
("cancel all logs on irc.freenode.org"
(cancel-log-requests t nil nil (server "irc.freenode.org")))
("cancel all logs"
(cancel-log-requests t nil nil nil))
;;
("cancel all log request on channel #lisp on server irc.freenode.org"
(cancel-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("cancel all log request on channel #lisp"
(cancel-log-requests t nil (channel "#lisp") nil))
("cancel all #lisp on irc.freenode.org"
(cancel-log-requests t nil (channel "#lisp") (server "irc.freenode.org")))
("cancel all #lisp"
(cancel-log-requests t nil (channel "#lisp") nil))
;;
("cancel log 42"
(cancel-log-id (id "42")))
;;
("log channel #lisp on server irc.freenode.org to 2016-02-28"
(log-request (channel "#lisp") (server "irc.freenode.org") nil (date "2016-02-28")))
("log channel #lisp on server irc.freenode.org from 2016-03-01 to 2016-03-31"
(log-request (channel "#lisp") (server "irc.freenode.org") (date "2016-03-01") (date "2016-03-31")))
("log channel #lisp on server irc.freenode.org from 2016-06-01"
(log-request (channel "#lisp") (server "irc.freenode.org") (date "2016-06-01") nil))
("log #lisp to 2016-02-28T00:00:00"
(log-request (channel "#lisp") nil nil (date "2016-02-28T00:00:00")))
("log #lisp from 20160301T000000 to 2016-03-31T00:00:00"
(log-request (channel "#lisp") nil (date "20160301T000000") (date "2016-03-31T00:00:00")))
("log #lisp from 20160601T000000"
(log-request (channel "#lisp") nil (date "20160601T000000") nil))
)))
(define-test test/pathnames ()
(with-temporary-database
(let* ((server (create-server "irc.freenode.org"))
(user (ensure-user server "pjb"))
(channel (ensure-channel server "#lisp")))
(declare (ignorable server user channel))
(check equal (server-pathname "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/" *database*))
(check equal (server-pathname (find-server "irc.freenode.org"))
(merge-pathnames #P"servers/irc.freenode.org/" *database*))
(check equal (server-pathname "irc.freenode.org")
(server-pathname (find-server "irc.freenode.org")))
(check equal (server-pathname :wild)
(merge-pathnames #P"servers/*/" *database*))
(check equal (server-datafile-pathname "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/server.sexp" *database*))
(check equal (server-datafile-pathname (find-server "irc.freenode.org"))
(merge-pathnames #P"servers/irc.freenode.org/server.sexp" *database*))
(check equal (server-datafile-pathname "irc.freenode.org")
(server-datafile-pathname (find-server "irc.freenode.org")))
(expect-condition 'error (user-pathname "pjb"))
(check equal (user-pathname "pjb" "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/users/pjb.sexp" *database*))
(check equal (user-pathname "pjb" (find-server "irc.freenode.org"))
(merge-pathnames #P"servers/irc.freenode.org/users/pjb.sexp" *database*))
(check equal (user-pathname (find-user (find-server "irc.freenode.org") "pjb"))
(merge-pathnames #P"servers/irc.freenode.org/users/pjb.sexp" *database*))
(check equal (user-pathname (find-user "irc.freenode.org" "pjb"))
(merge-pathnames #P"servers/irc.freenode.org/users/pjb.sexp" *database*))
(check equal (user-pathname :wild "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/users/*.sexp" *database*))
(expect-condition 'error (channel-pathname "#lisp"))
(check equal (channel-pathname "#lisp" "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/channels/#lisp/" *database*))
(check equal (channel-pathname "#lisp" (find-server "irc.freenode.org"))
(merge-pathnames #P"servers/irc.freenode.org/channels/#lisp/" *database*))
(check equal (channel-pathname (find-channel (find-server "irc.freenode.org") "#lisp"))
(merge-pathnames #P"servers/irc.freenode.org/channels/#lisp/" *database*))
(check equal (channel-pathname (find-channel "irc.freenode.org" "#lisp"))
(merge-pathnames #P"servers/irc.freenode.org/channels/#lisp/" *database*))
(check equal (channel-pathname :wild "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/channels/*/" *database*))
(check equal (log-file-pathname (ensure-channel "irc.freenode.org" "#lisp") 201602)
(merge-pathnames #P"servers/irc.freenode.org/channels/#lisp/logs/201602.log" *database*))
(check equal (requests-pathname "irc.freenode.org")
(merge-pathnames #P"servers/irc.freenode.org/requests.sexp" *database*))
(check equal (requests-pathname server)
(merge-pathnames #P"servers/irc.freenode.org/requests.sexp" *database*))
)))
(define-test test/users ()
(with-temporary-database
(let* ((server (create-server "irc.freenode.org"))
(user (ensure-user server "pjb"))
(channel (ensure-channel server "#lisp")))
(declare (ignorable server user channel))
(check eq (find-user server "pjb") (ensure-user server "pjb"))
)))
(define-test test/requests ()
(with-temporary-database
(let ((server (create-server "irc.freenode.org")))
(create-request (ensure-channel server "#lisp") (ensure-user server "pjb"))
(create-request (ensure-channel server "#clnoobs") (ensure-user server "pjb"))
(create-request (ensure-channel server "#lisp") (ensure-user server "foo"))
(let ((all (requests server))
(lisp (requests (ensure-channel server "#lisp")))
(clnoobs (requests (ensure-channel server "#clnoobs")))
(foo (requests (ensure-user server "foo")))
(pjb (requests (ensure-user server "pjb"))))
(check = (length all) 3)
(check = (length lisp) 2)
(check = (length clnoobs) 1)
(check = (length pjb) 2)
(check = (length foo) 1)
(assert-true (subsetp lisp all))
(assert-true (subsetp clnoobs all))
(assert-true (subsetp foo all))
(assert-true (subsetp pjb all)))
(create-request (ensure-channel server "#time") (ensure-user server "foo") 12000 15500)
(create-request (ensure-channel server "#time") (ensure-user server "pjb") 10000 12500)
(create-request (ensure-channel server "#time") (ensure-user server "pjb") 11000 13500)
(create-request (ensure-channel server "#time") (ensure-user server "bar") 13000 14500)
(let ((all (requests (ensure-channel server "#time"))))
(check = (length all) 4)
(loop
:for (a b) :on all
:while b
:do (assert-true (<= (start-date a) (start-date b)))))
(let ((channel (ensure-channel server "#time")))
(assert-false (channel-active-p channel 9600))
(assert-true (channel-active-p channel 10600))
(assert-true (channel-active-p channel 11600))
(assert-true (channel-active-p channel 12600))
(assert-true (channel-active-p channel 13600))
(assert-true (channel-active-p channel 14600))
(assert-true (channel-active-p channel 15600))
(assert-false (channel-active-p channel 16600))
(loop :for time :from 8600 :to 17600 :by 1000
:for results :in '((10000 nil)
(10000 nil)
(11000 12500)
(12000 12500)
(13000 13500)
(nil 15500)
(nil 15500)
(nil nil)
(nil nil))
:do (check eql (channel-next-start-log-date channel time) (first results))
(check eql (channel-next-stop-log-date channel time) (second results)))
(create-request channel (ensure-user server "pjb") 9000)
(check eql (channel-next-start-log-date channel 8600) 9000)
(check eql (channel-next-stop-log-date channel 8600) nil)
(loop :for time :from 9600 :to 17600 :by 1000
:do (check eql (channel-next-start-log-date channel time) t)
(check eql (channel-next-stop-log-date channel time) t))
(loop :for time :from 9600 :to 17600 :by 1000
:do (assert-true (channel-active-p channel time)
(time)))))))
(define-test test/predicates ()
(dolist (nick '("pjb" "[pjb]" "pjb`"))
(assert-true (nicknamep nick)))
(dolist (nick '("hello world" "#lisp" "!foo" "&bar" "+baz"))
(assert-false (nicknamep nick)))
(dolist (channel '("#lisp" "##lisp" "&lisp" "+lisp"
"#foo~" "##b^ar" "&!quux!" "+~-/*+"
"!ABCDE" "!01234" "!56789"
"#lisp:foo" "##lisp:bar" "&lisp:baz" "+lisp:quux"
"#foo~:1234" "##b^ar:/div" "&!quux!:hey" "+~-/*+:--"
"!ABCDE:;-)" "!01234:\\" "!56789:yep"))
(assert-true (channel-name-p channel)))
(dolist (channel '("!foo" "!1234567" "!ZORRO" "pjb"))
(assert-false (channel-name-p channel)))
(dolist (server '("irc.freenode.org" "01.irc.example.net" "localhost"))
(assert-true (server-name-p server)))
(dolist (server '("#lisp" "foo.%a6t%a7.com"))
(assert-false (server-name-p server))))
(define-test test/all ()
(test/botil-grammar)
(test/predicates)
(test/users)
(test/pathnames)
(test/requests))
#-(and)
(progn
(let (s)
(com.informatimago.common-lisp.cesarum.list:maptree
(lambda (node) (if (symbolp node) (push node s)))
sexp)
(mapcar (function symbol-name) (sort (remove-duplicates s) (function string<))) )
(mapcar (function symbol-name)
(sort (remove-duplicates
(let (ss
(p (find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL")))
(do-symbols (s p ss)
(when (and (fboundp s)
(eql (symbol-package s) p)
(not (com.informatimago.common-lisp.cesarum.sequence:prefixp "BOTIL/PARSE-" (symbol-name s))))
(push s ss)))))
(function string<)))
(mapcar (function symbol-name)
(sort (remove-duplicates
(let (ss
(p (find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTIL")))
(do-symbols (s p ss)
(when (and (boundp s)
(eql (symbol-package s) p))
(push s ss)))))
(function string<)))
(progn
(create-request (ensure-channel (first *servers*) "#lisp")
(ensure-user (first *servers*) "pjb"))
(create-request (ensure-channel (first *servers*) "#clnoobs")
(ensure-user (first *servers*) "pjb"))
(create-request (ensure-channel (first *servers*) "#lisp")
(ensure-user (first *servers*) "foo")))
(values
(requests (first *servers*))
(requests (ensure-channel (first *servers*) "#lisp"))
(requests (ensure-channel (first *servers*) "#clnoobs"))
(requests (ensure-user (first *servers*) "foo"))
(requests (ensure-user (first *servers*) "pjb")))
)
;; (test/all)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
;; (untrace ensure-user)
;; (reconnect (first *servers*))
;; (ql:quickload :com.informatimago.small-cl-pgms.botil)
;; (find-user (first *servers*) "ogam")
;; (mapcar (lambda (f) (funcall f (find-user (first *servers*) "ogam"))) '(name email password key verified))
;; (reset (find-user (first *servers*) "ogam") nil)
| 100,659 | Common Lisp | .lisp | 2,076 | 37.948459 | 139 | 0.545564 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 599719f5332452d69b49e95953d649f289028ad3b22c1970c26c36c7239d9d5a | 4,872 | [
-1
] |
4,873 | loader.lisp | informatimago_lisp/small-cl-pgms/botil/loader.lisp | (cd #P"/Users/pjb/src/public/lisp/small-cl-pgms/botil/")
(push (pwd) asdf:*central-registry*)
(ql:quickload :com.informatimago.small-cl-pgms.botil)
(in-package :com.informatimago.small-cl-pgms.botil)
(com.informatimago.small-cl-pgms.botil:main)
| 245 | Common Lisp | .lisp | 5 | 48 | 56 | 0.775 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 4900949837c9fd1ead64c8cea8cf48ba770c938683910b504e3c6e6b9e7c08a0 | 4,873 | [
-1
] |
4,874 | sudoku-solver.lisp | informatimago_lisp/small-cl-pgms/sudoku-solver/sudoku-solver.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: sudoku-solver.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A sudoku solver.
;;;;
;;;; I never tried to solve a sudoku myself… and never will.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-12-02 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2023
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SUDOKU-SOLVER"
(:use "COMMON-LISP")
(:export "SUDOKU-SOLVER" "SUDOKU-PRINT"))
(in-package "COM.INFORMATIMAGO.SUDOKU-SOLVER")
(defun iota (count &optional (start 0) (step 1))
"
RETURN: A list containing the elements
(start start+step ... start+(count-1)*step)
The start and step parameters default to 0 and 1, respectively.
This procedure takes its name from the APL primitive.
EXAMPLE: (iota 5) => (0 1 2 3 4)
(iota 5 0 -0.1) => (0 -0.1 -0.2 -0.3 -0.4)
"
(loop
:for item = start :then (+ item step)
:repeat count
:collect item))
(defun copy-array (array &key copy-fill-pointer copy-adjustable
copy-displacement)
"
RETURN: A copy of the ARRAY.
ARRAY: An array.
COPY-FILL-POINTER: Indicate whether the copy must have the same
FILL-POINTER as the ARRAY.
COPY-ADJUSTABLE: Indicate whether the copy must be an adjustable
array when the ARRAY is adjustable.
COPY-DISPLACEMENT: Indicate whether the copy must be an array
displaced to the same array as the ARRAY.
"
(when copy-displacement
(multiple-value-bind (disto disoff) (array-displacement array)
(when disto
(return-from copy-array
(make-array (array-dimensions array)
:element-type (array-element-type array)
:displaced-to disto
:displaced-index-offset disoff
:adjustable (when copy-adjustable
(adjustable-array-p array))
:fill-pointer (when copy-fill-pointer
(fill-pointer array)))))))
(let ((copy (make-array (array-dimensions array)
:adjustable (when copy-adjustable
(adjustable-array-p array))
:fill-pointer (when copy-fill-pointer
(fill-pointer array))
:element-type (array-element-type array))))
(dotimes (i (array-total-size copy))
(setf (row-major-aref copy i) (row-major-aref array i)))
copy))
(defun make-sudoku ()
(make-array '(9 9) :initial-element 'x))
(defun emptyp (slot)
(or (null slot)
(and (symbolp slot)
(string= slot 'x))))
(defun list-or-single-element (list)
(if (null (rest list))
(first list)
list))
(defun row (sudoku row)
"Return the list of elements present in the row ROW of the sudoku."
(loop
:for col :below (array-dimension sudoku 0)
:for item = (aref sudoku col row)
:unless (emptyp item)
:collect item))
(defun col (sudoku col)
"Return the list of elements present in the column COL of the sudoku."
(loop
:for row :below (array-dimension sudoku 1)
:for item = (aref sudoku col row)
:unless (emptyp item)
:collect item))
(defun reg (sudoku col row)
"Return the list of elements present in the region containing slot
\(col row) of the sudoku."
(loop
:with bac = (* (truncate col 3) 3)
:with bar = (* (truncate row 3) 3)
:for i :from bac :below (+ bac 3)
:nconc (loop
:for j :from bar :below (+ bar 3)
:for item = (aref sudoku i j)
:unless (emptyp item)
:collect item)))
#+emacs (put 'for-each-slot 'common-lisp-indent-function 1)
(defmacro for-each-slot ((slot-and-var sudoku) &body body)
"
SLOT-AND-VAR: either a symbol naming the variable that will be bound to the slot,
or a list (slot i j) of three symbols naming the variables that
will be bound to the slot, the row and the column indices.
SUDOKU: An expression that evaluates to a sudoku board.
BODY: A list of lisp forms.
DO: Evaluates the BODY for each slot in the sudoku board, in
a lexical context where the slot variable and when
present, the row and column indices variables are bound
to the slot and indices, for each slot of the sudoku
board. The slot variable can be modified and this
changes the slot in the sudoku board.
RETURN: no value.
"
(let ((i (gensym "i"))
(j (gensym "j"))
(di (gensym "di"))
(dj (gensym "dj"))
(s (gensym "s"))
(slot (if (atom slot-and-var)
slot-and-var
(first slot-and-var)))
(ivar (if (atom slot-and-var)
nil
(progn
(assert (second slot-and-var) () "The ivar must not be NIL")
(second slot-and-var))))
(jvar (if (atom slot-and-var)
nil
(progn
(assert (third slot-and-var) () "The jvar must not be NIL")
(third slot-and-var)))))
`(loop
:with ,s = ,sudoku
:with ,di = (array-dimension ,s 0)
:with ,dj = (array-dimension ,s 1)
:for ,i :below ,di
:do ,(if ivar
`(loop
:with ,ivar = ,i
:for ,j :below ,dj
:do (symbol-macrolet ((,slot (aref ,s ,i ,j)))
(let ((,jvar ,j))
,@body)))
`(loop
:for ,j :below ,dj
:do (symbol-macrolet ((,slot (aref ,s ,i ,j)))
,@body)))
:finally (return (values)))))
(defun optimalize (matrix &key (key (function identity)) (lessp (function <)))
"
DO: Find the extremum of the values obtained by calling the KEY
function on each slot of the MATRIX, using the LESSP
comparator.
RETURN: If an extremum is found: the extremum value; the row; the column;
otherwise NIL; -1; -1.
"
(let ((mini -1)
(minj -1)
(minv nil))
(for-each-slot ((slot i j) matrix)
(let ((val (funcall key slot)))
(if minv
(when (funcall lessp val minv)
(setf minv val
mini i
minj j))
(setf minv val
mini i
minj j))))
(values minv mini minj)))
(defun conflictp (sudoku col row)
"Predicates whether there's a conflict around slot (col row)."
(let ((val (aref sudoku col row)))
(loop
:for i :below (array-dimension sudoku 0)
:when (and (/= i col) (eql val (aref sudoku i row)))
:do (return-from conflictp :row-conflict))
(loop
:for j :below (array-dimension sudoku 1)
:when (and (/= j row) (eql val (aref sudoku col j)))
:do (return-from conflictp :col-conflict))
(loop
:with from := (* (truncate col 3) 3)
:for i :from from :below (+ from 3)
:when (/= i col)
:do (loop
:with from := (* (truncate row 3) 3)
:for j :from from :below (+ from 3)
:when (and (/= j row) (eql val (aref sudoku i j)))
:do (return-from conflictp :reg-conflict)))
nil))
(defvar *sudoku-tries* 0)
(defun sudoku-backtracking (sudoku)
"
PRE: The slots of sudoku contain either an atom, an empty list,
or a list of two or more atoms.
DO: If there is an empty list in one of the slots, then throws
the SUDOKU-BACKTRACK symbol.
Else finds a slot with a small list, and tries each atom
in it in turn.
RETURN: A list of sudoku solutions boards.
"
(multiple-value-bind (possibles i j)
(optimalize sudoku :key (let ((infinite (reduce (function +)
(array-dimensions sudoku))))
(lambda (slot)
(cond
((null slot) (throw 'sudoku-backtrack nil))
((listp slot) (length slot))
(t infinite)))))
(declare (ignore possibles))
;; (format t "Found a small set of choices at (~D ~D): ~S~%" i j (aref sudoku i j))
(if (consp (aref sudoku i j))
(loop
:with results = '()
:for val :in (aref sudoku i j)
:do (catch 'sudoku-backtrack
(incf *sudoku-tries*)
(let ((sudoku (copy-array sudoku))
(check-list '()))
(setf (aref sudoku i j) val)
;; (format t "Trying to put ~D at (~D ~D)~%" val i j)
;; (sudoku-print sudoku)
(loop
:named update-col
:for col :below (array-dimension sudoku 0)
:do (cond
((= col i))
((listp (aref sudoku col j))
(setf (aref sudoku col j) (list-or-single-element (remove val (aref sudoku col j))))
(when (atom (aref sudoku col j))
(push (list col j) check-list)))
((eql (aref sudoku col j) val)
;; (format t " won't do, there's already a ~D on the same row.~%" val)
(throw 'sudoku-backtrack nil))))
(loop
:named update-row
:for row :below (array-dimension sudoku 1)
:do (cond
((= row j))
((listp (aref sudoku i row))
(setf (aref sudoku i row) (list-or-single-element (remove val (aref sudoku i row))))
(when (atom (aref sudoku i row))
(push (list i row) check-list)))
((eql (aref sudoku i row) val)
;; (format t " won't do there's already a ~D on the same column.~%" val)
(throw 'sudoku-backtrack nil))))
(loop
:named update-reg
:with from := (* (truncate i 3) 3)
:for col :from from :below (+ from 3)
:do (loop
:with from := (* (truncate j 3) 3)
:for row :from from :below (+ from 3)
:do (cond
((and (= col i) (= row j)))
((listp (aref sudoku col row))
(setf (aref sudoku col row) (list-or-single-element (remove val (aref sudoku col row))))
(when (atom (aref sudoku col row))
(push (list col row) check-list)))
((eql (aref sudoku col row) val)
;; (format t " won't do there's already a ~D in the same region.~%" val)
(throw 'sudoku-backtrack nil)))))
(loop
:for (col row) :in check-list
:for conflict = (conflictp sudoku col row)
:do (when conflict
;; (format t " won't do, there'd be a ~(~A~) at (~D ~D).~%" conflict col row)
(throw 'sudoku-backtrack nil)))
;; (format t " fits so far.~%")
;; (sudoku-print sudoku)
(setf results (nconc (sudoku-backtracking sudoku) results))))
:finally (return results))
(list sudoku))))
(defun sudoku-solver (sudoku)
"
DO: Solves the SUDOKU board (it contains atoms and X or NIL that
are replaced in the solutions by the atoms required by the
rules.
RETURN: A list of sudoku solution boards.
"
(let* ((*sudoku-tries* 1)
(sudoku (copy-array sudoku))
;; Well for now, the atoms are integers from 1 up to the
;; maximal dimension of the matrix.
(all (iota (max (array-dimension sudoku 0)
(array-dimension sudoku 1))
1))
(cols (coerce (loop :for col :below (array-dimension sudoku 0) :collect (col sudoku col)) 'vector))
(rows (coerce (loop :for row :below (array-dimension sudoku 1) :collect (row sudoku row)) 'vector))
(regs (let ((regs (make-array (mapcar (lambda (x) (ceiling x 3)) (array-dimensions sudoku)))))
(loop
:for i :below (array-dimension regs 0)
:do (loop
:for j :below (array-dimension regs 1)
:do (setf (aref regs i j) (reg sudoku (* 3 i) (* 3 j)))))
regs)))
(for-each-slot ((slot i j) sudoku)
(when (emptyp slot)
(let ((possibles (set-difference all (union
(union (aref cols i) (aref rows j))
(aref regs (truncate i 3) (truncate j 3))))))
(setf slot (list-or-single-element possibles)))))
(catch 'sudoku-backtrack
(values (sudoku-backtracking sudoku) *sudoku-tries*))))
(defun sudoku-print (sudoku &optional (*standard-output* *standard-output*))
"
DO: Prints the SUDOKU board to the optional stream given.
RETURN SUDOKU.
"
(loop
:with =line = (with-output-to-string (*standard-output*)
(loop
:repeat (array-dimension sudoku 1)
:do (princ "+---")
:finally (princ "+") (terpri)))
:with -line = (with-output-to-string (*standard-output*)
(loop
:for i :below (array-dimension sudoku 1)
:do (princ (if (zerop (mod i 3)) "| " "+ "))
:finally (princ "|") (terpri)))
:for i :below (array-dimension sudoku 0)
:do (princ (if (zerop (mod i 3)) =line -line))
:do (loop
:for j :below (array-dimension sudoku 1)
:do (format t (if (zerop (mod j 3)) "|~2@A " " ~2@A ")
(let ((slot (aref sudoku i j)))
(if (emptyp slot)
"."
slot)))
:finally (princ "|") (terpri))
:finally (princ =line) (terpri))
sudoku)
(defun sudoku-count-empty-slots (sudoku)
(let ((empty-count 0))
(for-each-slot (slot sudoku)
(when (emptyp slot)
(incf empty-count)))
empty-count))
;;----------------------------------------------------------------------
(defparameter *royco-minut-soup* #2A((x x x 8 x 4 2 x x)
(6 x 8 x 2 x x x 4)
(2 1 x 6 5 3 x x 8)
(x 7 x 2 x 6 x 9 x)
(x x x x 3 x 1 x x)
(4 2 3 x x 9 x 5 7)
(x 6 x 4 1 5 7 x x)
(x x 7 x x 8 3 x x)
(x 5 9 x x x x 1 x)))
(defparameter *20-minutes/1499/facile* #2A((2 x 4 1 5 x 8 7 x)
(x x x 3 x x x 9 1)
(x 7 x 8 6 x x x 4)
(x x 3 x 2 1 x 8 x)
(x x 1 x 8 x 3 x x)
(x 8 x 4 3 x 9 x x)
(9 x x x 1 3 x 6 x)
(3 2 x x x 4 x x x)
(x 1 7 x 9 8 4 x 3)))
(defparameter *20-minutes/1501/difficile* #2A((x 1 5 x 8 9 x x x)
(2 x 6 3 x 5 x x x)
(x 7 x x x x x 8 x)
(x 6 9 x x 1 x x 3)
(x x x 8 x 3 x x x)
(3 x x 6 x x 2 9 x)
(x 9 x x x x x 2 x)
(x x x 9 x 6 1 x 5)
(x x x 7 1 x 9 3 x)))
(defparameter *20-minutes/1502/expert* #2A((5 7 x x x x x x x)
(x x 8 x x x 1 7 x)
(x 1 x 7 x 4 x 2 8)
(x x 1 x 4 x x 8 5)
(x 5 x x 1 x x 3 x)
(8 6 x x 7 x 4 x x)
(1 4 x 3 x 9 x 6 x)
(x 3 2 x x x 9 x x)
(x x x x x x x 1 3)))
(defparameter *20-minutes/1505/moyen* #2A((1 x 2 x 6 5 9 x x)
(x 4 x 8 x x x x 5)
(x 8 x 1 x x 4 3 6)
(x x 1 9 x x x x x)
(6 5 x x x x x 4 9)
(x x x x x 6 1 x x)
(2 1 3 x x 8 x 5 x)
(8 x x x x 2 x 9 x)
(x x 4 5 7 x 3 x 2)))
(defparameter *20-minutes/1506/facile* #2A((3 x 5 8 4 x x x 1)
(7 x x x x x 5 x x)
(4 x 1 6 3 x 8 x x)
(8 x x x x x 3 5 7)
(x x 3 x x x 9 x x)
(6 1 9 x x x x x 8)
(x x 8 x 6 2 4 x 5)
(x x 7 x x x x x 2)
(2 x x x 5 1 7 x 3)))
(defparameter *metrofrance/694/moyen* #2A((x x 1 2 x x x x 8)
(x x x x 5 1 x x 3)
(x 7 x x x x 6 x 1)
(9 x 4 x 1 7 x x 5)
(1 3 x x x x x 2 9)
(8 x x 9 2 x 1 x 4)
(4 x 6 x x x x 1 x)
(3 x x 8 7 x x x x)
(7 x x x x 4 3 x x)))
(defparameter *metrofrance/696/facile* #2A((2 4 x 9 x x 7 6 x)
(3 x x x 8 x x x x)
(8 5 x 4 x x x x x)
(5 x x x x 8 4 x x)
(7 x 4 6 9 3 2 x 5)
(x x 9 5 x x x x 3)
(x x x x x 1 x 2 4)
(x x x x 6 x x x 1)
(x 6 8 x x 9 x 5 7)))
(defparameter *metrofrance/700/moyen* #2A ((1 9 x 8 3 7 x x x)
(7 5 x x 2 x x x x)
(4 x x x 9 x x x 7)
(x 3 4 x x x x x 9)
(9 x 7 x x x 6 x 2)
(8 x x x x x 4 7 x)
(3 x x x 1 x x x 6)
(x x x x 6 x x 3 4)
(x x x 9 4 3 x 2 8)))
(defparameter *andre* #2A ((x x x x x 2 x x x)
(1 x x x 3 x x 4 x)
(x x x x 1 9 x 6 x)
(7 x x 3 4 x 1 x 5)
(x x x x x x 8 x x)
(9 x x x x 5 x 3 4)
(2 x 6 x 5 1 x x x)
(x 7 x x x x x x x)
(x x 8 9 x 4 5 7 x)))
(defparameter *240* #2A((7 8 x 2 6 x x x x)
(3 2 4 x x 9 5 x x)
(1 6 x x 3 5 4 x 2)
(x 1 x 4 2 8 x x 9)
(4 x 3 5 x 7 x x x)
(2 x x 6 x 3 7 x 4)
(9 x x x x 1 8 x 5)
(x x 1 9 8 x 6 3 7)
(8 7 x x 5 6 9 x 1)))
(defun solve-sudokus (&key (print t))
(dolist (sudoku '(
*20-minutes/1499/facile*
*20-minutes/1501/difficile*
*20-minutes/1502/expert*
*20-minutes/1505/moyen*
*20-minutes/1506/facile*
*metrofrance/694/moyen*
*metrofrance/696/facile*
*metrofrance/700/moyen*
*royco-minut-soup*
*andre*
*240*
))
(multiple-value-bind (solutions tries) (sudoku-solver (symbol-value sudoku))
(terpri)
(when print
(print sudoku) (terpri)
(sudoku-print (symbol-value sudoku)))
(format t " ~A (with ~D empty slots)~% has ~D solution~:*~P,~% found in ~D tries.~2%"
sudoku (sudoku-count-empty-slots (symbol-value sudoku))
(length solutions) tries)
(when print
(map nil 'sudoku-print solutions)))))
;;----------------------------------------------------------------------
(defun read-grid (stream)
(let ((line (read-line stream nil nil)))
(when (and line (plusp (length line)))
(if (= 81 (length line))
(let ((sudoku (make-sudoku))
(i -1))
(for-each-slot (slot sudoku)
(setf slot (let ((value (digit-char-p (aref line (incf i)))))
(if (and value (plusp value))
value
'x))))
sudoku)
(loop
:with sudoku = (make-sudoku)
:for j :below 9
:for line = (read-line stream)
:do (loop
:for i :below 9
:for value = (digit-char-p (aref line i))
:do (setf (aref sudoku i j) (if (and value (plusp value)) value 'x)))
:finally (return sudoku))))))
(defun solve-grids (grid-file)
(with-open-file (grids grid-file)
(loop
:for sudoku = (read-grid grids)
:while sudoku
:do (multiple-value-bind (solutions tries) (sudoku-solver sudoku)
(sudoku-print sudoku)
(format t " (with ~D empty slots)~% has ~D solution~:*~P,~% found in ~D tries.~2%"
(sudoku-count-empty-slots sudoku)
(length solutions) tries)
(map nil 'sudoku-print solutions)))))
(defun solve-grids/no-print (grid-file)
(with-open-file (grids grid-file)
(loop
:for sudoku = (read-grid grids)
:while sudoku
:collect (multiple-value-bind (solutions tries) (sudoku-solver sudoku)
(declare (ignore solutions))
tries))))
(defun time-dim-grids ()
(dolist (file '(#P"~/src-lisp/usenet/dim-sudoku/sudoku.txt"
#P"~/src-lisp/usenet/dim-sudoku/easy50.txt"
#P"~/src-lisp/usenet/dim-sudoku/top95.txt"
#P"~/src-lisp/usenet/dim-sudoku/hardest.txt"))
(terpri) (print file) (terpri)
(print (time (solve-grids/no-print file)))))
;; (solve-sudokus :print t)
;; (solve-sudokus :print nil)
;;;; THE END ;;;;
| 25,266 | Common Lisp | .lisp | 540 | 30.103704 | 121 | 0.435992 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | cc1e03be55ca8bb515f27eb5038ae91aa65a3c319cb6e1c0a45fb42c1c8264ef | 4,874 | [
-1
] |
4,875 | ibcl-bootstrap.lisp | informatimago_lisp/small-cl-pgms/ibcl/ibcl-bootstrap.lisp | ;;;;**************************************************************************
;;;;FILE: ibcl-bootstrap.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This script generates an executable saved image environment using
;;;; IMAGE-BASED-COMMON-LISP instead of COMMON-LISP.
;;;;
;;;; IBCL Bootstrap
;;;;
;;;; To create the executable image:
;;;;
;;;; clisp -ansi -norc -i ibcl-bootstrap.lisp -p "IBCL"
;;;; sbcl --userinit /dev/null --load ibcl-bootstrap.lisp
;;;;
;;;; Then, to launch it, use:
;;;;
;;;; ./ibcl
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-07-01 <PJB> Added support to SBCL.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(load (merge-pathnames #p"ibcl.lisp" *load-pathname*))
(in-package "COMMON-LISP")
(rename-package (find-package "COMMON-LISP-USER") "OLD-CL-USER")
(defpackage "COMMON-LISP-USER"
(:nicknames "CL-USER")
(:use "IBCL"))
(in-package "IMAGE-BASED-COMMON-LISP-USER")
#+clisp (ext:saveinitmem "ibcl" :executable t)
#+sbcl (sb-ext:save-lisp-and-die
"ibcl" :executable t
:toplevel (lambda ()
(setf *package* (find-package "COMMON-LISP-USER"))
(delete-package (find-package "OLD-CL-USER"))
(sb-posix:putenv
(format nil "SBCL_HOME=~A"
(namestring (user-homedir-pathname))))
(sb-impl::toplevel-repl nil)
(sb-ext:quit 0)))
#-(or clisp sbcl) (error "How do we save an image in ~A"
(lisp-implementation-type))
#+clisp (ext:quit)
#+sbcl (sb-ext:quit)
#-(or clisp sbcl) (error "How do we quit from ~A" (lisp-implementation-type))
| 2,861 | Common Lisp | .lisp | 70 | 36.871429 | 83 | 0.580911 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 9c656619fdd9283a38195a1a45b27361b132959db348ad455ad277e42b952386 | 4,875 | [
-1
] |
4,876 | botvot-test.lisp | informatimago_lisp/small-cl-pgms/botvot/botvot-test.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTVOT")
(eval-when (:compile-toplevel :load-toplevel :execute)
(use-package "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"))
(define-test test/serialize ()
(assert-true (string= (with-output-to-string (out)
(princ "(list" out)
(serialize (choice "pgc1" "yes" "Yes, obj always reachable.") out)
(serialize (choice "pgc1" "no" "No, obj may be GCed.") out)
(serialize (choice "pgc1" "what" "What are presentations?") out)
(princ ")" out))
"(list(choice \"pgc1\" \"yes\" \"Yes, obj always reachable.\")(choice \"pgc1\" \"no\" \"No, obj may be GCed.\")(choice \"pgc1\" \"what\" \"What are presentations?\"))"))
(assert-true (string= (with-output-to-string (out)
(serialize (make-instance 'vote :ballot-id "pgc1"
:choice-id "yes"
:user-id "pjb")
out))
"(vote \"pgc1\" \"0af3a45d6dc7ee8efc3a7aae3f6c33d21d0321776d73aa996060ec35c26cc0a7\" \"yes\" \"5c2031740cd336081cdfbb96b53b12920005aad6334ee070878f7d4dd27ff8a1\")")))
(define-test test/parse-time ()
(assert-true (= (parse-time '("12:00")) 43200))
(assert-true (= (parse-time '("12:00:00")) 43200))
(assert-true (= (parse-time '("00:00:00")) 0))
(assert-true (= (parse-time '("00:00")) 0))
(assert-true (= (parse-time '("10:30")) 37800))
(assert-true (= (parse-time '("10:30:33")) 37833))
(assert-true (= (parse-time '("1:2:3")) 3723))
(assert-true (= (parse-time '("1" "hour")) 3600))
(assert-true (= (parse-time '("1" "hours")) 3600))
(assert-true (= (parse-time '("1" "oclock")) 3600))
(assert-true (= (parse-time '("1" "o'clock")) 3600)))
(define-test test/parse-deadline ()
;; on mon|tue|wed|thi|fri|sat|sun at $h [hours|o'clock]
;; on mon|tue|wed|thi|fri|sat|sun at $HH:MM
;; at $h [hours|o'clock]
;; at $HH:MM
(assert-true (equal (parse-deadline '("in" "1" "d")) '(:relative 86400)))
(assert-true (equal (parse-deadline '("in" "1" "day")) '(:relative 86400)))
(assert-true (equal (parse-deadline '("in" "1" "days")) '(:relative 86400)))
(assert-true (equal (parse-deadline '("in" "1" "h")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "1" "hour")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "1" "hours")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "60" "m")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "60" "min")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "60" "minute")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "60" "minutes")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "3600" "s")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "3600" "sec")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "3600" "second")) '(:relative 3600)))
(assert-true (equal (parse-deadline '("in" "3600" "seconds")) '(:relative 3600)))
(assert-true (parse-deadline '("on" "mon" "at" "12" "o'clock")))
(assert-true (parse-deadline '("on" "Tuesday" "at" "12" "o'clock")))
(assert-true (parse-deadline '("at" "12" "o'clock")))
(assert-true (parse-deadline '("at" "12" "oclock")))
(assert-true (parse-deadline '("at" "12" "hours")))
(assert-true (parse-deadline '("at" "12" "hour")))
(assert-true (parse-deadline '("at" "12:00")))
(assert-true (parse-deadline '("at" "12:00:00")))
(assert-true (= (parse-deadline '("at" "12" "o'clock"))
(parse-deadline '("at" "12" "oclock"))
(parse-deadline '("at" "12" "hours"))
(parse-deadline '("at" "12" "hour"))
(parse-deadline '("at" "12:00"))
(parse-deadline '("at" "12:00:00")))))
(define-test test/command-matches ()
(assert-true (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("set")))
(assert-true (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("ballot")))
(assert-true (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("title")))
(assert-true (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("ballot" "title")))
(assert-true (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title")))
(assert-true (not (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("vote" "ballot"))))
(assert-true (not (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title" "pg1"))))
(assert-true (not (command-matches-approximatively '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title" "pg1" "Presentation Garbage Collection"))))
(assert-true (not (command-matches-exactly '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title" "pg1"))))
(assert-true (command-matches-exactly '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title" "pg1" "Presentation Garbage Collection")))
(assert-true (equalp (multiple-value-list (command-matches-exactly '("set" (opt "ballot") "title" ballot-id title)
'("set" "ballot" "title" "pg1" "Presentation Garbage Collection")))
'(t ((title . "Presentation Garbage Collection") (ballot-id . "pg1")))))
(assert-true (command-matches-exactly '("set" (opt "ballot") "title" ballot-id title)
'("set" "title" "pg1" "Presentation Garbage Collection")))
(assert-true (equalp (multiple-value-list (command-matches-exactly '("set" (opt "ballot") "title" ballot-id title)
'("set" "title" "pg1" "Presentation Garbage Collection")))
'(t ((title . "Presentation Garbage Collection") (ballot-id . "pg1"))))))
(define-test test/parse-words ()
(assert-true (equal (parse-words "goldorak")
'("goldorak")))
(assert-true (equal (parse-words "gold orak")
'("gold" "orak")))
(assert-true (equal (parse-words " gold orak ")
'("gold" "orak")))
(assert-true (equal (parse-words "gold orak & acta rus")
'("gold" "orak" "&" "acta" "rus")))
(assert-true (equal (parse-words "\"gold orak\" & \"acta rus\"")
'("gold orak" "&" "acta rus")))
(assert-true (equal (parse-words "\"gold \\\"orak\\\"\" & \"acta rus\"")
'("gold \"orak\"" "&" "acta rus")))
(assert-true (equal (parse-words " \"goldorak & actarus\" ")
'("goldorak & actarus")))
(assert-true (handler-case (parse-words " \"goldorak & actarus")
(:no-error (&rest results)
(declare (ignore results))
nil)
(error ()
t))))
(define-test test/all ()
(test/serialize)
(test/parse-time)
(test/parse-deadline)
(test/command-matches)
(test/parse-words))
| 8,089 | Common Lisp | .lisp | 120 | 53.983333 | 188 | 0.523235 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 79bae0f561b9beec4da6993eee92c2823bd85d6b616346d80cf6a30f32677307 | 4,876 | [
-1
] |
4,877 | generate-application.lisp | informatimago_lisp/small-cl-pgms/botvot/generate-application.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: generate-application.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Save the botvot executable.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-04-14 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
(progn (format t "~%;;; Loading quicklisp.~%") (finish-output) (values))
(load #P"~/quicklisp/setup.lisp")
(ql:register-local-projects)
(progn (format t "~%;;; Loading botvot.~%") (finish-output) (values))
(setf asdf:*central-registry*
(append (mapcar (lambda (path)
(make-pathname :name nil :type nil :version nil
:defaults path))
(directory (merge-pathnames
#P"../../**/*.asd"
*load-truename*)))
asdf:*central-registry*))
;; (format t "~&;;; asdf:*central-registry* = ~S~%" asdf:*central-registry*)
(ql:quickload :com.informatimago.small-cl-pgms.botvot)
#+ccl (pushnew 'com.informatimago.common-lisp.interactive.interactive:initialize
ccl:*restore-lisp-functions*)
(progn (format t "~%;;; Saving botvot.~%") (finish-output) (values))
;; This doesn't return.
#+ccl (ccl::save-application
"botvot"
:mode #o755 :prepend-kernel t
:toplevel-function (function com.informatimago.small-cl-pgms.botvot:main)
:init-file nil ;; "~/.botvot.lisp"
:error-handler :quit)
| 2,664 | Common Lisp | .lisp | 60 | 39.583333 | 83 | 0.587308 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b1ae13c235a4331cd02173701ea3a56f3e7174d4e8683ff76f8c16f884c458e2 | 4,877 | [
-1
] |
4,878 | botvot.lisp | informatimago_lisp/small-cl-pgms/botvot/botvot.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: botvot.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: IRC
;;;;DESCRIPTION
;;;;
;;;; Botvot: an IRC bot monitoring Hacker News.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-04-14 <PJB> Reconverted into botvot.
;;;; 2019-08-27 <PJB> Added blacklist.
;;;; 2015-07-17 <PJB> Added commands: help uptime version sources; added restarts.
;;;; 2015-04-27 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTVOT"
(:use "COMMON-LISP"
"CL-IRC" "SPLIT-SEQUENCE" "CL-PPCRE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.UTILITY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.FILE")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.INTERACTIVE.INTERACTIVE"
"DATE" "UPTIME")
(:export "MAIN" "BALLOT-REPL")
(:documentation "
Botvot is a simple IRC bot to manage ballots.
It is run with:
(com.informatimago.small-cl-pgms.botvot:main)
Copyright Pascal J. Bourguignon 2015 - 2021
Licensed under the AGPL3.
"))
(in-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTVOT")
(defparameter *version* "1.0")
;;;
;;; Configuration:
;;;
(defvar *server* "irc.freenode.org"
"The fqdn of the IRC server.")
(defvar *nickname* "botvot"
"The nickname of the botvot user.")
(defvar *sources-url*
"https://gitlab.com/com-informatimago/com-informatimago/tree/master/small-cl-pgms/botvot/"
"The URL where the sources of this ircbot can be found.")
(defvar *connection* nil
"The current IRC server connection.")
(defvar *botpass* "1234")
(defvar *ballots* '()
"A list of ballots.")
(defvar *ballot-file* #P"/usr/local/var/botvot/ballot.sexp"
"Path of the file where the *ballot* is saved.")
;; All the data is serialized to the *ballot-file* after each mutation,
;; and when zombie ballots are garbage collected.
(defvar *ballot-zombie-life* (days 15)
"Delete closed or cancelled ballots older than that.")
(defvar *requester-nick* nil
"Nickname of the user who send the current command.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun seconds (x) x)
(defun minutes (x) (* x 60))
(defun hours (x) (* x 60 60))
(defun days (x) (* x 24 60 60)))
(defconstant +minimum-relative-deadline+ (minutes 30))
;;;
;;; Types and classes:
;;;
(deftype octet () `(unsigned-byte 8))
(deftype universal-time () `integer)
(deftype ballot-state () `(member :editing :open :closed :cancelled))
(defclass choice ()
((ballot-id :reader ballot-id :type string :initarg :ballot-id)
(id :reader choice-id :type string :initarg :choice-id)
(title :accessor title :type string :initarg :title)))
(defclass vote ()
((ballot-id :reader ballot-id :type string :initarg :ballot-id)
(user-id-hash :reader user-id-hash :type string :initarg :user-id-hash)
(choice-id :reader choice-id :type string :initarg :choice-id)
(choice-id-hash :reader choice-id-hash :type string :initarg :choice-id-hash)))
(defclass ballot ()
((id :reader ballot-id :type string :initarg %id)
(title :accessor title :type string :initarg :title)
(deadline :reader ballot-deadline :type (or universal-time list) :initarg :deadline)
(remind-period :reader ballot-remind-period :type integer :initarg :remind-period)
(owner :reader ballot-owner :type string :initarg :owner)
(password-hash :reader ballot-password-hash :type string :initarg %password-hash)
(secret-seed :reader ballot-secret-seed :type (vector octet) :initarg %secret-seed)
(state :reader ballot-state :type ballot-state :initarg %state :initform :editing)
(last-publication :reader ballot-last-publication :type universal-time :initarg %last-publication :initform 0)
(channels :reader ballot-channels :type list :initarg %channels :initform '())
(choices :reader ballot-choices :type list :initarg %choices :initform '())
(votes :reader ballot-votes :type list :initarg %votes :initform '())))
#|
The BALLOT-ID are unique IDs amongst *ballots*. They could be reused
only when a ballot is deleted from the system.
The TITLE of a ballot can be changed at will by the ballot owner while
the ballot is in state :EDITING.
The DEADLINE is either a UNIVERSAL-TIME specifying an absolute
deadline, or a list (:relative offset), which specifies a deadline
relatively to the open datetime. When the ballot goes to the :OPEN
state, the relative deadline is replaced by an absolute deadline
computed from the current universal-time.
The REMIND-PERIOD is a period (in seconds) for publishing reminders to
the ballot channels, before the deadline. The time of reminder
publishing are computed from the deadline:
(- deadline (* n remind-period))
The LAST-PUBLICATION universal-time is the date of the last
publication message. A new publication can only occur after:
(+ last-publication remind-period).
The OWNER of the ballot is the user-id of the user who created the
ballot and who is the sole user allowed to edit it and to open or
cancel it. The owner specifies a password for critical operations
(open and cancel).
When the ballot is created, a random SECRET-SEED value is computed, to
be used to compute the other hashes.
The ballot STATES are: :EDITING :OPEN :CANCELED :CLOSED
- when created, the ballot is in the :EDITING state which
allows modification of some parameters, such as title, and the choices.
- once ready the ballot can be put in the :OPEN state, which allows
the users to vote, and reminders to be published to the channels.
The relative deadlines are computed from the time the ballot goes to
the :OPEN state.
- the owner can move a ballot to the :CANCELED state, which stops any
operation for the ballot.
- when the deadline passes without the ballot being cancelled, the
ballot goes to the :CLOSED state, and the results of the vote are
then published, and available for query.
The CHANNELS is a list of IRC channel names (strings starting with
"#"), where the reminders and ballot results are sent.
The CHOICES is a list of ballot choices, that can be selected by the
voters.
The VOTES is a list of votes, at most one per user, selecting one choice.
When the ballot is closed those votes are tallied by choice.
The VOTE instances contain a user-id-hash to ensure that only one vote
per user is present, and a choice-id-hash to validate the vote of each
user.
user-id-hash = (sha256-hash user-id)
choice-id-hash = (sha256-hash (concat user-id-hash ballot-id choice-id))
|#
;;;
;;; Conditions
;;;
(define-condition deadline-syntax-error (error)
((words :initarg :words :reader deadline-syntax-error-words))
(:report (lambda (condition stream)
(format stream "Invalid deadline specification syntax: ~{~A~^ ~}. Try: in X days|hours|minutes|seconds "
(deadline-syntax-error-words condition)))))
(define-condition deadline-too-close (error)
((specification :initarg :specification :reader deadline-too-close-deadline-specification)
(minimum-relative :initarg :minimum-relative-deadline :reader deadline-too-close-minimum-relative-deadline))
(:report (lambda (condition stream)
(format stream "Deadline ~S too close. Must be at least ~A hours from now."
(deadline-too-close-deadline-specification condition)
(deadline-too-close-minimum-relative-deadline condition)))))
(define-condition invalid-vote-data (error)
((vote :initarg :vote :reader invalid-vote-data-vote)
(choice-id-hash :initarg :choice-id-hash :reader invalid-vote-data-choice-id-hash))
(:report (lambda (condition stream)
(format stream "Invalid vote choice-id-hash for ~S: ~S"
(invalid-vote-data-vote condition)
(invalid-vote-data-choice-id-hash condition)))))
(define-condition owner-error (error)
((ballot :initarg :ballot :reader owner-error-ballot)
(user-id :initarg :user-id :reader owner-error-user-id))
(:report (lambda (condition stream)
(format stream "User ~S is not owner of ballot ~S"
(owner-error-user-id condition)
(owner-error-ballot condition)))))
(define-condition password-error (error)
((ballot :initarg :ballot :reader password-error-ballot))
(:report (lambda (condition stream)
(format stream "Bad password for ballot ~S"
(password-error-ballot condition)))))
(define-condition ballot-state-error (error)
((ballot :initarg :ballot :reader ballot-state-error-ballot)
(state :initarg :expected-state :reader ballot-state-error-expected-state)
(operation :initarg :operation :reader ballot-state-error-operation))
(:report (lambda (condition stream)
(format stream "Ballot ~S is not in the right state ~S for the operation ~A"
(ballot-state-error-ballot condition)
(ballot-state-error-expected-state condition)
(ballot-state-error-operation condition)))))
(define-condition no-ballot-error (error)
((id :initarg :id :reader no-ballot-error-ballot-id))
(:report (lambda (condition stream)
(format stream "No ballot with ID ~S; try: list ballots"
(no-ballot-error-ballot-id condition)))))
(define-condition already-voted-error (error)
((user-id :initarg :user-id :reader already-voted-error-user-id)
(ballot-id :initarg :ballot-id :reader already-voted-error-ballot-id))
(:report (lambda (condition stream)
(format stream "User ~S has already voted to ballot ~S"
(already-voted-error-user-id condition)
(already-voted-error-ballot-id condition)))))
(define-condition syntax-error (error)
((command :initarg :command :reader syntax-error-command)
(token :initarg :token :reader syntax-error-token))
(:report (lambda (condition stream)
(format stream "Syntax error in command ~S; invalid token: ~S"
(syntax-error-command condition)
(syntax-error-token condition)))))
(define-condition double-quote-syntax-error (syntax-error)
()
(:report (lambda (condition stream)
(format stream "Syntax error in command ~S; Missing closing double-quote"
(syntax-error-command condition)))))
(define-condition no-binding-error (error) ; internal-error ?
((variable :initarg :variable :reader no-binding-error-variable)
(command :initarg :command :reader no-binding-error-command)
(call :initarg :call :reader no-binding-error-call))
(:report (lambda (condition stream)
(format stream "No binding for variable ~S used in call ~S for command ~S"
(no-binding-error-variable condition)
(no-binding-error-command condition)
(no-binding-error-call condition)))))
(define-condition bad-channel-error (error)
((channel :initarg :channel :reader bad-channel-error-channel))
(:report (lambda (condition stream)
(format stream "Bad channel: ~A"
( bad-channel-error-channel condition)))))
;;;
;;; Hash
;;;
(defun sha256-hash (text)
(ironclad:byte-array-to-hex-string
(ironclad:digest-sequence :sha256 (babel:string-to-octets text :encoding :utf-8))))
(defun sha256-hash-bytes (text)
(ironclad:digest-sequence :sha256 (babel:string-to-octets text :encoding :utf-8)))
(defun sha256-hmac (secret text)
(check-type secret (vector (unsigned-byte 8)))
(check-type text string)
(let ((hmac (ironclad:make-hmac secret :sha256)))
(ironclad:update-hmac hmac (babel:string-to-octets text :encoding :utf-8))
(ironclad:byte-array-to-hex-string (ironclad:hmac-digest hmac))))
;;;
;;; Initialization, serialization:
;;;
(defun choice (ballot-id choice-id title)
(make-instance 'choice
:ballot-id ballot-id
:choice-id choice-id
:title title))
(defmethod print-object ((choice choice) stream)
(print-unreadable-object (choice stream :identity t :type t)
(format stream "~S ~S ~S"
(ballot-id choice)
(choice-id choice)
(title choice)))
choice)
(defmethod serialize ((choice choice) stream)
(format stream "(choice ~S ~S ~S)"
(ballot-id choice)
(choice-id choice)
(title choice)))
(defun vote (ballot-id user-id-hash choice-id choice-id-hash)
(make-instance 'vote
:ballot-id ballot-id
:choice-id choice-id
:user-id-hash user-id-hash
:choice-id-hash choice-id-hash))
(defmethod print-object ((vote vote) stream)
(print-unreadable-object (vote stream :identity t :type t)
(format stream "~S ~S ~S"
(ballot-id vote)
(user-id-hash vote)
(choice-id vote)))
vote)
(defmethod initialize-instance :after ((vote vote) &key (user-id nil user-id-p) &allow-other-keys)
(if user-id-p
;; compute the new choice-id-hash:
(let* ((user-id-hash (sha256-hash user-id))
(choice-id-hash (sha256-hash (format nil "~A|~A|~A"
user-id-hash
(ballot-id vote)
(choice-id vote)))))
(setf (slot-value vote 'user-id-hash) user-id-hash
(slot-value vote 'choice-id-hash) choice-id-hash))
;; validate the choice-id-hash:
(let ((choice-id-hash (sha256-hash (format nil "~A|~A|~A"
(user-id-hash vote)
(ballot-id vote)
(choice-id vote)))))
(unless (string-equal choice-id-hash (slot-value vote 'choice-id-hash))
(error 'invalid-vote-data
:vote vote
:choice-id-hash choice-id-hash)))))
(defmethod serialize ((vote vote) stream)
(format stream "(vote ~S ~S ~S ~S)"
(ballot-id vote)
(user-id-hash vote)
(choice-id vote)
(choice-id-hash vote)))
(defun compute-new-ballot-id (title ballots)
(let ((stem (map 'string (lambda (word) (char-downcase (aref word 0)))
(split-sequence #\space title :remove-empty-subseqs t))))
(loop
:with id := stem
:for i :from 1
:while (find id ballots :key (function ballot-id) :test (function string-equal))
:do (setf id (format nil "~A~D" stem i))
:finally (return id))))
(defun compute-secret-seed (ballot-id ballot-owner)
(sha256-hash-bytes (format nil "~A|~A|~36R"
ballot-id
ballot-owner
(random #.(expt 36 8)))))
(defun compute-password-hash (secret-seed password)
(sha256-hmac secret-seed password))
(defmethod initialize-instance :after ((ballot ballot) &key (password nil passwordp) &allow-other-keys)
(let* ((ballot-id (compute-new-ballot-id (title ballot) *ballots*))
(secret-seed (when passwordp (compute-secret-seed ballot-id (ballot-owner ballot))))
(password-hash (when passwordp (compute-password-hash secret-seed password))))
(setf (slot-value ballot 'id) ballot-id)
(when passwordp
(setf (slot-value ballot 'secret-seed) secret-seed
(slot-value ballot 'password-hash) password-hash))))
(defmethod print-object ((ballot ballot) stream)
(print-unreadable-object (ballot stream :identity t :type t)
(format stream "~S ~S (~{~S~^ ~}) (~D vote~:*~P) ~{~A~^ ~}"
(ballot-id ballot)
(title ballot)
(mapcar (function choice-id) (ballot-choices ballot))
(length (ballot-votes ballot))
(ballot-channels ballot)))
ballot)
(defun ballot (ballot-id title deadline remind-period owner password-hash secret-seed state last-publication channels choices votes)
(make-instance 'ballot
'%id ballot-id
:title title
:deadline deadline
:remind-period remind-period
:owner owner
'%password-hash password-hash
'%secret-seed (coerce secret-seed '(vector octet))
'%state state
'%last-publication last-publication
'%channels channels
'%choices choices
'%votes votes))
(defmethod serialize ((ballot ballot) stream)
(format stream "(ballot ~S ~S ~S ~S ~S ~S ~S ~S ~S "
(ballot-id ballot)
(title ballot)
`(quote ,(ballot-deadline ballot))
`(quote ,(ballot-remind-period ballot))
(ballot-owner ballot)
(ballot-password-hash ballot)
(ballot-secret-seed ballot)
(ballot-state ballot)
(ballot-last-publication ballot))
(format stream "(list ~{~S~^ ~})" (ballot-channels ballot))
(terpri stream)
(format stream "(list")
(dolist (choice (ballot-choices ballot))
(terpri stream)
(serialize choice stream))
(format stream ")")
(terpri stream)
(format stream "(list")
(dolist (vote (ballot-votes ballot))
(terpri stream)
(serialize vote stream))
(format stream ")")
(format stream ")"))
;;;
;;; Commands
;;;
;; | new ballot $title $password | $ballot-id | Creates a new ballot and issues a ballot ID for reference.
(defun new-ballot (owner password title &key
(deadline '(:relative #.(days 1)))
(remind-period #.(hours 1)))
(let ((deadline
(typecase deadline
(integer
(if (< (+ (get-universal-time) +minimum-relative-deadline+)
deadline)
deadline
(error 'deadline-too-close
:specification deadline
:minimum-relative-deadline (/ +minimum-relative-deadline+ (hours 1.0)))))
(list
(ecase (first deadline)
(:relative
(if (< +minimum-relative-deadline+ (second deadline))
deadline
(error 'deadline-too-close
:specification deadline
:minimum-relative-deadline (/ +minimum-relative-deadline+ (hours 1.0))))))))))
(let ((ballot (make-instance 'ballot
:title title
:owner owner
:password password
:deadline deadline
:remind-period remind-period)))
(setf *ballots* (sort (cons ballot *ballots*)
(function string<)
:key (function ballot-id)))
(format t "New ballot ID: ~S~%" (ballot-id ballot))))
(save-ballots))
(defmethod user-is-owner ((ballot ballot) (user-id string))
(string= user-id (ballot-owner ballot)))
(defun check-channel (channel)
(unless (and (stringp channel)
(< 1 (length channel))
(char= #\# (aref channel 0))
;; find-channel finds only joined channels (channels in *connection*).
;; (if *connection*
;; (find-channel *connection* channel)
;; (char= #\# (aref channel 0)))
)
(error 'bad-channel-error :channel channel)))
(defmethod check-ballot-owner ((ballot ballot) (user-id string))
(unless (user-is-owner ballot user-id)
(error 'owner-error
:ballot ballot
:user-id user-id)))
(defmethod check-ballot-password ((ballot ballot) (password string))
(let ((password-hash (compute-password-hash (ballot-secret-seed ballot) password)))
(unless (string-equal password-hash (ballot-password-hash ballot))
(error 'password-error
:ballot ballot))))
(defmethod check-ballot-state ((ballot ballot) (state symbol) operation)
(unless (eql (ballot-state ballot) state)
(error 'ballot-state-error
:ballot ballot
:expected-state state
:operation operation)))
(defmethod check-ballot-state ((ballot ballot) (state cons) operation)
(unless (member (ballot-state ballot) state)
(error 'ballot-state-error
:ballot ballot
:expected-state state
:operation operation)))
(defun find-ballot-id (ballot-id)
(let ((ballot (find ballot-id *ballots*
:key (function ballot-id)
:test (function string-equal))))
(unless ballot
(error 'no-ballot-error :id ballot-id))
ballot))
(defmethod find-vote ((ballot ballot) (user-id string))
(let ((user-id-hash (sha256-hash user-id)))
(find user-id-hash (ballot-votes ballot)
:key (function user-id-hash)
:test (function string-equal))))
;; | set [ballot] title $ballot-id $title | | Sets the title of a ballot. Only in :editing state.
(defun set-ballot-title (user-id ballot-id title)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'set-ballot-title)
;; TODO: Add some validation of title?
(setf (slot-value ballot 'title) title))
(save-ballots))
;; | set [ballot] dead[-]line $ballot-id $dead-line | | Sets the deadline of a ballot. Only in :editing state.
(defun set-ballot-deadline (user-id ballot-id deadline)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'set-ballot-deadline)
;; TODO: Add some validation of deadline
(setf (slot-value ballot 'deadline) deadline))
(save-ballots))
;; | set [ballot] remind-period $ballot-id $period | | Sets the remind period of a ballot.
(defun set-ballot-remind-period (user-id ballot-id remind-period)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'set-ballot-remind-period)
;; TODO: Add some validation of remind-period
(setf (slot-value ballot 'remind-period) remind-period))
(save-ballots))
(defun cl-user::fmt-datetime (stream date colon at &rest parameters)
(declare (ignore colon at parameters))
(format stream "~{~5*~4,'0D-~2:*~2,'0D-~2:*~2,'0D ~2:*~2,'0D:~2:*~2,'0D:~2:*~2,'0D~8*~}"
(multiple-value-list (decode-universal-time date))))
(defmethod ballot-tally ((ballot ballot))
(let ((tally (make-hash-table :test (function equal))))
(dolist (vote (ballot-votes ballot))
(incf (gethash (choice-id vote) tally 0)))
(let ((votes '()))
(maphash (lambda (choice-id count)
(push (list choice-id count) votes))
tally)
(sort votes (function >) :key (function second)))))
(defmethod format-ballot-tally ((ballot ballot))
(let ((tally (ballot-tally ballot))
(nvotes (length (ballot-votes ballot))))
(with-output-to-string (*standard-output*)
(loop :for (choice-id count) :in tally
:for percent = (/ (* 100.0 count) nvotes)
:do (format t "~A ~A (~,1F%); " choice-id count percent)))))
(defmethod list-ballot ((ballot ballot))
(format t "~8A ~9A ~S ~:[~A after open~*~;~*at ~/fmt-datetime/~] (~8A) ~A~%"
(ballot-id ballot)
(ballot-state ballot)
(title ballot)
(typep (ballot-deadline ballot) 'universal-time)
(unless (typep (ballot-deadline ballot) 'universal-time)
(d-dms (/ (second (ballot-deadline ballot)) 3600.0d0)))
(when (typep (ballot-deadline ballot) 'universal-time)
(ballot-deadline ballot))
(ballot-owner ballot)
(case (ballot-state ballot)
(:editing "")
(:open (format nil "~D vote~:*~P in." (length (ballot-votes ballot))))
(:closed (format-ballot-tally ballot))
(:cancelled ""))))
;; | list [ballot[s]] | list of ballots | Lists all known ballots with their state and deadline or results.
(defun list-ballots ()
(if *ballots*
(dolist (ballot *ballots*)
(list-ballot ballot))
(format t "No ballots yet. Use the new ballot command.~%")))
;; | show [ballot] $ballot-id | display info of ballot | Displays all the public information about the ballot.
(defun show-ballot (ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(list-ballot ballot)))
;; | add choice $ballot-id $choice-id $choice-title | | Adds a new choice to the ballot. Only in :editing state.
(defun add-choice (user-id ballot-id choice-id choice-title)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'add-choice)
(setf (slot-value ballot 'choices)
(sort (cons (make-instance 'choice
:ballot-id (ballot-id ballot)
:choice-id choice-id
:title choice-title)
(slot-value ballot 'choices))
(function string<)
:key (function choice-id)))
(format t "There are ~D choice~:*~P in ballot ~A.~%"
(length (ballot-choices ballot))
(ballot-id ballot)))
(save-ballots))
;; | delete choice $ballot-id $choice-id | | Remove a choice from a ballot. Only in :editing state.
(defun delete-choice (user-id ballot-id choice-id)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'delete-choice)
(setf (slot-value ballot 'choices)
(delete choice-id (slot-value ballot 'choices)
:key (function choice-id)
:test (function string-equal)))
(format t "There remain ~D choice~:*~P in ballot ~A.~%"
(length (ballot-choices ballot))
(ballot-id ballot)))
(save-ballots))
;; | list choice[s] $ballot-id | list of choices | Lists all the choices of a ballot.
;; | ballot [choice[s]] $ballot-id | list of choices | Lists all the choices of a ballot. If the user has already voted, this will be indicated.
(defun list-choices (user-id ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(dolist (choice (ballot-choices ballot))
(let ((user-has-voted-for-choice
(and user-id
(let ((vote (find-vote ballot user-id)))
(when vote
(string-equal (choice-id choice)
(choice-id vote)))))))
(format t "Ballot ~A: choice ~8A ~S~:[~; *~]~%"
ballot-id (choice-id choice) (title choice)
user-has-voted-for-choice)))))
(defun open-ballots ()
(remove :open *ballots* :test-not (function eql) :key (function ballot-state)))
(defun open-channels ()
(remove-duplicates (loop
:for ballot :in (open-ballots)
:append (ballot-channels ballot))
:test (function string-equal)))
(defun update-channels ()
(when *connection*
(let* ((myself (find-user *connection* *nickname*))
(open-channels (open-channels))
(current-channels (mapcar (function name) (channels myself)))
(new-channels (set-difference current-channels open-channels
:test (function string-equal)))
(old-channels (set-difference open-channels current-channels
:test (function string-equal))))
(dolist (channel old-channels)
(part *connection* channel))
(dolist (channel new-channels)
(join *connection* channel)))))
;; | add channel[s] $ballot-id #channel… | | Add a channel to the ballot. Only in :editing state.
(defun add-channels (user-id ballot-id channels)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot '(:editing :open) 'add-channels)
(dolist (channel channels)
(check-channel channel))
(setf (slot-value ballot 'channels)
(sort (remove-duplicates
(append channels (slot-value ballot 'channels))
:test (function string=))
(function string<)))
(update-channels)
(list-ballot-channels ballot-id)
(save-ballots)))
;; | remove channel[s] $ballot-id #channel | | Remove channels from the ballot. Only in :editing state.
(defun remove-channels (user-id ballot-id channels)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot '(:editing :open) 'remove-channels)
(dolist (channel channels)
(check-channel channel))
(setf (slot-value ballot 'channels)
(set-difference (slot-value ballot 'channels)
channels
:test (function string=)))
(update-channels)
(list-ballot-channels ballot-id)
(save-ballots)))
;; | list [ballot] channel[s] $ballot-id | list of channels | List the channels of the ballot.
(defun list-ballot-channels (ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(format t "Ballot ~A ~:[will be~;has been~] published in ~D channel~:*~P: ~{~A~^ ~}.~%"
(ballot-id ballot)
(member (ballot-state ballot) '(:editing :open))
(length (ballot-channels ballot))
(ballot-channels ballot))))
(defun absolute-deadline (deadline)
(cond ((and (listp deadline) (eql ':relative (first deadline)))
(+ (get-universal-time) (second deadline)))
((typep deadline 'universal-time)
deadline)
(t
(error 'type-error
:datum deadline
:expected-type 'universal-time))))
(defmethod publish-ballot ((ballot ballot))
(let ((message (case (ballot-state ballot)
(:open (format nil "Ballot ~A ~S is open till ~/fmt-datetime/. ~
Cast your vote with: /msg ~A ballot ~A ~
and: ~2:*/msg ~A vote ~A $choice-id"
(ballot-id ballot) (title ballot)
(ballot-deadline ballot)
*nickname* (ballot-id ballot)))
(:canceled (format nil "Ballot ~A ~S is canceled."
(ballot-id ballot) (title ballot)))
(:closed (format nil "Ballot ~A ~S is closed. Results are: ~A"
(ballot-id ballot) (title ballot)
(format-ballot-tally ballot)))
(otherwise nil))))
(when message
(answer "~A" message)
(setf (slot-value ballot 'last-publication) (get-universal-time))
(when *connection*
(dolist (channel (ballot-channels ballot))
(privmsg *connection* channel message))))))
;; | open ballot $ballot-id $password | | Opens the ballot. From the :editing state.
(defun open-ballot (user-id password ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :editing 'open-ballot)
(check-ballot-password ballot password)
(setf (slot-value ballot 'state) :open
(slot-value ballot 'deadline) (absolute-deadline (ballot-deadline ballot)))
(publish-ballot ballot)
(save-ballots)))
;; | cancel ballot $ballot-id $password | | Cancel a ballot. We can cancel a ballot from the :editing or the :open state.
(defun cancel-ballot (user-id password ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot '(:editing :open) 'cancel-ballot)
(check-ballot-password ballot password)
(setf (slot-value ballot 'state) :cancelled)
(publish-ballot ballot)
(save-ballots)))
;; | close ballot $ballot-id $password | | Close the ballot before the deadline. From the :opoen state.
(defun close-ballot (user-id password ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(check-ballot-owner ballot user-id)
(check-ballot-state ballot :open 'close-ballot)
(check-ballot-password ballot password)
(setf (slot-value ballot 'state) :closed)
(publish-ballot ballot)
(save-ballots)))
;; | vote $ballot-id [choice] $choice-id | | Cast or change a vote. Only in :open state.
;; | | | If the same user votes several times, only the last vote is taken into account.
(defun vote-choice (user-id ballot-id choice-id)
(let* ((ballot (find-ballot-id ballot-id))
(vote (find-vote ballot user-id)))
(check-ballot-state ballot :open 'vote-choice)
(if vote
(error 'already-voted :user-id user-id :ballot-id ballot-id)
;; cast a new vote
(progn
(push (make-instance 'vote
:ballot-id ballot-id
:user-id user-id
:choice-id choice-id)
(slot-value ballot 'votes))
(save-ballots)))))
;; | [ballot] results [of] [ballot] $ballot-id | list of vote results | in :editing state, we only display the ballot info (same as show ballot $ballot-id);
;; | | | in :open state, we only display the number of casted votes;
;; | | | in :closed state, we display the vote results.
(defun show-ballot-results (user-id ballot-id)
(let ((ballot (find-ballot-id ballot-id)))
(ecase (ballot-state ballot)
(:editing
(list-ballot ballot))
(:open
(format t "~D vote~:*~P have been casted in ballot ~A~%"
(length (ballot-votes ballot))
(ballot-id ballot))
(when (user-is-owner ballot user-id)
(ballot-tally ballot)))
(:closed
(ballot-tally ballot))
(:cancelled
(format t "Ballot ~A has been cancelled.~%"
(ballot-id ballot))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun load-ballots ()
(setf *ballots* (eval (sexp-file-contents *ballot-file* :if-does-not-exist '())))
(update-channels)
(values))
(defun save-ballots ()
(setf (text-file-contents *ballot-file*)
(with-output-to-string (out)
(princ "(list " out)
(terpri out)
(dolist (ballot *ballots*)
(serialize ballot out)
(terpri out))
(princ ")" out)
(terpri out)))
(values))
(defun garbage-collect-ballots ()
(let ((live-ballots (remove-if (lambda (ballot)
(and (member (ballot-state ballot) '(:canceled :closed))
(< (+ (ballot-last-publication ballot)
*ballot-zombie-life*)
(get-universal-time))))
*ballots*)))
(when (/= (length live-ballots)
(length *ballots*))
(setf *ballots* live-ballots)
(save-ballots))))
(defun publish-ballots ()
;; Recently published, do nothing:
;; | deadline-(n+1)*remind | last | now | last+remind | deadline-n*remind | … | deadline-remind | deadline
;;
;; Recently published, do nothing:
;; | deadline-(n+1)*remind | last | last+remind | now | deadline-n*remind | … | deadline-remind | deadline
;;
;; Publish again:
;; | deadline-(n+1)*remind | last | last+remind | deadline-n*remind | now | … | deadline-remind | deadline
(let ((now (get-universal-time)))
(dolist (ballot (remove :open *ballots* :test-not (function eql) :key (function ballot-state)))
(when (or (zerop (ballot-last-publication ballot))
(and (< (+ (ballot-last-publication ballot) (ballot-remind-period ballot)) now)
(< (let ((n (truncate (- (ballot-deadline ballot) (ballot-last-publication ballot))
(ballot-remind-period ballot))))
(- (ballot-deadline ballot) (* n (ballot-remind-period ballot))))
now)))
(publish-ballot ballot)))))
;;;
;;; Syntax of Commands
;;;
#|
The *commands* list specifies the syntax of all botvot commands.
Each sublist in *commands* is of the form: (syntax docstring --> call)
SYNTAX is a list specifying the syntax of the command.
Each element in the list can be:
- a string specifying a terminal;
- a symbol specifying a parameter word or string; the word in the
command is then bound to that symbol, which can be refered to in the
CALL sexp.
- a list starting with the symbol OPT specifying a sequence of
optional tokens.
TODO: parsing OPT sequence is not implemented yet, only a single token is allowed in the OPT element.
- a list starting with the symbol ALT specifying alternate tokens.
- a list starting with the symbol OPT-ALT specifying optional
alternate tokens.
The list can be a dotted-list, in which case the last element must be
a symbol that will be bound to the remaining words in the command.
The DOCSTRING is displayed in the help for the command.
The symbol --> is required and ignored. It's for esthetics.
The CALL sexp is a list containing the name of a function, followed by
arguments. The arguments may be:
- the symbol USER-ID which is then substituted by the value of the
*REQUESTER-NICK*;
- the symbol NIL which is then passed to the function;
- a list which is processed recursively as the CALL sexp, the result
of the function call used as argument;
- any other symbol is substituted by the word bound to it from parsing
the command.
|#
(defparameter *commands*
'((("new" "ballot" title password)
"Creates a new ballot and issues a ballot ID for reference."
--> (new-ballot user-id password title))
(("set" (opt "ballot") "title" ballot-id title)
"Sets the title of a ballot. Only in :editing state."
--> (set-ballot-title user-id ballot-id))
(("set" (opt "ballot") (alt "dead-line" "deadline") ballot-id . deadline)
"Sets the deadline of a ballot. Only in :editing state. "
--> (set-ballot-deadline user-id ballot-id (parse-deadline deadline)))
(("set" (opt "ballot") "remind-period" ballot-id . period)
"Sets the remind period of a ballot."
--> (set-ballot-remind-period user-id ballot-id (parse-period period)))
(("list" (opt-alt "ballot" "ballots"))
"Lists all known ballots with their state and deadline or results."
--> (list-ballots))
(("show" (opt "ballot") ballot-id)
"Displays all the public information about the ballot."
--> (show-ballot ballot-id))
(("add" "choice" ballot-id choice-id choice-title)
"Adds a new choice to the ballot. Only in :editing state."
--> (add-choice user-id ballot-id choice-id choice-title))
(("delete" "choice" ballot-id choice-id)
"Remove a choice from a ballot. Only in :editing state."
--> (delete-choice user-id ballot-id choice-id))
(("list" (alt "choice" "choices") ballot-id)
"Lists all the choices of a ballot."
--> (list-choices nil ballot-id))
(("ballot" (opt-alt "choice" "choices") ballot-id)
"Lists all the choices of a ballot. If the user has already voted, this will be indicated."
--> (list-choices user-id ballot-id))
(("add" (alt "channel" "channels") ballot-id . channels)
"Add a channel to the ballot. Only in :editing state. "
--> (add-channels user-id ballot-id channels))
(("remove" (alt "channel" "channels") ballot-id . channels)
"Remove channels from the ballot. Only in :editing state."
--> (remove-channels user-id ballot-id channels))
(("list" (opt "ballot") (alt "channel" "channels") ballot-id)
"List the channels of the ballot."
--> (list-ballot-channels ballot-id))
(("open" (opt "ballot") ballot-id password)
"Opens the ballot. From the :editing state."
--> (open-ballot user-id password ballot-id))
(("cancel" (opt "ballot") ballot-id password)
"Cancel a ballot. We can cancel a ballot from the :editing or the :open state."
--> (cancel-ballot user-id password ballot-id))
(("close" (opt "ballot") ballot-id password)
"Closes the ballot before the deadline. From the :open state."
--> (close-ballot user-id password ballot-id))
(("vote" ballot-id (opt "choice") choice-id)
"Cast or change a vote. Only in :open state."
--> (vote-choice user-id ballot-id choice-id))
(((alt "results" "result") (opt "of") (opt "ballot") ballot-id)
"Display vote results (tally only in the :closed state)"
--> (show-ballot-results user-id ballot-id))
;; --------------------
(("help" . command)
"Display this help."
--> (help command))
(("version")
"Display the version of this bot."
--> (display-version))
(("uptime")
"Display the uptime of this bot."
--> (display-uptime))
(("sources")
"Display information about the sources and license of this bot."
--> (display-sources))
(("reconnect" botpass)
"Instructs the bot to close the connection to the IRC server and reconnect."
--> (reconnect-command botpass))))
;;;
;;; Parsing and processing commands:
;;;
(defun parse-hms (word)
(* 3600 (dms-d word)))
(defun parse-time (words)
;; ("HH:MM")
;; ("HH:MM:SS")
;; ("HH" "hour|hours|oclock|o'clock")
(cond
((and (= 1 (length words))
(member (count #\: (first words)) '(1 2)))
(parse-hms (first words)))
((and (= 2 (length words))
(member (second words)
'("hour" "hours" "oclock" "o'clock")
:test (function string-equal)))
(ignore-errors (hours (parse-integer (first words)))))
(t nil)))
(defun today (&optional time)
(if time
(let ((tz 0)
(time (round time)))
(multiple-value-bind (se mi ho da mo ye dow dst tz) (decode-universal-time (get-universal-time) tz)
(declare (ignore dst dow))
(declare (ignore se mi ho))
(multiple-value-bind (se2 mi2 ho2) (decode-universal-time time 0)
(encode-universal-time se2 mi2 ho2 da mo ye tz))))
(get-universal-time)))
(defun next-dow (next-dow time)
(let ((tz 0))
(multiple-value-bind (se mi ho da mo ye dow dst tz) (decode-universal-time (get-universal-time) tz)
(declare (ignore se mi ho dst))
(multiple-value-bind (se2 mi2 ho2) (decode-universal-time time 0)
(if (< dow next-dow)
(encode-universal-time se2 mi2 ho2 (+ da (- next-dow dow)) mo ye tz)
(encode-universal-time se2 mi2 ho2 (+ da 7 (- next-dow dow)) mo ye tz))))))
(defun next-monday (time) (next-dow 0 time))
(defun next-tuesday (time) (next-dow 1 time))
(defun next-wednesday (time) (next-dow 2 time))
(defun next-thirsday (time) (next-dow 3 time))
(defun next-friday (time) (next-dow 4 time))
(defun next-saturday (time) (next-dow 5 time))
(defun next-sunday (time) (next-dow 6 time))
(defun parse-deadline (words)
;; in $x days|minutes|seconds
;; on mon|tue|wed|thi|fri|sat|sun at $h [hours|o'clock]
;; on mon|tue|wed|thi|fri|sat|sun at $HH:MM
;; at $h [hours|o'clock]
;; at $HH:MM
(let ((deadline
(cond ((string= "in" (first words))
(let ((n (ignore-errors (parse-integer (second words)))))
(when n
(let ((unit (first (find (third words)
'((days "day" "days" "d")
(hours "hour" "hours" "h")
(minutes "minutes" "minute" "min" "m")
(seconds "seconds" "second" "sec" "s"))
:test (lambda (w u)
(member w u :test (function string-equal)))))))
(when unit
`(:relative ,(funcall unit n)))))))
((and (string= "on" (first words))
(string= "at" (third words)))
(let ((dow (first (find (second words)
'((next-monday "monday" "mon")
(next-tuesday "tuesday" "tue")
(next-wednesday "wednesday" "wed")
(next-thirsday "thirsday" "thi")
(next-friday "friday" "fri")
(next-saturday "saturday" "sat")
(next-sunday "sunday" "sun"))
:test (lambda (w u)
(member w u :test (function string-equal)))))))
(when dow
(let ((time (parse-time (subseq words 3))))
(when time
(funcall dow time))))))
((string= "at" (first words))
(let ((time (parse-time (subseq words 1))))
(when time
(today time)))))))
(or deadline
(error 'deadline-syntax-error :words words))))
(defun parse-period (words)
(error "Not implemented yet."))
(defun format-command-syntax (command-syntax)
(with-output-to-string (*standard-output*)
(labels ((format-word (syntax)
(cond
((null syntax)
nil)
((atom syntax)
;; dotted list
(if (symbolp syntax)
(format t "$~(~A~)…" syntax)
(format t "~(~A~)…" syntax))
nil)
((symbolp (first syntax))
(format t "$~(~A~)" (pop syntax))
syntax)
((stringp (first syntax))
(format t "~(~A~)" (pop syntax))
syntax)
((listp (first syntax))
(case (first (first syntax))
(opt
(format t "[~A]"
(format-command-syntax (rest (first syntax))))
(rest syntax))
(alt
(format t "~{~A~^|~}"
(mapcar (lambda (token)
(format-command-syntax (list token)))
(rest (first syntax))))
(rest syntax))
(opt-alt
(format t "[~{~A~^|~}]"
(mapcar (lambda (token)
(format-command-syntax (list token)))
(rest (first syntax))))
(rest syntax))
(t
(error 'syntax-error :command command-syntax :token syntax))))
(t
(error 'syntax-error :command command-syntax :token syntax)))))
(loop
:for sep := "" :then " "
:for rest-command-syntax := (progn (princ sep)
(format-word command-syntax))
:do (setf command-syntax rest-command-syntax)
:while command-syntax))))
(defun command-matches-approximatively (command-syntax words)
(let ((flat-syntax
(labels ((flatten-syntax (syntax)
(cond ((atom syntax) nil)
((stringp (first syntax))
(cons (first syntax)
(flatten-syntax (rest syntax))))
((symbolp (first syntax))
(flatten-syntax (rest syntax)))
((listp (first syntax))
(case (first (first syntax))
((opt alt opt-alt)
(nconc (flatten-syntax (rest (first syntax)))
(flatten-syntax (rest syntax))))
(otherwise
(error 'syntax-error :command command-syntax :token syntax))))
(t
(error 'syntax-error :command command-syntax :token syntax)))))
(flatten-syntax command-syntax))))
(loop :for word := (pop words)
:for m := (member word flat-syntax :test (function string-equal))
:then (member word m :test (function string-equal))
:while (and m words)
:finally (return (and m (null words))))))
(defun command-matches-exactly (command-syntax words)
(loop
:with bindings := '()
:do (cond
((null command-syntax)
(return-from command-matches-exactly
(values (null words) bindings)))
((symbolp command-syntax) ;; dotted-list
(push (cons command-syntax words) bindings)
(return-from command-matches-exactly
(values t bindings)))
((atom command-syntax)
(error 'syntax-error :command command-syntax :token command-syntax))
(t (let ((syntax-element (pop command-syntax)))
(cond ((symbolp syntax-element)
(if words
(push (cons syntax-element (pop words)) bindings)
(return-from command-matches-exactly
(values nil bindings))))
((stringp syntax-element)
(if (and words (string-equal (first words) syntax-element))
(pop words)
(return-from command-matches-exactly
(values nil bindings))))
((atom syntax-element)
(error 'syntax-error :command command-syntax :token syntax-element))
(t
(case (first syntax-element)
((opt-alt opt) ; 0 or 1
;; TODO: parse correctly (opt tok1 tok2 … tokn) vs. (opt-alt tok1 tok2 … tokn)
(if (member (first words) (rest syntax-element)
:test (function string-equal))
(pop words)))
(alt ; need 1
(if (member (first words) (rest syntax-element)
:test (function string-equal))
(pop words)
(return-from command-matches-exactly
(values nil bindings))))
(otherwise
(error 'syntax-error :command command-syntax :token syntax-element))))))))))
;; | ("set" (opt "ballot") "title" ballot-id title) | exact | ¬exact
;; |------------------------------------------------------------------+-------+--------+
;; | ("set") | nil | t
;; | ("ballot") | nil | t
;; | ("title") | nil | t
;; | ("ballot" "title") | nil | t
;; | ("set" "ballot" "title" "pg1" "Presentation Garbage Collection") | t | t
;; | ("set" "ballot" "title" "pg1") | t | t
;; | ("set" "title" "pg1" "Presentation Garbage Collection") | t | t
;; | ("set" "title" "pg1") | t | t
(defun match-command (words commands &key (exact t))
(if exact
(loop :for (command docstring nil call) :in commands
:do (multiple-value-bind (matches bindings) (command-matches-exactly command words)
(when matches
(return-from match-command (values (list command)
docstring
bindings
call)))))
(loop :for command :in commands
:when (command-matches-approximatively (first command) words)
:collect command)))
(defun print-command-help (command)
(destructuring-bind (syntax docstring --> call) command
(declare (ignore --> call))
(answer "~A -- ~A" (format-command-syntax syntax) docstring)))
(defun list-commands (commands)
(loop :for i :from 0
:for command :in commands
:initially (answer "List of commands:")
:do (answer "~A" (format-command-syntax (first command)))
(if (zerop (mod i 10))
(sleep 2)
(sleep 0.5))
:finally (answer "Done")))
(defun help (command)
(if command
(let ((matched-commands (match-command command *commands* :exact nil)))
(if (rest matched-commands)
(list-commands matched-commands)
(print-command-help (first matched-commands))))
(list-commands *commands*)))
(defun display-version ()
(answer "Version: ~A" *version*))
(defun display-uptime ()
(answer "~A" (substitute #\space #\newline
(with-output-to-string (*standard-output*)
(date) (uptime)))))
(defun display-sources ()
(answer "I'm an IRC bot helping to define ballots and cast votes on them; ~
under AGPL3 license, my sources are available at <~A>."
*sources-url*))
(defun reconnect-command (botpass)
(if (string= botpass *botpass*)
(progn (answer "Reconnecting…")
(reconnect))
(answer "I'm not in the mood.")))
(defun parse-words (command)
"We parse the irc message splitting words on spaces,
but with double-quotes escaping them."
(loop
:with words := '()
:with word := '()
:with state := :out
:for ch :across command
:do (case state
(:out (case ch
(#\"
(setf state :in
word '()))
(#\space
(when word
(push (coerce (nreverse word) 'string) words)
(setf word '())))
(otherwise
(push ch word))))
(:in (case ch
(#\"
(push (coerce (nreverse word) 'string) words)
(setf state :out
word '()))
(#\\
(setf state :escape))
(otherwise
(push ch word))))
(:escape
(push ch word)
(setf state :in)))
:finally (case state
(:out
(when word
(push (coerce (nreverse word) 'string) words)
(setf word '()))
(return (nreverse words)))
(otherwise
(error 'double-quote-syntax-error
:command command
:token (coerce (nreverse word) 'string))))))
(defun call-command (command call bindings)
(let ((fun (first call))
(args (mapcar (lambda (arg)
(cond
((stringp arg) arg)
((null arg) nil)
((eql 'user-id arg) *requester-nick*)
((consp arg)
(call-command command arg bindings))
(t
(let ((binding (assoc arg bindings)))
(if binding
(cdr binding)
(error 'no-binding-error
:variable arg
:command command
:call call))))))
(rest call))))
(apply fun args)))
(defun process-command (words)
(handler-bind ((error (lambda (err)
(print-backtrace)
(format *error-output* "~%~A~%" err)
(return-from process-command))))
(unwind-protect
(multiple-value-bind (matches docstring bindings call)
(match-command words *commands* :exact t)
(declare (ignore docstring))
(if matches
(call-command matches call bindings)
(answer "Invalid command: ~{~S~^ ~}" words)))
(garbage-collect-ballots))))
;;;
;;; A little ballot REPL to try out the command processing from the
;;; lisp REPL instead of thru a IRC connection:
;;;
(defun ballot-repl ()
(unwind-protect
(let ((*requester-nick* (first (last (pathname-directory (user-homedir-pathname))))))
(load-ballots)
(loop
:for command := (progn (format t "~&> ") (finish-output) (read-line))
:when (string-equal "quit" (string-trim #(#\space #\tab) command))
:do (loop-finish)
:do (with-simple-restart (continue "Continue REPL")
(handler-bind ((error (function invoke-debugger)))
(process-command (parse-words command))))))
(save-ballots)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The IRC agent:
;;;
(defun configure ()
(setf *server* (or (uiop:getenv "BOTVOT_SERVER") *server*)
*nickname* (or (uiop:getenv "BOTVOT_NICKNAME") *nickname*)
*botpass* (or (uiop:getenv "BOTVOT_BOTPASS") *botpass*)))
(defun say (&rest args)
(format *trace-output* "~{~A~^ ~}~%" args)
(force-output *trace-output*))
(defun answer (format-control &rest format-arguments)
(let ((text (apply (function format) nil format-control format-arguments)))
(say text)
(when (and *connection* *requester-nick*)
(privmsg *connection* *requester-nick* text))))
(defun msg-hook (message)
"Answers to PRIVMSG sent directly to this bot."
#-(and)
(with-slots (source user host command arguments connection received-time raw-message-string)
message
(format t "~20A = ~S~%" 'source source)
(format t "~20A = ~S~%" 'user user)
(format t "~20A = ~S~%" 'host host)
(format t "~20A = ~S~%" 'command command)
(format t "~20A = ~S~%" 'arguments arguments)
(format t "~20A = ~S~%" 'connection connection)
(format t "~20A = ~S~%" 'received-time received-time)
(format t "~20A = ~S~%" 'raw-message-string
(map 'string (lambda (ch)
(let ((code (char-code ch)))
(if (< code 32)
(code-char (+ code 9216))
;; (aref "␀␁␂␃␄␅␆␇␈␉␊␋␌␍␎␏␐␑␒␓␔␕␖␗␘␙␚␛␜␝␞␟␠␡" code)
ch)))
raw-message-string))
(finish-output))
(handler-bind
((error (lambda (err)
(print-backtrace)
(format *error-output* "~%~A~%" err)
(return-from msg-hook t))))
(let ((arguments (arguments message))
(*requester-nick* (source message)))
(when (string= *nickname* (first arguments))
(dolist (line (split-sequence
#\newline
(with-output-to-string (*standard-output*)
(process-command (parse-words (second arguments))))
:remove-empty-subseqs t))
(answer "~A" line)))))
t)
(defun call-with-retry (delay thunk)
"Calls THUNK repeatitively, reporting any error signaled,
and calling the DELAY-ing thunk between each."
(loop
(handler-case (funcall thunk)
(error (err) (format *error-output* "~A~%" err)))
(funcall delay)))
(defmacro with-retry (delay-expression &body body)
"Evaluates BODY repeatitively, reporting any error signaled,
and evaluating DELAY-EXPRESSIONS between each iteration."
`(call-with-retry (lambda () ,delay-expression)
(lambda () ,@body)))
(defun exit ()
"Breaks the main loop and exit."
(throw :gazongues nil))
(defun reconnect ()
"Disconnect and reconnect to the IRC server."
(throw :petites-gazongues nil))
(defparameter *allow-print-backtrace* t)
(defun print-backtrace (&optional (output *error-output*))
#+ccl (when *allow-print-backtrace*
(let ((*allow-print-backtrace* nil))
(format output "~&~80,,,'-<~>~&~{~A~%~}~80,,,'-<~>~&"
(ccl::backtrace-as-list)))))
(defun main ()
"The main program of the botvot IRC bot.
We connect and reconnect to the *SERVER* under the *NICKNAME*,
and join to the *CHANNEL* where HackerNews are published."
(let ((*package* (load-time-value (find-package "COM.INFORMATIMAGO.SMALL-CL-PGMS.BOTVOT"))))
(configure)
(load-ballots)
(catch :gazongues
(with-simple-restart (quit "Quit")
(with-retry (sleep (+ 10 (random 30)))
(catch :petites-gazongues
(with-simple-restart (reconnect "Reconnect")
(unwind-protect
(progn
(setf *connection* (connect :nickname *nickname* :server *server*))
(add-hook *connection* 'irc::irc-privmsg-message 'msg-hook)
(load-ballots)
(loop
:with next-time = (+ *period* (get-universal-time))
:for time = (get-universal-time)
:do (if (<= next-time time)
(progn
(handler-bind
((error (lambda (err)
(print-backtrace)
(format *error-output* "~%~A~%" err))))
(publish-ballots))
(incf next-time *period*))
(read-message *connection*) #|there's a 10 s timeout in here.|#)))
(save-ballots)
(when *connection*
(quit *connection*)
(setf *connection* nil))))))))))
;; (join *connection* *channel*)
;; (monitor-initialize)
;; (monitor-hacker-news (lambda (message) (privmsg *connection* *channel* message)))
#-(and) (progn
(setf *nickname* "botvot-test"
*ballot-file* #P"/tmp/ballot.sexp"
*ballot-zombie-life* (minutes 10))
(bt:make-thread (function main) :name "botvol ircbot")
(*requester-user* (format nil "~A!~A@~A"
(nickname user)
(username user)
(hostname user)))
(find-user *connection* *requester-nick*)
(channels (find-user *connection* *nickname*))
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; THE END ;;;;
| 65,996 | Common Lisp | .lisp | 1,348 | 38.321958 | 170 | 0.55936 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b96abac95dac74b2f8c51683863a9908b9ee00d8ecec5ca22b661f8b57c65df5 | 4,878 | [
-1
] |
4,879 | playtomo-stonedge.lisp | informatimago_lisp/small-cl-pgms/playtomo-stonedge/playtomo-stonedge.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: playtomo-stonedge.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements the Playtomo Stonedge Game, and its solver.
;;;; See http://www.playtomo.com/ (not much here when I went);
;;;; Download the playtomo games on BlackBerry.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2010-07-09 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2010 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(asdf-load :split-sequence)
(asdf-load :com.informatimago.common-lisp)
(use-package :com.informatimago.common-lisp.graph)
(use-package :com.informatimago.common-lisp.graph-dot)
(shadow 'copy) ; from :com.informatimago.common-lisp.graph
;;;-----------------------------------------------------------------------------
;;;
;;; STONE
;;;
(defclass stone ()
((x :initform 0
:initarg :x
:reader stone-x
:documentation "Ordinate of the first cube of the stone.")
(y :initform 0
:initarg :y
:reader stone-y
:documentation "Coordinate of the first cube of the stone.")
(direction :initform (vector 0 0 1)
:initarg :direction
:reader stone-direction
:documentation "A unit vector indicating the direction of the stone.
The coordinate of the other cube of the stone is given by adding this vector to
the coordinates of the first cube.
Note: The stone is normalized so that the vertical coordinate of the direction is either 0 or 1."))
(:documentation "A stone is made of two cubes of size equal to the cells.
To move, it rotates 1/4 turn on one of its edges that is in contact with the cells."))
(defconstant +right+ 0)
(defconstant +left+ 1)
(defconstant +front+ 2)
(defconstant +back+ 3)
;;
;; ^
;; y|front
;; |
;; |
;; left | right
;; -------------+-------------------->
;; 0| x
;; |
;; |
;; |back
;;
(defparameter *rotations*
;; x x x x
;; y y y y
;; right z left z front z back z
;; ------- --- -------- --- -------- --- ------- ---
;; 0 0 1 z 0 0 -1 -z 1 0 0 x 1 0 0 x
;; 0 1 0 y 0 1 0 y 0 0 1 z 0 0 -1 -z
;; -1 0 0 -x 1 0 0 x 0 -1 0 -y 0 1 0 y
#(
;; +right+
#2a((0 0 1)
(0 1 0)
(-1 0 0))
;; +left+
#2a((0 0 -1)
(0 1 0)
(1 0 0))
;; +front+
#2a((1 0 0)
(0 0 1)
(0 -1 0))
;; +back+
#2a((1 0 0)
(0 0 -1)
(0 1 0)))
"A vector of 3D rotation matrices for right, left, front and back rotations.")
(defun rotate (matrix vector)
"Returns matrix * vector"
(coerce
(loop
:for i :from 0 :to 2
:collect (loop
:for j :from 0 :to 2
:sum (* (aref vector j) (aref matrix i j))))
'vector))
(defun test-rotate ()
(assert
(equalp
(let ((result '()))
(dolist (direction (list #(1 0 0) #(-1 0 0) #(0 1 0) #(0 -1 0) #(0 0 1) #(0 0 -1))
result)
(dotimes (rotation 4)
(push (list direction (aref #(left--> right-> front-> back-->) rotation)
(rotate (aref *rotations* rotation) direction))
result))))
'((#(0 0 -1) back--> #(0 1 0)) (#(0 0 -1) front-> #(0 -1 0))
(#(0 0 -1) right-> #(1 0 0)) (#(0 0 -1) left--> #(-1 0 0))
(#(0 0 1) back--> #(0 -1 0)) (#(0 0 1) front-> #(0 1 0))
(#(0 0 1) right-> #(-1 0 0)) (#(0 0 1) left--> #(1 0 0))
(#(0 -1 0) back--> #(0 0 -1)) (#(0 -1 0) front-> #(0 0 1))
(#(0 -1 0) right-> #(0 -1 0)) (#(0 -1 0) left--> #(0 -1 0))
(#(0 1 0) back--> #(0 0 1)) (#(0 1 0) front-> #(0 0 -1))
(#(0 1 0) right-> #(0 1 0)) (#(0 1 0) left--> #(0 1 0))
(#(-1 0 0) back--> #(-1 0 0)) (#(-1 0 0) front-> #(-1 0 0))
(#(-1 0 0) right-> #(0 0 -1)) (#(-1 0 0) left--> #(0 0 1))
(#(1 0 0) back--> #(1 0 0)) (#(1 0 0) front-> #(1 0 0))
(#(1 0 0) right-> #(0 0 1)) (#(1 0 0) left--> #(0 0 -1)))))
:success)
(test-rotate)
(defun invert (vector)
"Returns - vector"
(map 'vector (lambda (x) (- x)) vector))
(defgeneric normalize (stone direction)
(:documentation "
Normalize the stone for a rotation in the given direction.
DIRECTION: (member :left :right :front :back)
")
(:method ((self stone) (direction (eql :right)))
(declare (ignorable direction))
(with-slots (x direction) self
(when (plusp (aref direction 0))
(progn
(incf x)
(setf direction (invert direction)))))
self)
(:method ((self stone) (direction (eql :left)))
(declare (ignorable direction))
(with-slots (x direction) self
(when (minusp (aref direction 0))
(progn
(decf x)
(setf direction (invert direction)))))
self)
(:method ((self stone) (direction (eql :front)))
(declare (ignorable direction))
(with-slots (y direction) self
(when (plusp (aref direction 1))
(progn
(incf y)
(setf direction (invert direction)))))
self)
(:method ((self stone) (direction (eql :back)))
(declare (ignorable direction))
(with-slots (y direction) self
(when (minusp (aref direction 1))
(progn
(decf y)
(setf direction (invert direction)))))
self))
(defgeneric move (stone direction)
(:documentation "Move the stone in the given direction.")
(:method ((self stone) (direction (eql :right)))
(declare (ignorable direction))
(with-slots (x direction) self
(incf x)
(setf direction (rotate (aref *rotations* +right+) direction)))
self)
(:method ((self stone) (direction (eql :left)))
(declare (ignorable direction))
(with-slots (x direction) self
(decf x)
(setf direction (rotate (aref *rotations* +left+) direction)))
self)
(:method ((self stone) (direction (eql :front)))
(declare (ignorable direction))
(with-slots (y direction) self
(incf y)
(setf direction (rotate (aref *rotations* +front+) direction)))
self)
(:method ((self stone) (direction (eql :back)))
(declare (ignorable direction))
(with-slots (y direction) self
(decf y)
(setf direction (rotate (aref *rotations* +back+) direction)))
self))
(defmethod move :before ((self stone) direction) (normalize self direction))
(defun verticalp (direction)
(not (zerop (aref direction 2))))
(defun lateralp (direction)
(not (zerop (aref direction 0))))
(defun frontp (direction)
(not (zerop (aref direction 1))))
(defmethod print-object ((self stone) stream)
(print-unreadable-object (self stream :type t)
(with-slots (x y direction) self
(format stream "~A,~A ~S~%" x y direction)
(cond
((verticalp direction)
(format stream "\"
+---+
/ /|
+---+ |
| | |
| | +
| |/
+---+ ~A,~A
\"" x y))
((lateralp direction)
(apply (function format) stream "\"
+------+
/ /|
+------+ +
| |/
+------+ ~A,~A
\""
(if (minusp (aref direction 0))
(list x y)
(list (1+ x) y))))
((frontp direction)
(apply (function format) stream "\"
+---+
/ /|
/ / +
/ / /
+---+ /
| |/
+---+ ~A,~A
\""
(if (plusp (aref direction 1))
(list x y)
(list x (1- y))))))))
self)
;;;-----------------------------------------------------------------------------
;;;
;;; CELLS
;;;
(defclass cell ()
((x :initform 0
:initarg :x
:reader cell-x
:documentation "Lateral coordinate.")
(y :initform 0
:initarg :y
:reader cell-y
:documentation "Front coordinate."))
(:documentation "This is an abstract cell. Cells are square, and all of the same size."))
(define-condition game-won () ())
(define-condition game-lost () ())
(defgeneric stone-moved-over-cell (stone cell)
(:documentation "Do cell specific behavior when the stone moves over the cell.
May signal a game-won or game-lost condition.")
(:method (stone cell)
(declare (ignorable stone cell))
(values)))
(defgeneric stone-left-cell (stone cell)
(:documentation "Do cell specific behavior when the stone moves from the cell.
May signal a game-won or game-lost condition.")
(:method (stone cell)
(declare (ignorable stone cell))
(values)))
(defgeneric game-status (stone cell)
(:documentation "Returns nil :win or :lose depending on what would happen if the stone was on the cell.")
(:method (stone cell)
(declare (ignorable stone cell))
nil))
(defclass solid-cell (cell)
()
(:documentation "The stone may remain securely on a solid cell."))
(defclass target-cell (cell)
()
(:documentation "Once the stone is in vertical position on a target cell,
the game is won."))
(defmethod stone-moved-over-cell (stone (cell target-cell))
(declare (ignorable stone cell))
(when (verticalp (stone-direction stone))
(signal 'game-won)))
(defmethod game-status (stone (cell target-cell))
(declare (ignorable cell))
(when (verticalp (stone-direction stone))
:win))
(defclass empty-cell (cell)
()
(:documentation "When the stone is over an empty cell,
the game is lost."))
(defmethod stone-moved-over-cell (stone (cell empty-cell))
(declare (ignorable stone cell))
(signal 'game-lost))
(defmethod game-status (stone (cell empty-cell))
(declare (ignorable stone cell))
:lose)
(defclass button-cell (cell)
((switches :initform '()
:initarg :switches
:accessor button-cell-switches
:documentation "A list of cells that may be switched when the stone is over the button cell."))
(:documentation "This is an abstract button cell.
Button cells may switch the state of pathway-cells."))
(defgeneric switch-pathway-cells (button-cell)
(:documentation "Switches the associated pathway-cells.")
(:method ((self button-cell))
(map nil (function switch-cell) (button-cell-switches self))
self))
(defclass red-button-cell (button-cell)
()
(:documentation "A red button cell switches its pathway cells
as soon as the stone is over it."))
(defmethod stone-moved-over-cell ((s stone) (cell red-button-cell))
(declare (ignorable s))
(switch-pathway-cells cell))
(defclass blue-button-cell (button-cell)
()
(:documentation "A blue button cell switches its pathway cells
only when the stone is over it in vertical position."))
(defmethod stone-moved-over-cell ((s stone) (cell blue-button-cell))
(when (verticalp (stone-direction s))
(switch-pathway-cells cell)))
(defclass pathway-cell (cell)
((state :initform :closed
:initarg :state
:reader pathway-cell-state
:type (member :closed :open)
:documentation "A pathway cell may be :open or :closed."))
(:documentation "When a pathway cell is :open, it supports a stone;
when it's :closed the stone falls down and
the game is lost."))
(defmethod stone-moved-over-cell ((s stone) (cell pathway-cell))
(declare (ignorable s))
(when (eql :closed (pathway-cell-state cell))
(signal 'game-lost)))
(defmethod game-status (stone (cell pathway-cell))
(declare (ignorable stone))
(when (eql :closed (pathway-cell-state cell))
:lose))
(defmethod switch-cell ((self pathway-cell))
(setf (slot-value self 'state) (ecase (pathway-cell-state self)
((:open) :closed)
((:closed) :open)))
self)
(defclass crumble-cell (cell)
((state :initform :open
:initarg :state
:reader crumble-cell-state
:type (member :closed :open)
:documentation "A crumble cell goes from :open to :closed the first time
it's walked over, and stays :closed thereafter."))
(:documentation "When a crumble cell is :open, it supports a stone;
when it's :closed the stone falls down and
the game is lost."))
(defmethod stone-moved-over-cell ((s stone) (cell crumble-cell))
(declare (ignorable s))
(when (eql :closed (crumble-cell-state cell))
(signal 'game-lost)))
(defmethod stone-left-cell (stone (cell crumble-cell))
(declare (ignorable stone))
(setf (slot-value cell 'state) :closed))
(defmethod game-status (stone (cell crumble-cell))
(declare (ignorable stone))
(when (eql :closed (crumble-cell-state cell))
:lose))
(defclass ice-cell (cell)
()
(:documentation "An ice cell supports an horizontal stone, but
when the stone is over it in vertical position, it breaks, the stone falls down, and
the game is lost."))
(defmethod stone-moved-over-cell ((s stone) (cell ice-cell))
(declare (ignorable cell))
(when (verticalp (stone-direction s))
(signal 'game-lost)))
(defmethod game-status (stone (cell ice-cell))
(declare (ignorable cell))
(when (verticalp (stone-direction stone))
:lose))
;;;-----------------------------------------------------------------------------
;;;
;;; GAME
;;;
(defclass game ()
((stone :initform (make-instance 'stone)
:initarg :stone
:reader game-stone
:documentation "The stone.")
(cells :initform #2a()
:initarg :cells
:reader game-cells
:documentation "The cells.")))
(defgeneric text-icon (cell)
(:documentation "Returns a three-character strings denoting graphically the cell.")
(:method ((cell empty-cell)) (declare (ignorable cell)) " ")
(:method ((cell solid-cell)) (declare (ignorable cell)) "SSS")
(:method ((cell red-button-cell)) (declare (ignorable cell)) "[R]")
(:method ((cell blue-button-cell)) (declare (ignorable cell)) "[B]")
(:method ((cell ice-cell)) (declare (ignorable cell)) ",,,")
(:method ((cell target-cell)) (declare (ignorable cell)) "TTT")
(:method ((cell crumble-cell))
(declare (ignorable cell))
(if (eql :open (crumble-cell-state cell))
"CCC"
" "))
(:method ((cell pathway-cell))
(declare (ignorable cell))
(if (eql :open (pathway-cell-state cell))
"---"
" / ")))
(defun stone-coverage (stone)
"
Returns: direction; left; back; right; front
DIRECTION: (member :vertical :lateral :front)
"
(let ((direction (cond
((verticalp (stone-direction stone)) :vertical)
((lateralp (stone-direction stone)) :lateral)
(t :front))))
(if (eql direction :vertical)
(values direction (stone-x stone) (stone-y stone) (stone-x stone) (stone-y stone))
(let* ((x0 (stone-x stone))
(x1 (+ x0 (aref (stone-direction stone) 0)))
(y0 (stone-y stone))
(y1 (+ y0 (aref (stone-direction stone) 1))))
(values direction (min x0 x1) (min y0 y1) (max x0 x1) (max y0 y1))))))
(defun print-game (game stream)
"
Prints an ASCII-art representation of the GAME onto the STREAM.
"
(let* ((cells (game-cells game))
(line (with-output-to-string (out)
(loop
:initially (princ "+" out)
:repeat (array-dimension cells 0)
:do (princ "---+" out)))))
(multiple-value-bind (direction stone-left stone-back stone-right stone-front)
(stone-coverage (game-stone game))
(loop
:for j :from (1- (array-dimension cells 1)) :downto 0
:initially (princ line stream) (terpri stream)
:do (loop
:for i :from 0 :below (array-dimension cells 0)
:initially (princ "|" stream)
:do (unless (ecase direction
((:vertical)
(when (and (= stone-left i) (= stone-back j))
(princ "BBB" stream) (princ "|" stream) t))
((:lateral)
(cond
((and (= stone-left i) (= stone-back j))
(princ "BBBB" stream) t)
((and (= stone-right i) (= stone-back j))
(princ "BBB" stream) (princ "|" stream) t)))
((:front)
(when (and (= stone-left i) (or (= stone-back j)
(= stone-front j)))
(princ "BBB" stream) (princ "|" stream) t)))
(princ (text-icon (aref cells i j)) stream) (princ "|" stream))
:finally (progn
(terpri stream)
(if (and (eql direction :front) (= stone-front j))
(let ((line (copy-seq line)))
(replace line "BBB" :start1 (+ 1 (* 4 stone-left)))
(princ line stream))
(princ line stream))
(terpri stream)))))))
(defmethod print-object ((self game) stream)
(print-unreadable-object (self stream :type t :identity t)
(format stream "\"~%")
(print-game self stream)
(format stream "~%\""))
self)
(defun parse-game (level)
"
LEVEL: A CONS whose car is a string drawing the cells, and whose cdr
is a list of cell definitions. The string is a multiline
string, each line containing one character per cell. The
character encodes the class of cell (case insensitively):
. or space: empty-cell
S solid-cell starting position
O solid-cell
T target-cell
I ice-cell
C crumble-cell
other: the character is searched in the list of cell definitions.
The list of cell definitions contains sublists of these forms:
(cell-name :pathway :open|:closed)
(cell-name :red . list-of-cell-names)
(cell-name :blue . list-of-cell-names)
Cell-name is either a character, a single-character string or
symbol, or a digit (0 from 9).
:pathway indicates the class of the cell is pathway-cell, and
the following keyword indicates its initial state.
:red indicates the class of the cell is red-button-cell;
:blue indicates the class of the cell is blue-button-cell; in
both cases, the rest is the list of pathway cell-names
connected to the button.
There must be a start position, and all the non empty cells
must be at least two steps from the borders.
"
(let* ((lines (split-sequence:split-sequence #\newline (first level)))
(depth (length lines))
(width (reduce (function max) lines :key (function length)))
(cells (make-array (list width depth)))
(links (rest level))
(linked-cells '())
(stone))
(flet ((cell-key (designator)
(typecase designator
((or symbol string character) (char (string-upcase designator) 0))
((integer 0 9) (char (princ-to-string designator) 0))
(t (error "Invalid reference in level links: ~S" designator)))))
(loop
:with start-x :with start-y
:for line :in lines
:for j :from (1- depth) :downto 0
:do (loop
:for i :from 0 :below width
:for ch = (if (< i (length line))
(aref line i)
#\.)
:do (setf (aref cells i j)
(flet ((make-cell (class &rest args)
(unless (eql class 'empty-cell)
(assert (and (< 1 i (- width 2))
(< 1 j (- depth 2)))
(i j)
"Non empty cells must be at more than two steps from the border."))
(apply (function make-instance) class :x i :y j args)))
(case (char-upcase ch)
((#\. #\space) (make-cell 'empty-cell))
((#\S) (progn
(setf start-x i
start-y j)
(make-cell 'solid-cell)))
((#\O) (make-cell 'solid-cell))
((#\I) (make-cell 'ice-cell))
((#\C) (make-cell 'crumble-cell))
((#\T) (make-cell 'target-cell))
(otherwise
(let ((link (assoc (char-upcase ch) links :key (function cell-key))))
(if link
(let ((cell
(ecase (second link)
((:red) (make-cell 'red-button-cell))
((:blue) (make-cell 'blue-button-cell))
((:pathway) (make-cell 'pathway-cell :state (third link))))))
(push (cons (cell-key ch) cell) linked-cells)
cell)
(error "Invalid character in level map: ~S" ch))))))))
:finally (progn
(unless start-x
(error "The level is missing a start position. ~%~S" level))
(setf stone (make-instance 'stone :x start-x :y start-y))
(loop
;; Put the pathways in the switches list of the buttons.
:for (key . cell) :in linked-cells
:for link = (assoc key links :key (function cell-key))
:do (ecase (second link)
((:red :blue) (dolist (pathway (cddr link))
(pushnew (cdr (assoc (cell-key pathway) linked-cells))
(button-cell-switches cell))))
((:pathway))))
(return (make-instance 'game :stone stone :cells cells)))))))
(defmethod move ((game game) direction)
"
Moves the stone of the game in the given direction.
"
(let ((stone (game-stone game))
(cells (game-cells game)))
(multiple-value-bind (direction stone-left stone-back stone-right stone-front) (stone-coverage stone)
(if (eql direction :vertical)
(stone-left-cell stone (aref cells stone-left stone-back))
(progn
(stone-left-cell stone (aref cells stone-left stone-back))
(stone-left-cell stone (aref cells stone-right stone-front)))))
(move (game-stone game) direction)
(multiple-value-bind (direction stone-left stone-back stone-right stone-front) (stone-coverage stone)
(if (eql direction :vertical)
(stone-moved-over-cell stone (aref cells stone-left stone-back))
(progn
(stone-moved-over-cell stone (aref cells stone-left stone-back))
(stone-moved-over-cell stone (aref cells stone-right stone-front))))))
game)
(defun stonedge (level)
"
Play the playtomo stonedge game for the given LEVEL.
See PARSE-GAME for the description of LEVEL.
"
(let ((game (parse-game level)))
(handler-case
(loop
(print-game game *query-io*)
(format *query-io* "Your move: ")
(block :abort
(move game
(case (char (string-trim #(#\space #\tab) (read-line *query-io*)) 0)
((#\j #\4) :left)
((#\l #\6) :right)
((#\i #\8) :front)
((#\k #\2) :back)
(otherwise (return-from :abort))))))
(game-won () (format t "~%You win!~2%"))
(game-lost () (format t "~%You lose!~2%")))
(values)))
;;;-----------------------------------------------------------------------------
;;;
;;; Solver
;;;
(defgeneric cell-state (cell)
(:documentation "Return NIL or the state of the cell.")
(:method (cell) (declare (ignorable cell)) nil)
(:method ((cell crumble-cell)) (declare (ignorable cell)) (crumble-cell-state cell))
(:method ((cell pathway-cell)) (declare (ignorable cell)) (pathway-cell-state cell)))
(defgeneric game-state (game)
(:documentation "Return a list containing in a concise form the full state of the game.")
(:method ((game game))
(let ((cells (game-cells game))
(stone (game-stone game)))
(multiple-value-bind (direction stone-left stone-back stone-right stone-front)
(stone-coverage stone)
(declare (ignore direction))
(list* (or (game-status stone (aref cells stone-left stone-back))
(game-status stone (aref cells stone-right stone-front)))
stone-left stone-back stone-right stone-front
(loop
:for i :from 0 :below (array-total-size cells)
:for state = (cell-state (row-major-aref cells i))
:when state :collect state))))))
(defgeneric copy (object &key &allow-other-keys)
(:documentation "Copy the game objects. Stateless cells are returned uncopied.")
(:method ((stone stone) &key &allow-other-keys)
(make-instance 'stone
:x (stone-x stone)
:y (stone-y stone)
:direction (stone-direction stone)))
(:method ((cell cell) &key &allow-other-keys)
cell)
(:method ((cell button-cell) &key &allow-other-keys)
(make-instance (class-of cell)
:x (cell-x cell)
:y (cell-y cell)
:switches (button-cell-switches cell)))
(:method ((cell pathway-cell) &key &allow-other-keys)
(make-instance (class-of cell)
:x (cell-x cell)
:y (cell-y cell)
:state (pathway-cell-state cell)))
(:method ((cell crumble-cell) &key &allow-other-keys)
(make-instance (class-of cell)
:x (cell-x cell)
:y (cell-y cell)
:state (crumble-cell-state cell)))
(:method ((game game) &key &allow-other-keys)
(make-instance 'game
:stone (copy (game-stone game))
:cells (loop
:with cells = (com.informatimago.common-lisp.array:copy-array (game-cells game))
:with pathways = '()
:with buttons = '()
:for i :from 0 :below (array-total-size cells)
:for original = (row-major-aref cells i)
:for copy = (copy original)
:do (setf (row-major-aref cells i) copy)
:do (typecase original
(pathway-cell (push (cons original copy) pathways))
(button-cell (push copy buttons)))
:finally (progn
(dolist (button buttons)
(setf (button-cell-switches button)
(mapcar (lambda (old) (cdr (assoc old pathways)))
(button-cell-switches button))))
(return cells))))))
(defstruct node
"A node of the graph of the stonedge game."
state
game
path
visitedp
startp
;; neighbors is nil or a vector of neighbor nodes in (:right :left :front :back) order.
neighbors)
(defvar *states* (make-hash-table :test (function equal))
"A hash-table mapping game states to nodes.")
(defun make-graph-from-states (states)
(let* ((ne (make-hash-table))
(en (make-hash-table))
(elements
(let ((elements '()))
(maphash
(lambda (state node)
(let ((element (make-instance 'element-class :ident state)))
(set-property element :path (reverse (node-path node)))
(set-property element :dot-label
#- (and) (with-output-to-string (out)
(dolist (line (split-sequence:split-sequence
#\newline
(with-output-to-string (out)
(print-game (node-game node) out))))
(princ line out)
(princ "\\n" out)))
#+ (and) "x")
(set-property element :dot-fill-color (if (node-startp node)
"Yellow"
(ecase (first state)
((:win) "Green")
((:lose) "Red")
((nil) "White"))))
(setf (gethash element en) node)
(setf (gethash node ne) element)
(push element elements)))
states)
elements))
(graph (make-instance 'graph-class
:nodes (make-instance 'set-class :elements elements)
:edge-class 'directed-edge)))
(print (list (length elements) 'elements))
(dolist (element elements)
(let ((node (gethash element en)))
(when (node-neighbors node)
(loop
:for successor :across (node-neighbors node)
:for direction :in '(:right :left :front :back)
:do (when successor
(let ((edge (make-instance 'directed-edge-class
:from element
:to (gethash successor ne))))
(set-property edge :dot-label direction)
(add-edge graph edge)))))))
graph))
(defun reset ()
"Cleans up the *STATES* hash-table."
(setf *states* (make-hash-table :test (function equal))))
(defun explore (game path)
"Walks the game graph, recoding each node in the *STATES* hash-table."
(let* ((state (game-state game))
(node (gethash state *states*)))
(unless node
(setf node (setf (gethash state *states*)
(make-node :state state
:game game
:path path
:visitedp nil))))
(unless (node-visitedp node)
(setf (node-visitedp node) t)
(unless (first state)
(setf (node-neighbors node)
(coerce
(loop
:for move :in '(:right :left :front :back)
:for reverse :in '(:left :right :back :front)
:collect (let ((child (copy game)))
(move child move)
(explore child (cons move path))))
'vector))))
node))
(defun print-wins ()
"Find all the WIN nodes from the *STATES* hash-table, and print thei state and path."
(maphash (lambda (state node)
(when (eq :win (first state))
(print (list state (reverse (node-path node))))))
*states*))
(defun solve-problem (problem)
"Solves the playtomo-stonedge game level PROBLEM,
printing the number of states and the win states."
(time (progn
(reset)
(setf (node-startp (explore (parse-game problem) '())) t)
(print `(number of states = ,(hash-table-count *states*)))
(print-wins))))
;;;-----------------------------------------------------------------------------
(defparameter *simple*
'("
...............
...............
......AO.......
....OOOOOO.....
..SOOOOOOO1OT..
...IIOOOOO.....
......IO.......
...............
...............
"
(a :red 1)
(1 :pathway :closed)))
(defparameter *level-36*
'("
...............
...............
......AO.......
....OOOIIO.....
..SOOOICOO1OT..
...IIOIOOO.....
......IO.......
...............
...............
"
(a :red 1)
(1 :pathway :closed)))
(defparameter *level-37*
'("
...........
...........
.....OC....
....CII....
..OO1BS23..
..OR4TCOO..
....COL....
.....O5....
...........
...........
"
(b :blue 1)
(r :red 4)
(l :red 2 3 5)
(1 :pathway :closed)
(2 :pathway :closed)
(3 :pathway :closed)
(4 :pathway :open)
(5 :pathway :open)))
(defparameter *level-38*
'("
.................
.................
..II.IIIICIIOIT..
..II..III.IIIII..
..SOII.II.IIIII..
..IIICOOC........
.................
.................
"))
(defparameter *level-39*
'("
..............
..............
..IIB1R2CLO...
..IIO.....O...
....O.....O...
....O.....3O..
....O.....OO..
....IO...OTO..
....SO...CO...
.....OCOCOO...
..............
..............
"
(b :blue 1)
(r :red 2)
(l :red 3)
(1 :pathway :closed)
(2 :pathway :closed)
(3 :pathway :closed)))
(defparameter *level-52*
'("
.........
...RO
...OC
..SBOC1
..OTIO2
..3OCO
..OC
"
(r :red 3)
(b :blue 1 2)
(1 :pathway :closed)
(2 :pathway :closed)
(3 :pathway :closed)))
;; (defparameter *game* (parse-game *problem*))
;; (stonedge *level-39*)
;; (solve-problem *problem*) (solve-problem *simple*)
;; (time (progn (reset) (explore (parse-game ) '()) (find-win)))
;;
;; (solve-problem *level-37*)
;; (solve-problem *level-38*)
;; (solve-problem *level-39*)
;; (solve-problem *level-52*)
;;
;; (let ((name "g"))
;; (with-open-file (dot (format nil "~A.dot" name)
;; :direction :output
;; :if-does-not-exist :create
;; :if-exists :supersede)
;; (princ (generate-dot (setf *g* (make-graph-from-states *states*))) dot))
;; (ext:shell (format nil "dot -Tpng -o ~A.png ~:*~A.dot" name)))
;;;; THE END ;;;;
| 35,808 | Common Lisp | .lisp | 899 | 30.609566 | 112 | 0.517204 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a38e654e5a9cc9c08bfec29cc1e497259275b982cbb7d1cdc46c5c0c77349d2d | 4,879 | [
-1
] |
4,880 | count-fork.lisp | informatimago_lisp/small-cl-pgms/clisp-fork/count-fork.lisp | ;;;;**************************************************************************
;;;;FILE: count-fork.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Testing fork and signals in clisp.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-05-02 <PJB> Added this header.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defparameter *run* t)
(defun install-signal-handler (signum handler)
(let ((oldhan (linux:|set-signal-handler| signum handler))
(sigset (second (multiple-value-list
(linux:|sigaddset| (second (multiple-value-list
(linux:|sigemptyset|)))
signum)))))
(linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| sigset)
(values signum oldhan sigset)))
(defun restore-signal-handler (signum oldhan sigset)
(linux:|set-signal-handler| signum oldhan)
(linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| sigset))
(defmacro with-signal-handler (signum handler &body body)
(let ((voldhan (gensym))
(vsignum (gensym))
(vsigset (gensym)))
`(let* ((,vsignum ,signum)
(,voldhan (linux:|set-signal-handler| ,vsignum ,handler))
(,vsigset (second (multiple-value-list
(linux:|sigaddset|
(second (multiple-value-list
(linux:|sigemptyset|)))
,vsignum)))))
(linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| ,vsigset)
(unwind-protect (progn ,@body)
(linux:|set-signal-handler| ,vsignum ,voldhan)
(linux:|sigprocmask-set-n-save| linux:|SIG_UNBLOCK| ,vsigset)))))
(ffi:def-c-struct itimerval
(interval-sec ffi:long)
(interval-mic ffi:long)
(value-sec ffi:long)
(value-mic ffi:long))
(defconstant +itimer-real+ 0)
(defconstant +itimer-virtual+ 1)
(defconstant +itimer-prof+ 2)
(ffi:def-call-out
setitimer
(:name "setitimer")
(:arguments (which ffi:int :in) (value (ffi:c-ptr itimerval) :in)
(ovalue (ffi:c-ptr-null itimerval) :in))
(:return-type ffi:int)
(:language :stdc)
(:library "/lib/libc.so.6"))
(defun main ()
(setf *run* t)
(sleep 1.0)
(with-signal-handler linux:|SIGVTALRM|
(lambda (signum) (declare (ignore signum)) (setf *run* nil))
(ffi:with-c-var (i 'itimerval (make-itimerval :interval-sec 0
:interval-mic 0
:value-sec 0
:value-mic 10000))
(setitimer +itimer-virtual+ i nil))
(loop
:with counter = 0
:with failed = 0
:while *run*
:do (let ((res (linux:fork)))
(cond ((null res) (incf failed))
((= 0 res) (linux:exit 0))
(t (incf counter))))
:finally (format t "forked ~D times (failed ~D times)~%"
counter failed)
(finish-output))))
| 4,143 | Common Lisp | .lisp | 98 | 34.193878 | 83 | 0.558422 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c432460917b930adc1fa805b0ad62529658b249334a25b5417d4e97c9fa6b688 | 4,880 | [
-1
] |
4,881 | character-sets.lisp | informatimago_lisp/clext/character-sets.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: character-sets.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Portability layer over character sets and external-formats.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-15 <PJB> Corrected character-set-to-emacs-encoding.
;;;; Added examples to package docstring.
;;;; 2012-04-06 <PJB> Extracted from
;;;; com.informatimago.common-lisp.cesarum.character-sets.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS")
(:export
"MAKE-EXTERNAL-FORMAT"
"EXTERNAL-FORMAT-CHARACTER-ENCODING"
"EXTERNAL-FORMAT-LINE-TERMINATION"
"CHARACTER-SET-TO-LISP-ENCODING"
"CHARACTER-SET-FOR-LISP-ENCODING"
"CHARACTER-SET-TO-EMACS-ENCODING"
"CHARACTER-SET-FROM-EMACS-ENCODING"
"EMACS-ENCODING-TO-LISP-EXTERNAL-FORMAT")
(:documentation "
This package exports functions to manage character-sets,
character encodings, coding systems and external format.
It's all the same, but everyone likes to have his own terms...
CHARACTER-SET are structures containing all the information about the
character set, (name, characters), the encodings, the lisp
external-format values, the emacs coding-system strings.
CHARACTER-SET can be designated by string-designators containing their
name or aliases.
LISP-ENCODING are CL implementation specific objects usable as
external-format arguments. They wrap a character-set, and a
line-termination mode, and possibly other parameters
(encoding/decoding error handling, etc).
EMACS-ENCODING are emacs coding systems (structured strings).
EXTERNAL-FORMATS are usually a combination of character set and
line-termination (and possibly additionnal information, such as
encoding/decoding error handling). Often, keywords naming the
character set can be used as designators for external formats.
(open file :external-format (make-external-format
(character-set-to-lisp-encoding \"utf-8\")
:dos))
(let ((cs (com.informatimago.common-lisp.cesarum.character-sets:find-character-set \"utf-8\")))
(when cs
(format t \";; -*- mode:lisp;coding:~A -*- ~%\" (character-set-to-emacs-encoding cs))))
(cs-name (character-set-from-emacs-encoding \"mule-utf-8-unix\"))
--> \"UTF-8\"
(character-set-to-emacs-encoding :utf-8)
--> \"mule-utf-8-unix\"
(character-set-to-lisp-encoding \"utf-8\")
--> #<external-format :utf-8/:unix #x3020003B7F5D>
(character-set-for-lisp-encoding
(make-external-format \"utf-8\" :dos))
--> :utf-8
:dos
(make-external-format
(character-set-for-lisp-encoding
(character-set-to-lisp-encoding \"utf-8\"))
:dos)
--> #<external-format :utf-8/:dos #x30200AF3E17D>
Copyright Pascal J. Bourguignon 2005 - 2021
This package is provided under the GNU General Public Licence.
See the source file for details.
"))
(in-package "COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS")
(defparameter *aliases*
'(
;; clisp, emacs:
("UNICODE-32-LITTLE-ENDIAN" "UTF-32-LE" "UTF-32LE")
("UNICODE-32-BIG-ENDIAN" "UTF-32-BE" "UTF-32BE")
("UNICODE-16-LITTLE-ENDIAN" "UTF-16-LE" "UTF-16LE")
("UNICODE-16-BIG-ENDIAN" "UTF-16-BE" "UTF-16BE")
;; clisp
("CP437-IBM" "CP437")
("CP852-IBM" "CP852")
("CP860-IBM" "CP860")
("CP861-IBM" "CP861")
("CP862-IBM" "CP862")
("CP863-IBM" "CP863")
("CP864-IBM" "CP864")
("CP865-IBM" "CP865")
("CP869-IBM" "CP869")
("CP874-IBM" "CP874")
;; emacs:
("VSCII" "VISCII")
;; Aliases for other implementations:
("LATIN1" "ISO-8859-1")
("LATIN2" "ISO-8859-2")
("LATIN3" "ISO-8859-3")
("LATIN4" "ISO-8859-4")
("LATIN5" "ISO-8859-9")
("LATIN6" "ISO-8859-10")
("LATIN8" "ISO-8859-14")
("LATIN9" "ISO-8859-15")
("LATIN-1" "ISO-8859-1")
("LATIN-2" "ISO-8859-2")
("LATIN-3" "ISO-8859-3")
("LATIN-4" "ISO-8859-4")
("LATIN-5" "ISO-8859-9")
("LATIN-6" "ISO-8859-10")
("LATIN-8" "ISO-8859-14")
("LATIN-9" "ISO-8859-15")
)
"A list of lists of aliases for character-set.")
(defun add-aliases-to-group (encoding-name-and-aliases aliases)
"
ENCODING-NAME-AND-ALIASES:
A list of name and aliases of character-sets.
ALIASES: A list of lists of aliases, each sublist naming the same character-set.
RETURN: A new list of name and aliases, with the ALIASES added, if
they name the same character-set as ENCODING-NAME-AND-ALIASES.
"
(let ((alias (find-if
(lambda (alias)
(intersection encoding-name-and-aliases alias :test (function string-equal)))
aliases)))
(if alias
(remove-duplicates (cons (car encoding-name-and-aliases)
(union (cdr encoding-name-and-aliases) alias
:test (function string-equal)))
:test (function string-equal))
encoding-name-and-aliases)))
(defparameter *lisp-encodings*
;; #+ccl-1.9
;; ccl:list-character-encodings. Use it
;; in ccl:describe-character-encodings
#+(and ccl (not ccl-1.6))
(mapcar (lambda (x) (mapcar (function string-upcase) x))
'((:iso-8859-1 :iso_8859-1 :latin1 :l1 :ibm819 :cp819 :csisolatin1)
(:iso-8859-2 :iso_8859-2 :latin-2 :l2 :csisolatin2)
(:iso-8859-3 :iso_8859-3 :latin3 :l3 :csisolatin3)
(:iso-8859-4 :iso_8859-4 :latin4 :l4 :csisolatin4)
(:iso-8859-5 :iso_8859-5 :cyrillic :csisolatincyrillic :iso-ir-144)
(:iso-8859-6 :iso_8859-6 :arabic :csisolatinarabic :iso-ir-127)
(:iso-8859-7 :iso_8859-7 :greek :greek8 :csisolatingreek :iso-ir-126 :elot_928 :ecma-118)
(:iso-8859-8 :iso_8859-8 :hebrew :csisolatinhebrew :iso-ir-138)
(:iso-8859-9 :iso_8859-9 :latin5 :csisolatin5 :iso-ir-148)
(:iso-8859-10 :iso_8859-10 :latin6 :csisolatin6 :iso-ir-157)
(:iso-8859-11)
(:iso-8859-13)
(:iso-8859-14 :iso_8859-14 :iso-ir-199 :latin8 :l8 :iso-celtic)
(:iso-8859-15 :iso_8859-15 :latin9)
(:iso-8859-16 :iso_8859-16 :iso-ir-199 :latin8 :l8 :iso-celtic)
(:macintosh :macos-roman :macosroman :mac-roman :macroman)
(:ucs-2)
(:ucs-2be)
(:ucs-2le)
(:us-ascii :csascii :cp637 :ibm637 :us :iso646-us :ascii :iso-ir-6)
(:utf-16)
(:utf-16be)
(:utf-16le)
(:utf-32 :utf-4)
(:utf-32be :ucs-4be)
(:utf-8)
(:utf-32le :ucs-4le)
(:windows-31j :cp932 :cswindows31j)
(:euc-jp :eucjp)))
#+lispworks '((:latin-1
:iso-8859-1 :iso_8859-1 :latin1 :l1 :ibm819 :cp819 :csisolatin1)
(:latin-1-terminal)
(:latin-1-safe)
(:macos-roman
:macintosh :macosroman :mac-roman :macroman)
(:ascii
:us-ascii :csascii :cp637 :ibm637 :us :iso646-us :iso-ir-6)
(:unicode)
(:utf-16 :utf-16be)
(:utf-8)
(:utf-32 :utf-32-be :ucs-4be)
(:bmp)
(:jis)
(:euc-jp
:eucjp)
(:sjis)
(:windows-cp936 :gbk)
(:koi8-r
:koi8 :cp878))
#+(and ccl ccl-1.6)
(mapcar (lambda (x) (mapcar (function string-upcase) x))
'((:iso-8859-1 :iso_8859-1 :latin1 :l1 :ibm819 :cp819 :csisolatin1)
(:iso-8859-2 :iso_8859-2 :latin-2 :l2 :csisolatin2)
(:iso-8859-3 :iso_8859-3 :latin3 :l3 :csisolatin3)
(:iso-8859-4 :iso_8859-4 :latin4 :l4 :csisolatin4)
(:iso-8859-5 :iso_8859-5 :cyrillic :csisolatincyrillic :iso-ir-144)
(:iso-8859-6 :iso_8859-6 :arabic :csisolatinarabic :iso-ir-127)
(:iso-8859-7 :iso_8859-7 :greek :greek8 :csisolatingreek :iso-ir-126 :elot_928 :ecma-118)
(:iso-8859-8 :iso_8859-8 :hebrew :csisolatinhebrew :iso-ir-138)
(:iso-8859-9 :iso_8859-9 :latin5 :csisolatin5 :iso-ir-148)
(:iso-8859-10 :iso_8859-10 :latin6 :csisolatin6 :iso-ir-157)
(:iso-8859-11)
(:iso-8859-13)
(:iso-8859-14 :iso_8859-14 :iso-ir-199 :latin8 :l8 :iso-celtic)
(:iso-8859-15 :iso_8859-15 :latin9)
(:iso-8859-16 :iso_8859-16 :iso-ir-199 :latin8 :l8 :iso-celtic)
(:macintosh :macos-roman :macosroman :mac-roman :macroman)
(:ucs-2)
(:ucs-2be)
(:ucs-2le)
(:us-ascii :csascii :cp637 :ibm637 :us :iso646-us :ascii :iso-ir-6)
(:utf-16)
(:utf-16be)
(:utf-16le)
(:utf-32 :utf-4)
(:utf-32be :ucs-4be)
(:utf-8)
(:utf-32le :ucs-4le)
(:windows-31j :cp932 :cswindows31j)
(:euc-jp :eucjp)
(:gb2312 :gb2312-80 :gb2312-1980 :euc-cn :euccn)
(:cp936 :gbk :ms936 :windows-936)))
#+clisp
(let ((h (make-hash-table)))
(do-external-symbols (s "CHARSET")
(push (string-upcase s) (gethash (ext:encoding-charset s) h)))
(let ((r '()))
(maphash (lambda (k v) (declare (ignore k)) (push v r)) h)
r))
#+cmu '(("ISO-8859-1")) ; :iso-latin-1-unix ; what else?
#+ecl '(("ISO-8859-1")
#+unicode ("UTF-8"))
#+sbcl
(mapcar (lambda (x)
(mapcar (function string-upcase)
(sb-impl::ef-names x)))
(etypecase sb-impl::*external-formats*
(hash-table (let ((result '()))
(maphash (lambda (name encoding)
(declare (ignore name))
(pushnew encoding result))
sb-impl::*external-formats*)
result))
(vector (remove 'SB-IMPL::EXTERNAL-FORMAT
(flatten (coerce sb-impl::*external-formats* 'list))
:key (function type-of)
:test-not (function eql)))
(list (remove 'SB-IMPL::EXTERNAL-FORMAT
(flatten sb-impl::*external-formats*)
:key (function type-of)
:test-not (function eql)))))
;; From Java7:
;; Every implementation of the Java platform is required to support
;; the following standard charsets. Consult the release
;; documentation for your implementation to see if any other
;; charsets are supported. The behavior of such optional charsets
;; may differ between implementations.
;;
;; Other external formats are also possible with abcl.
#+abcl
(remove-duplicates
(append '(("US-ASCII") ("ISO-8859-1") ("UTF-8") ("UTF-16BE") ("UTF-16LE") ("UTF-16"))
(mapcar (lambda (encoding)
(let ((n (symbol-name encoding))
(u (string-upcase encoding)))
(if (string= n u)
(list n)
(list n u))))
(system:available-encodings)))
:test (function equal))
#-(or abcl ccl clisp cmu ecl sbcl lispworks)
(progn
(warn "What are the available external formats in ~A ?"
(lisp-implementation-type))
'(("US-ASCII")))
"Give an a-list of name and list of aliases of encoding systems in
the current Common Lisp implementation. Those names and aliases are strings.")
(defun fill-character-set-lisp-encoding ()
"
DO: Set the cs-lisp-encoding of the character-sets present in
the current implementation.
"
(dolist (lsl *lisp-encodings* (values))
(let* ((aliases (add-aliases-to-group lsl *aliases*))
(cs (some (function find-character-set) aliases)))
(when cs
;; We don't add the aliases to the lisp-encoding, since this
;; list is used to make the implementation specific encodings
;; and external-formats.
(setf (cs-lisp-encoding cs) lsl)))))
(defgeneric make-external-format (character-encoding &optional line-termination)
(:documentation "Makes an implementation specific external-format.")
(:method ((cs character-set) &optional line-termination)
(if (cs-lisp-encoding cs)
(let ((encoding (first (cs-lisp-encoding cs)))
(line-termination (or line-termination
#+ccl ccl:*default-line-termination*
#-ccl :unix)))
(check-type line-termination (member :unix :mac :dos))
#+ccl
(ccl:make-external-format :domain nil
:character-encoding (intern encoding "KEYWORD")
:line-termination (case line-termination
((:unix :dos) line-termination)
((:mac) :macos)))
#+clisp
(ext:make-encoding :charset (symbol-value (intern encoding "CHARSET"))
:line-terminator line-termination
:input-error-action :error
:output-error-action :error)
#+cmu
(if (string-equal encoding "ISO-8859-1")
:iso-latin-1-unix
(progn #|should not occur|#
(cerror 'character-set-error
:character-set cs
:format-control "The character-set ~S has no lisp-encoding in ~A"
:format-arguments (list (cs-name cs) (lisp-implementation-type)))
:default))
#+ecl
(cond
((string-equal encoding "ISO-8859-1")
:iso-8859-1)
#+unicode
((string-equal encoding "UTF-8")
:utf-8)
(t #|should not occur|#
(cerror 'character-set-error
:character-set cs
:format-control "The character-set ~S has no lisp-encoding in ~A"
:format-arguments (list (cs-name cs) (lisp-implementation-type)))
:default))
#+sbcl
(intern encoding "KEYWORD")
#+abcl
(intern encoding "KEYWORD")
#-(or abcl ccl clisp cmu ecl sbcl)
(values
(find (lambda (cs) (member encoding (cs-lisp-encoding cs)
:test (function string-equal)))
*character-sets*)
:unix))
(error 'character-set-error
:character-set cs
:format-control "The character-set ~S has no lisp-encoding in ~A"
:format-arguments (list (cs-name cs) (lisp-implementation-type)))))
(:method ((character-set-name string) &optional line-termination)
(let ((cs (find-character-set character-set-name)))
(if cs
(make-external-format cs line-termination)
(error 'character-set-error
:character-set (string character-set-name)
:format-control "There is no character-set named ~S"
:format-arguments (list (string character-set-name))))))
(:method ((character-set symbol) &optional line-termination)
(make-external-format (string character-set) line-termination)))
(defun external-format-character-encoding (external-format)
#+ccl (ccl:external-format-character-encoding external-format)
#+(and clisp unicode) (string (ext:encoding-charset external-format))
#+cmu (string external-format)
#+ecl (string external-format)
#+sbcl (string external-format)
#+abcl (string external-format)
#-(or abcl ccl (and clisp unicode) cmu ecl sbcl)
(error "~S: How to decode an external-format in ~A"
'external-format-character-encoding
(lisp-implementation-type)))
(defun external-format-line-termination (external-format)
#+(or cmu ecl sbcl abcl) (declare (ignore external-format))
#+ccl (ccl:external-format-line-termination external-format)
#+(and clisp unicode) (string (ext:encoding-line-terminator external-format))
#+cmu :unix
#+ecl :unix
#+sbcl :unix
#+abcl :unix ; TODO: ???
#-(or abcl ccl (and clisp unicode) cmu ecl sbcl)
(error "~S: How to decode an external-format in ~A"
'external-format-line-termination
(lisp-implementation-type)))
(defun character-set-to-lisp-encoding (cs &key (line-termination :unix))
"
CS: A character set designator (ie. a character-set, or a string or
symbol naming a character-set).
RETURN: An implementation specific object representing the encoding for
the given character-set and line-termination.
SIGNAL: An error if line-termination is not (member :unix :mac :dos nil) or
if cs has no emacs encoding.
"
(assert (member line-termination '(:unix :mac :dos nil)))
(make-external-format (etypecase cs
(character-set cs)
((or string symbol) (find-character-set cs)))
line-termination))
(defun character-set-for-lisp-encoding (encoding)
"
ENCODING: An implementation specific object representing an encoding.
possibly with line-termination.
RETURN: The character-set that correspond to this lisp-encoding ;
the line-termination.
"
(values (external-format-character-encoding encoding)
(external-format-line-termination encoding)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; Emacs coding systems
;;;
(defparameter *emacs-encodings*
#||
;; emacs lisp code to generate the following list.
(require 'cl)
(sort*
(mapcar
(lambda (sl) (mapcar (lambda (sym) (upcase (symbol-name sym))) sl))
(delete-duplicates
(mapcar (lambda (coding-system)
(or (coding-system-get coding-system 'alias-coding-systems)
(list coding-system)))
(let ((coding-system-list '()))
(mapatoms (lambda (sym) (when (and sym (coding-system-p sym))
(push sym coding-system-list))))
coding-system-list))
:test (function equal)))
(function string<) :key (function first))
||#
(quote
(("CHINESE-BIG5" "BIG5" "CN-BIG5" "CP950")
("CHINESE-HZ" "HZ-GB-2312" "HZ")
("CHINESE-ISO-8BIT" "CN-GB-2312" "EUC-CHINA" "EUC-CN" "CN-GB" "GB2312" "CP936")
("CHINESE-ISO-8BIT-WITH-ESC")
("COMPOUND-TEXT" "X-CTEXT" "CTEXT")
("COMPOUND-TEXT-WITH-EXTENSIONS" "X-CTEXT-WITH-EXTENSIONS" "CTEXT-WITH-EXTENSIONS")
("CP1125" "RUSCII" "CP866U")
("CP437")
("CP720")
("CP737")
("CP775")
("CP850")
("CP851")
("CP852")
("CP855")
("CP857")
("CP860")
("CP861")
("CP862")
("CP863")
("CP864")
("CP865")
("CP866")
("CP869")
("CP874")
("CTEXT-NO-COMPOSITIONS")
("CYRILLIC-ALTERNATIVNYJ" "ALTERNATIVNYJ")
("CYRILLIC-ISO-8BIT" "ISO-8859-5")
("CYRILLIC-ISO-8BIT-WITH-ESC")
("CYRILLIC-KOI8" "KOI8-R" "KOI8" "CP878")
("EMACS-MULE")
("EUC-TW" "EUC-TAIWAN")
("GEORGIAN-PS")
("GREEK-ISO-8BIT" "ISO-8859-7")
("GREEK-ISO-8BIT-WITH-ESC")
("HEBREW-ISO-8BIT" "ISO-8859-8" "ISO-8859-8-E" "ISO-8859-8-I")
("HEBREW-ISO-8BIT-WITH-ESC")
("IN-IS13194" "DEVANAGARI")
("IN-IS13194-WITH-ESC")
("ISO-2022-7BIT")
("ISO-2022-7BIT-LOCK" "ISO-2022-INT-1")
("ISO-2022-7BIT-LOCK-SS2" "ISO-2022-CJK")
("ISO-2022-7BIT-SS2")
("ISO-2022-8BIT-SS2")
("ISO-2022-CN" "CHINESE-ISO-7BIT")
("ISO-2022-CN-EXT")
("ISO-2022-JP" "JUNET")
("ISO-2022-JP-2")
("ISO-2022-KR" "KOREAN-ISO-7BIT-LOCK")
("ISO-8859-11")
("ISO-8859-6" "ARABIC-ISO-8BIT")
("ISO-LATIN-1" "ISO-8859-1" "LATIN-1")
("ISO-LATIN-1-WITH-ESC")
("ISO-LATIN-10" "ISO-8859-16" "LATIN-10")
("ISO-LATIN-2" "ISO-8859-2" "LATIN-2")
("ISO-LATIN-2-WITH-ESC")
("ISO-LATIN-3" "ISO-8859-3" "LATIN-3")
("ISO-LATIN-3-WITH-ESC")
("ISO-LATIN-4" "ISO-8859-4" "LATIN-4")
("ISO-LATIN-4-WITH-ESC")
("ISO-LATIN-5" "ISO-8859-9" "LATIN-5")
("ISO-LATIN-5-WITH-ESC")
("ISO-LATIN-6" "ISO-8859-10" "LATIN-6")
("ISO-LATIN-7" "ISO-8859-13" "LATIN-7")
("ISO-LATIN-8" "ISO-8859-14" "LATIN-8")
("ISO-LATIN-8-WITH-ESC")
("ISO-LATIN-9" "ISO-8859-15" "LATIN-9" "LATIN-0")
("ISO-LATIN-9-WITH-ESC")
("ISO-SAFE" "US-ASCII")
("JAPANESE-ISO-7BIT-1978-IRV" "ISO-2022-JP-1978-IRV" "OLD-JIS")
("JAPANESE-ISO-8BIT" "EUC-JAPAN-1990" "EUC-JAPAN" "EUC-JP")
("JAPANESE-ISO-8BIT-WITH-ESC")
("JAPANESE-SHIFT-JIS" "SHIFT_JIS" "SJIS" "CP932")
("KOI8-T" "CYRILLIC-KOI8-T")
("KOI8-U")
("KOREAN-ISO-8BIT" "EUC-KR" "EUC-KOREA" "CP949")
("KOREAN-ISO-8BIT-WITH-ESC")
("LAO")
("LAO-WITH-ESC")
("MAC-ROMAN")
("MIK")
("MULE-UTF-16" "UTF-16")
("MULE-UTF-16BE" "UTF-16BE")
("MULE-UTF-16BE-WITH-SIGNATURE" "UTF-16BE-WITH-SIGNATURE"
"MULE-UTF-16-BE" "UTF-16-BE")
("MULE-UTF-16LE" "UTF-16LE")
("MULE-UTF-16LE-WITH-SIGNATURE" "UTF-16LE-WITH-SIGNATURE"
"MULE-UTF-16-LE" "UTF-16-LE")
("MULE-UTF-8" "UTF-8")
("NEXT")
("NO-CONVERSION")
("PT154")
("RAW-TEXT")
("THAI-TIS620" "TH-TIS620" "TIS620" "TIS-620")
("THAI-TIS620-WITH-ESC")
("TIBETAN-ISO-8BIT" "TIBETAN")
("TIBETAN-ISO-8BIT-WITH-ESC")
("UNDECIDED")
("UTF-7")
("VIETNAMESE-TCVN" "TCVN" "TCVN-5712")
("VIETNAMESE-VIQR" "VIQR")
("VIETNAMESE-VISCII" "VISCII")
("VIETNAMESE-VSCII" "VSCII")
("W3M-EUC-JAPAN")
("W3M-ISO-LATIN-1")
("WINDOWS-1250" "CP1250")
("WINDOWS-1251" "CP1251" "CP1251")
("WINDOWS-1252" "CP1252" "CP1252")
("WINDOWS-1253" "CP1253")
("WINDOWS-1254" "CP1254")
("WINDOWS-1255" "CP1255")
("WINDOWS-1256" "CP1256")
("WINDOWS-1257" "CP1257")
("WINDOWS-1258" "CP1258")))
"List of emacs encoding, grouped by aliases")
(defun fill-character-set-emacs-encoding ()
"
DO: Set the cs-emacs-encoding of the character-sets present in
the current implementation.
"
(dolist (ecsl *emacs-encodings* (values))
(let ((cs (some (function find-character-set)
(add-aliases-to-group ecsl *aliases*))))
(when cs
(setf (cs-emacs-encoding cs) ecsl)))))
(defun character-set-to-emacs-encoding (cs &key (line-termination :unix))
"
CS: A character set designator (ie. a character-set, or a string or
symbol naming a character-set).
RETURN: A string naming the emacs encoding for the given character-set
and line-termination.
SIGNAL: An error if line-termination is not (member :unix :mac :dos nil) or
if cs has no emacs encoding.
"
(assert (member line-termination '(:unix :mac :dos nil)))
(let* ((cs (etypecase cs
(character-set cs)
((or string symbol) (find-character-set cs))))
(ee (cs-emacs-encoding cs)))
(unless ee
(error "The character-set ~A has no corresponding emacs encoding"
(cs-name cs)))
(format nil "~(~A~:[~;~:*-~A~]~)" (first ee) line-termination)))
(defun character-set-from-emacs-encoding (ecs)
"
ECS: A string or symbol naming the emacs encoding,
possibly suffixed by a line-termination.
RETURN: The character-set that correspond to this emacs-encoding ;
the line-termination.
"
(let ((line-termination nil)
(ecs (string ecs)))
(cond
((suffixp "-unix" ecs :test (function char-equal))
(setf ecs (subseq ecs 0 (- (length ecs) 5))
line-termination :unix))
((suffixp "-dos" ecs :test (function char-equal))
(setf ecs (subseq ecs 0 (- (length ecs) 4))
line-termination :dos))
((suffixp "-mac" ecs :test (function char-equal))
(setf ecs (subseq ecs 0 (- (length ecs) 4))
line-termination :mac)))
(values
(find-if (lambda (cs) (member ecs (cs-emacs-encoding cs)
:test (function string-equal)))
*character-sets*)
line-termination)))
(defun emacs-encoding-to-lisp-external-format (emacs-encoding)
"
RETURN: the external-format value corresponding to this EMACS-ENCODING.
"
(multiple-value-bind (charset line-termination)
(character-set-from-emacs-encoding emacs-encoding)
(when charset
(character-set-to-lisp-encoding charset :line-termination line-termination))))
(eval-when (:load-toplevel :execute)
(fill-character-set-emacs-encoding)
(fill-character-set-lisp-encoding))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; The rest was used to generate the data in
;;; COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS
;;;
#+(and (and) clisp)
(defun compute-character-set-ranges ()
"
DO: Read the character-set file and build the *character-sets* list,
then update the character sets with emacs encodings, lisp encodings,
and character set ranges (found in clisp).
RETURN: *character-sets*
"
(setf *character-sets* (read-character-sets-file "character-sets"))
(fill-character-set-emacs-encoding)
(fill-character-set-lisp-encoding)
(dolist (cs *character-sets*)
(when (cs-lisp-encoding cs)
(let ((charset (find-symbol (first (cs-lisp-encoding cs)) "CHARSET")))
(setf (cs-ranges cs)
#+#.(cl:if #+mocl (cl:and (cl:find-package "SYSTEM")
(cl:find-symbol "GET-CHARSET-RANGE" "SYSTEM"))
#-mocl (cl:ignore-errors
(cl:find-symbol "GET-CHARSET-RANGE" "SYSTEM"))
'(:and) '(:or))
(map 'vector (function char-code)
(system::get-charset-range charset))
#-#.(cl:if #+mocl (cl:and (cl:find-package "SYSTEM")
(cl:find-symbol "GET-CHARSET-RANGE" "SYSTEM"))
#-mocl (cl:ignore-errors
(cl:find-symbol "GET-CHARSET-RANGE" "SYSTEM"))
'(:and) '(:or))
(coerce
(loop
:with charset = (symbol-value charset)
:with i = 0
:for start = (loop
:until (or (< char-code-limit i)
(typep (code-char i) charset))
:do (incf i)
:finally (return (when (<= i char-code-limit)
i)))
:while start
:nconc (list start
(loop
:while (and (<= i char-code-limit)
(typep (code-char i) charset))
:do (incf i)
:finally (return (1- i)))))
'vector)))))
*character-sets*)
;;; Provide a default value for *CHARACTER-SETS*
#-(and)
(let ((*print-right-margin* 72))
(pprint
`(setf *character-sets*
(list
,@(mapcar
(lambda (cs)
`(make-character-set
:mib-enum ,(cs-mib-enum cs)
:name ,(cs-name cs)
:aliases ',(cs-aliases cs)
:mime-encoding ',(cs-mime-encoding cs)
:source ',(cs-source cs)
:comments ',(cs-comments cs)
:references ',(cs-references cs)
:ranges ,(cs-ranges cs)))
(compute-character-set-ranges))))))
;;;; THE END ;;;;
| 29,286 | Common Lisp | .lisp | 692 | 33.166185 | 107 | 0.571003 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 84a1080f98de3f9281947cc4f94cf23446e104b8f2daedce162b33800ca4c3b8 | 4,881 | [
-1
] |
4,882 | closer-weak-test.lisp | informatimago_lisp/clext/closer-weak-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: closer-weak-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Test the closer-weak package.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-02-24 <PJB> Added this header. Moved tests.lisp in here.
;;;;BUGS
;;;;
;;;; - integrate tests with simple-test for standard reporting.
;;;;
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
;; #+clisp (pushnew :weak-test *features*)
;; #+#.#+(and clisp (not debug-weak))
;; (cl:if (cl:y-or-n-p "Are we debugging it on clisp?") '(and) '(or))
;; #-(and clisp (not debug-weak))'(or) (pushnew :debug-weak *features*)
(defpackage "COM.INFORMATIMAGO.CLEXT.CLOSER-WEAK.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.CLEXT.CLOSER-WEAK")
#+clisp (:import-from "EXT" "GC")
#+cmu (:import-from "EXTENSIONS" "GC")
#+ccl (:import-from "CCL" "GC")
(:shadowing-import-from
"COM.INFORMATIMAGO.CLEXT.CLOSER-WEAK"
"HASH-TABLE" "MAKE-HASH-TABLE"
"HASH-TABLE-P" "HASH-TABLE-COUNT" "HASH-TABLE-REHASH-SIZE"
"HASH-TABLE-REHASH-THRESHOLD" "HASH-TABLE-SIZE" "HASH-TABLE-TEST"
"GETHASH" "REMHASH" "MAPHASH" "WITH-HASH-TABLE-ITERATOR" "CLRHASH")
(:export "TEST/ALL"))
(in-package "COM.INFORMATIMAGO.CLEXT.CLOSER-WEAK.TEST")
#+sbcl (defun gc () (sb-ext:gc :full t))
(defvar co)
(defvar tab)
(defvar wp)
(defvar wpp)
;;;
;;; This tests.lisp is taken from clisp-2.38/tests/tests.lisp
;;; and modified to take only the weak-*.tst files we're interested in.
;;;
;; run the test suit:
(defun princ-error (c) (format t "~&[~A]: ~A~%" (type-of c) c))
#+old-clisp
;; Binding *ERROR-HANDLER* is a hammer technique for catching errors. It also
;; disables CLCS processing and thus breaks tests that rely on the condition
;; system, such as:
;; - the compile-file on structure literal test in clos.lisp
;; - all tests that use IGNORE-ERRORS
(defmacro with-ignored-errors (&rest forms)
(let ((b (gensym)))
`(block ,b
(let ((*error-handler*
#'(lambda (&rest args)
(with-standard-io-syntax
(let* ((*print-readably* nil)
(error-message (apply #'format nil (cdr args))))
(terpri) (princ error-message)
(return-from ,b (values 'error error-message)))))))
,@forms))))
#+(or (and akcl (not gcl)) ecl)
(defmacro with-ignored-errors (&rest forms)
(let ((b (gensym))
(h (gensym)))
`(block ,b
(let ((,h (symbol-function 'system:universal-error-handler)))
(unwind-protect
(progn (setf (symbol-function 'system:universal-error-handler)
#'(lambda (&rest args) (return-from ,b 'error)))
,@forms)
(setf (symbol-function 'system:universal-error-handler) ,h))))))
#+allegro
(defmacro with-ignored-errors (&rest forms)
(let ((r (gensym)))
`(let ((,r (multiple-value-list (excl:errorset (progn ,@forms)))))
(if (car ,r) (values-list (cdr ,r)) 'error))))
#-(or old-clisp (and akcl (not gcl)) ecl allegro)
(defmacro with-ignored-errors (&rest forms)
(let ((b (gensym)))
`(block ,b
(handler-bind
((error #'(lambda (condition)
(princ-error condition)
(return-from ,b (values 'error
(princ-to-string condition))))))
,@forms))))
(defun merge-extension (type filename)
(make-pathname :type type :defaults filename))
;; (lisp-implementation-type) may return something quite long, e.g.,
;; on CMUCL it returns "CMU Common Lisp".
(defvar lisp-implementation
#+clisp "CLISP" #+(and akcl (not gcl)) "AKCL" #+gcl "GCL" #+ecl "ECL" #+allegro "ALLEGRO" #+cmu "CMUCL"
#-(or clisp akcl gcl ecl allegro cmu) (lisp-implementation-type))
(defvar *eval-method* :eval)
(defvar *eval-out* nil)
(defvar *eval-err* nil)
(defun my-eval (form)
(when *eval-out* (get-output-stream-string *eval-out*))
(when *eval-err* (get-output-stream-string *eval-err*))
#+mocl
(ecase *eval-method*
(:eval (eval form)))
#-mocl
(ecase *eval-method*
(:eval (eval form))
(:compile (funcall (compile nil `(lambda () ,form))))
(:both (let ((e-value (eval form))
(c-value (funcall (compile nil `(lambda () ,form)))))
(unless (equalp e-value c-value)
(error "eval: ~S; compile: ~S" e-value c-value))
e-value))))
(defgeneric pretty-compare (result my-result log)
(:documentation "print a pretty comparison of two results")
(:method ((result sequence) (my-result sequence) (log stream))
(let ((pos (mismatch result my-result :test #'equalp)))
(let ((*print-length* 10))
(if pos
(flet ((pretty-tail-10 (seq)
(if (and (> (length seq) (+ pos 10))
(typep seq 'string))
(concatenate 'string (subseq seq pos (+ pos 10)) "...")
(subseq seq pos))))
(format log "~&Differ at position ~:D: ~S vs ~S~%CORRECT: ~S~%~7A: ~S~%"
pos
(if (< pos (length result))
(elt result pos) 'end-of-sequence)
(if (< pos (length my-result))
(elt my-result pos) 'end-of-sequence)
(pretty-tail-10 result)
lisp-implementation
(pretty-tail-10 my-result)))
(format log "~&Type mismatch: ~S should be ~S~%"
(type-of my-result) (type-of result))))))
(:method ((result pathname) (my-result pathname) (log stream))
(dolist (slot '(pathname-host pathname-device pathname-directory
pathname-name pathname-type pathname-version))
(let ((s-r (funcall slot result)) (s-m (funcall slot my-result)))
(format log "~&~S:~%CORRECT: ~S~%~7A: ~S~%~:[ DIFFERENT!~;same~]~%"
slot s-r lisp-implementation s-m (equal s-r s-m)))))
(:method ((result t) (my-result t) (log stream)))) ; do nothing
(defun show (object &key ((:pretty *print-pretty*) *print-pretty*))
"Print the object on its own line and return it. Used in many tests!"
(fresh-line) (prin1 object) (terpri) object)
(defun type-error-handler (err)
"Print the condition and THROW.
Usage: (handler-bind ((type-error #'type-error-handler)) ...)"
(princ-error err)
(let ((da (type-error-datum err)) (et (type-error-expected-type err)))
(show (list :datum da :expected-type et) :pretty t)
(throw 'type-error-handler (typep da et))))
(defvar *test-ignore-errors* t)
(defvar *test-result-in-file* t
"T: CLISP-style: evaluation result in the file after the test form.
NIL: sacla-style: forms should evaluate to non-NIL.")
(defun do-test (stream log)
(let ((eof stream) (error-count 0) (total-count 0))
(loop
(let ((form (read stream nil eof)) out err (result nil))
(when (or (eq form eof) (eq result eof)) (return))
(if *test-result-in-file*
(setq result (read stream))
(setq form `(not ,form)))
(incf total-count)
(show form)
(multiple-value-bind (my-result error-message)
(if *test-ignore-errors*
(with-ignored-errors (my-eval form)) ; return ERROR on errors
(my-eval form)) ; don't disturb the condition system when testing it!
(setq out (and *eval-out* (get-output-stream-string *eval-out*))
err (and *eval-err* (get-output-stream-string *eval-err*)))
(cond ((eql result my-result)
(format t "~&EQL-OK: ~S~%" result)
(progress-success))
((equal result my-result)
(format t "~&EQUAL-OK: ~S~%" result)
(progress-success))
((equalp result my-result)
(format t "~&EQUALP-OK: ~S~%" result)
(progress-success))
(t
(incf error-count)
(progress-failure-message form "~&ERROR!! ~S should be ~S !~%" my-result result)
(format t "~&ERROR!! ~S should be ~S !~%" my-result result)
(format log "~&Form: ~S~%CORRECT: ~S~%~7A: ~S~%~@[~A~%~]"
form result lisp-implementation
my-result error-message)
(pretty-compare result my-result log)
(format log "~[~*~:;OUT:~%~S~%~]~[~*~:;ERR:~%~S~]~2%"
(length out) out (length err) err))))))
(values total-count error-count)))
(defmacro check-ignore-errors (&body body)
`(handler-case (progn ,@body)
(type-error (c)
(if (ignore-errors
(typep (type-error-datum c) (type-error-expected-type c)))
(format nil "[~S --> ~A]: ~S is of type ~S" ',body c
(type-error-datum c) (type-error-expected-type c))
c))
(stream-error (c)
(if (streamp (stream-error-stream c)) c
(format nil "[~S --> ~A]: ~S is not a ~S" ',body c
(stream-error-stream c) 'stream)))
(file-error (c)
(let ((path (file-error-pathname c)))
(if (or (pathnamep path) (stringp path) (characterp path)) c
(format nil "[~S --> ~A]: ~S is not a ~S" ',body c
(file-error-pathname c) 'pathname))))
(package-error (c)
(let ((pack (package-error-package c)))
(if (or (packagep pack) (stringp pack) (characterp pack)) c
(format nil "[~S --> ~A]: ~S is not a ~S" ',body c
(package-error-package c) 'package))))
(cell-error (c)
(if (cell-error-name c) c
(format nil "[~S --> ~A]: no cell name" ',body c)))
(error (c) c)
(:no-error (v) (format t "~&no error, value: ~S~%" v))))
(defun do-errcheck (stream log)
(let ((eof "EOF") (error-count 0) (total-count 0))
(loop
(let ((form (read stream nil eof))
(errtype (read stream nil eof)))
(when (or (eq form eof) (eq errtype eof)) (return))
(incf total-count)
(show form)
(let ((my-result (check-ignore-errors (my-eval form)))
(out (and *eval-out* (get-output-stream-string *eval-out*)))
(err (and *eval-err* (get-output-stream-string *eval-err*))))
(multiple-value-bind (typep-result typep-error)
(ignore-errors (typep my-result errtype))
(cond ((and (not typep-error) typep-result)
(format t "~&OK: ~S~%" errtype)
(progress-success))
(t
(incf error-count)
(progress-failure-message form "~&ERROR!! ~S instead of ~S !~%" my-result errtype)
(format t "~&ERROR!! ~S instead of ~S !~%" my-result errtype)
(format log "~&Form: ~S~%CORRECT: ~S~%~7A: ~S~%~
~[~*~:;OUT:~%~S~%~]~[~*~:;ERR:~%~S~]~2%"
form errtype lisp-implementation my-result
(length out) out (length err) err)))))))
(values total-count error-count)))
(defvar *dirpath* nil)
(eval-when (:compile-toplevel)
(defparameter *dirpath* #.(make-pathname :name nil :type nil :version nil
:defaults *compile-file-pathname*)))
(eval-when (:load-toplevel :execute)
(defparameter *dirpath* (or *dirpath* (make-pathname :name nil :type nil :version nil
:defaults *load-pathname*))))
(defvar *run-test-tester* #'do-test)
(defvar *run-test-type* "tst")
(defvar *run-test-erg* "erg")
(defvar *run-test-truename*)
(defun run-test (testname
&key ((:tester *run-test-tester*) *run-test-tester*)
((:ignore-errors *test-ignore-errors*)
*test-ignore-errors*)
((:eval-method *eval-method*) *eval-method*)
(logname testname)
&aux (logfile (merge-extension *run-test-erg* logname))
error-count total-count *run-test-truename*)
(let ((*default-pathname-defaults* *dirpath*))
(with-open-file (s (merge-pathnames
(merge-extension *run-test-type* testname)
*dirpath* nil)
:direction :input)
(setq *run-test-truename* (truename s))
(format t "~&~s: started ~s~%" 'run-test s)
(with-open-file (log (merge-pathnames logfile *dirpath* nil)
:direction :output
#+(or cmu sbcl) :if-exists
#+(or cmu sbcl) :supersede
#+ansi-cl :if-exists #+ansi-cl :new-version)
(setq logfile (truename log))
(let* ((*package* *package*) (*print-circle* t) (*print-pretty* nil)
(*eval-err* (make-string-output-stream))
(*error-output* (make-broadcast-stream *error-output* *eval-err*))
(*eval-out* (make-string-output-stream))
(*standard-output* (make-broadcast-stream *standard-output*
*eval-out*)))
(setf (values total-count error-count)
(funcall *run-test-tester* s log))))))
(format t "~&~s: finished ~s (~:d error~:p out of ~:d test~:p)~%"
'run-test testname error-count total-count)
(if (zerop error-count)
(delete-file logfile)
(format t "~s: see ~a~%" 'run-test logfile))
(list testname total-count error-count))
(defun report-results (res)
"res = list of RUN-TEST return values (testname total-count error-count)"
(let ((error-count (reduce #'+ res :key #'third)))
(format
t "~&finished ~3d file~:p:~31T ~3:d error~:p out of~50T ~5:d test~:p~%"
(length res) error-count (reduce #'+ res :key #'second))
(loop :with here = (truename "./") :for rec :in res :for count :upfrom 1 :do
(format t "~&~3d ~25@a:~31T ~3:d error~:p out of~50T ~5:d test~:p~%"
count (enough-namestring (first rec) here)
(third rec) (second rec)))
error-count))
(defun run-some-tests (&key (dirlist '("./"))
((:eval-method *eval-method*) *eval-method*))
(let ((files (mapcan (lambda (dir)
(directory (make-pathname :name :wild
:type *run-test-type*
:defaults dir)))
dirlist)))
(if files (report-results (mapcar #'run-test files))
(warn "no ~S files in directories ~S" *run-test-type* dirlist))))
(defun run-all-tests (&key (disable-risky t)
(verbose t)
((:eval-method *eval-method*) *eval-method*))
(let ((res ())
#+clisp (custom:*load-paths* nil)
(*features* (if disable-risky *features*
(cons :enable-risky-tests *features*)))
(*standard-output* (if verbose
*standard-output*
(make-broadcast-stream))))
;; Since weakptr can run on #+cmu, we should run
;; the other too with CLOSER-WEAK.
(dolist (ff '(#+(or clisp cmu sbcl) "weak-oid"
#+(or clisp cmu sbcl) "weak"
#+(or clisp cmu sbcl allegro openmcl lispworks) "weakhash"
#+(or clisp cmu sbcl lispworks) "weakhash2"
))
(push (run-test ff) res))
#+(or clisp cmu sbcl allegro lispworks)
(let ((tmp (list "weakptr" 0 0)))
(push tmp res)
(dotimes (i 20)
(let ((weak-res (run-test "weakptr")))
(incf (second tmp) (second weak-res))
(incf (third tmp) (third weak-res)))))
(report-results (nreverse res))))
(define-test test/all ()
(run-all-tests :verbose nil))
#-(and) (progn
(mapcar
(lambda (x)
(list (weak-pointer-p x)
(weak-list-p x)
(weak-and-relation-p x)
(weak-or-relation-p x)
(weak-mapping-p x)
(weak-and-mapping-p x)
(weak-or-mapping-p x)
(weak-alist-p x)))
(list '(a b c)
#(a b c)
(make-weak-pointer (list 'x))
(make-weak-list (list 'x 'y 'z))
(make-weak-and-relation (list (list 'x)))
(make-weak-or-relation (list (list 'x)))
(make-weak-mapping '#:g15 '#:g16)
(make-weak-and-mapping (list '#:g15 '#:g16) '#:g17)
(make-weak-or-mapping (list '#:g15 '#:g16) '#:g17)
(make-weak-alist)))
(let ((a (list 'x))
(b (list 'y)))
(let ((w (make-weak-and-mapping (list a) b)))
(gc)
(list (multiple-value-list (weak-and-mapping-pair w))
(multiple-value-list (weak-and-mapping-value w)))))
(let ((a (list 'x))
(b (list 'y)))
(let ((w (make-weak-or-mapping (list a) b)))
(gc)
(list (multiple-value-list (weak-or-mapping-pair w))
(multiple-value-list (weak-or-mapping-value w)))))
(let
((a1 (list 'x1)) (a2 (list 'x2)) (a3 (list 'x3)) (a4 (list 'x4))
(a5 (list 'x5)))
(let
((w1 (make-weak-alist :initial-contents (list (cons a3 a4))))
(w2 (make-weak-alist :initial-contents (list (cons a1 a2))))
(w3 (make-weak-alist :initial-contents (list (cons a4 a5))))
(w4 (make-weak-alist :initial-contents (list (cons a2 a3)))))
(setq a1 nil a2 nil a4 nil a5 nil) (gc)
(list (weak-alist-contents w2)
(weak-alist-contents w4)
(weak-alist-contents w1)
(weak-alist-contents w3))))
(let ((a1 (list 'x1)) (a2 (list 'x2)) (a3 (list 'x3)) (a4 (list 'x4)) (a5 (list 'x5))) (let ((w1 (make-weak-alist :initial-contents (list (cons a3 a4)))) (w2 (make-weak-alist :initial-contents (list (cons a1 a2)))) (w3 (make-weak-alist :initial-contents (list (cons a4 a5)))) (w4 (make-weak-alist :initial-contents (list (cons a2 a3))))) (setq a1 nil a2 nil a4 nil a5 nil) (gc) (list (weak-alist-contents w2) (weak-alist-contents w4) (weak-alist-contents w1) (weak-alist-contents w3))))
);; progn
;;;; THE END ;;;;
| 19,932 | Common Lisp | .lisp | 410 | 37.802439 | 496 | 0.537601 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 90c237ea0c8334eff7f40faa1d4db13956acf1a61c1ddb98e556fda07d14726d | 4,882 | [
-1
] |
4,883 | debug.lisp | informatimago_lisp/clext/debug.lisp | (eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.DEBUG"
(:use "COMMON-LISP"
"BORDEAUX-THREADS")
(:shadow "WITH-LOCK-HELD")
(:export "TR" "WITH-LOCK-HELD"))
(in-package "COM.INFORMATIMAGO.CLEXT.DEBUG")
(defvar *tr-lock* (make-lock "trace"))
(defvar *tr-output* (make-synonym-stream '*trace-output*))
(defun tr (fc &rest a)
(bt:with-lock-held (*tr-lock*)
(format *tr-output* "~&~30A: ~?~&" (thread-name (current-thread)) fc a)))
(defmacro with-lock-held ((place) &body body)
(let ((lock (gensym)))
`(let ((,lock ,place))
(tr "will acquire lock ~A" (ccl:lock-name ,lock))
(unwind-protect
(bt:with-lock-held (,lock)
(tr "acquired lock ~A" (ccl:lock-name ,lock))
,@body)
(tr "released lock ~A" (ccl:lock-name ,lock))))))
;;;; THE END ;;;;
| 918 | Common Lisp | .lisp | 23 | 34.695652 | 78 | 0.611924 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c8a7f1102f53819a670abf6e7093c735b4aadf5b3aa3cd5298962b25a19117eb | 4,883 | [
-1
] |
4,884 | queue-test.lisp | informatimago_lisp/clext/queue-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: queue-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Tests the atomic non-negative queue, blocking on decrement at 0.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2016-01-16 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.QUEUE.TEST"
(:use "COMMON-LISP"
"BORDEAUX-THREADS"
"COM.INFORMATIMAGO.CLEXT.QUEUE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.TIME")
(:export
"TEST/ALL")
(:documentation "Tests the thread-safe message queue."))
(in-package "COM.INFORMATIMAGO.CLEXT.QUEUE.TEST")
(define-test test/queue (&optional (*standard-output* *standard-output*))
"A simple little test. Check the output."
(slow-test 480
(let ((queue (make-queue "test-queue"))
(out (make-lock "out")))
(check string= (queue-name queue) "test-queue")
(check = (queue-count queue) 0)
(make-thread (lambda ()
(loop
:named producer
:with message := 1000
:repeat 50
:do (with-lock-held (out)
(format t "~&Will enqueue: ~A~%" (incf message)) (finish-output))
(enqueue queue message)
(sleep (random 0.1))))
:name "test-queue-consummer"
:initial-bindings `((*standard-output* . ,*standard-output*)))
(loop :named consumer
:with expected := 1000
:repeat 5
:do (loop :repeat 10
:do (let ((message (dequeue queue)))
(with-lock-held (out)
(format t "~&Did dequeue: ~A~%" message) (finish-output))
(check = message (incf expected))))
(terpri) (force-output)
(sleep 2))
(check string= (queue-name queue) "test-queue")
(check = (queue-count queue) 0))))
(define-test test/all ()
(let ((*test-output* *standard-output*))
(test/queue (make-broadcast-stream))))
;;;; THE END ;;;;
| 3,407 | Common Lisp | .lisp | 79 | 35.556962 | 94 | 0.552077 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 82dfe41ad362dcc535fbf5f1f211a130837eb54dadcb411fc8f324b912cb52c4 | 4,884 | [
-1
] |
4,885 | logical-pathname.lisp | informatimago_lisp/clext/logical-pathname.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: logical-pathname.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Parses and validates a logical pathname namestring.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-11-01 <PJB> Extracted from COM.INFORMATIMAGO.COMMON-LISP.VIRTUAL-FILE-SYSTEM.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.LOGICAL-PATHNAME"
(:use "COMMON-LISP"
"CL-PPCRE"
"SPLIT-SEQUENCE")
(:export "PARSE-LOGICAL-PATHNAME"))
(in-package "COM.INFORMATIMAGO.CLEXT.LOGICAL-PATHNAME")
(defun re-compile (re &key extended)
(cl-ppcre:create-scanner re :extended-mode extended))
(defun re-exec (re string &key (start 0) (end nil))
(multiple-value-bind (mstart mend starts ends)
(cl-ppcre:scan re string
:start start
:end (or end (length string)))
(and mstart mend
(values-list (cons (list mstart mend)
(map 'list (lambda (s e)
(if (or s e)
(list s e)
nil))
starts ends))))))
(defun re-match-string (string match)
(subseq string (first match) (second match)))
(defun re-match (regexp string)
(re-exec (re-compile regexp :extended t) string))
(defparameter *logical-pathname-regexp*
(let ((host "(([-A-Z0-9]+):)?")
(dire "(;)?(([-*A-Z0-9]+;|\\*\\*;)*)")
(name "([-*A-Z0-9]+)?")
(type "(.([-*A-Z0-9]+)(.([0-9]+|newest|NEWEST|\\*))?)?"))
#-(and)
(concatenate 'string "^" host dire name type "$")
(re-compile (concatenate 'string "^" host dire name type "$")
:extended t)))
(defun parse-logical-pathname (string &key (start 0) (end nil))
"
RETURN: a list containing the pathname components: (host directory name type version)
"
;; TODO: implement junk-allowed
;; TODO: return new position.
(flet ((wild (item part wild-inferiors-p)
(cond ((string= "*" item) :wild)
((and wild-inferiors-p (string= "**" item)) :wild-inferiors)
((search "**" item)
(error "Invalid ~A part: ~S; ~
\"**\" inside a wildcard-world is forbidden."
part item))
((position #\* item) (list :wild-word item))
(t item))))
(multiple-value-bind (all
dummy0 host
relative directories dummy1
name
dummy2 type dummy3 version)
(re-exec *logical-pathname-regexp* string :start start :end end)
(declare (ignore dummy0 dummy1 dummy2 dummy3))
(if all
(list (and host (re-match-string string host))
(if relative :relative :absolute)
(and directories
(mapcar
(lambda (item) (wild item "directory" t))
(butlast (split-sequence #\; (re-match-string
string directories)))))
(and name
(let ((item (re-match-string string name)))
(wild item "name" nil)))
(and type
(let ((item (re-match-string string type)))
(wild item "type" nil)))
(and version
(let ((version (re-match-string string version)))
(cond
((string= "*" version) :wild)
((string-equal "NEWEST" version) :newest)
(t (parse-integer version :junk-allowed nil))))))
(error "Syntax error parsing logical pathname ~S"
(subseq string start end))))))
#-(and)
(mapc
(lambda (path) (print (ignore-errors (parse-logical-pathname path))))
'("SYS:KERNEL;PATH;LOGICAL.LISP"
"SYS:;KERNEL;PATH;LOGICAL.LISP"
"SYS:;KERNEL;**;LOGICAL.LISP"
"SYS:;KERNEL;**;LO*L.LISP"
"SYS:kernel;path/logical.lisp"))
;;;; THE END ;;;;
| 5,341 | Common Lisp | .lisp | 121 | 34.107438 | 90 | 0.529197 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 423024f14cf7bbc2d80c824e0e1b92c6dd8f65ce230f311a589477967dcb1603 | 4,885 | [
-1
] |
4,886 | redirecting-stream.lisp | informatimago_lisp/clext/redirecting-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: redirecting-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This Gray stream redirects to streams determined at I/O time.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2014-03-26 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; GPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2014 - 2017
;;;;
;;;; 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/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.REDIRECTING-STREAM"
(:use "COMMON-LISP"
"TRIVIAL-GRAY-STREAMS")
(:export "REDIRECTING-CHARACTER-OUTPUT-STREAM"
"REDIRECTING-CHARACTER-INPUT-STREAM"))
(in-package "COM.INFORMATIMAGO.CLEXT.REDIRECTING-STREAM")
;; ---
(defclass redirecting-character-output-stream (fundamental-character-output-stream)
((output-stream-function :initarg :output-stream-function :reader output-stream-function)
(column :initform 0 :accessor column)))
(defmethod stream-write-char ((stream redirecting-character-output-stream) character)
(write-char character (funcall (output-stream-function stream)))
(case character
((#\newline #\return #\page) (setf (column stream) 0))
(otherwise (incf (column stream))))
character)
(defmethod stream-line-column ((stream redirecting-character-output-stream))
(column stream))
(defmethod stream-start-line-p ((stream redirecting-character-output-stream))
(zerop (column stream)))
(defmethod stream-write-string ((stream redirecting-character-output-stream) string &optional (start 0) (end nil))
(let ((end (or end (length string)))
(last-newline (position-if (lambda (ch) (position ch #(#\newline #\return #\page)))
string :from-end t :start start :end end)))
(write-string string (funcall (output-stream-function stream)) :start start :end end)
(if last-newline
(setf (column stream) (- end last-newline 1))
(incf (column stream) (- end start)))
string))
(defmethod stream-terpri ((stream redirecting-character-output-stream))
(terpri (funcall (output-stream-function stream))))
(defmethod stream-fresh-line ((stream redirecting-character-output-stream))
(fresh-line (funcall (output-stream-function stream))))
(defmethod stream-finish-output ((stream redirecting-character-output-stream))
(finish-output (funcall (output-stream-function stream))))
(defmethod stream-force-output ((stream redirecting-character-output-stream))
(force-output (funcall (output-stream-function stream))))
(defmethod stream-clear-output ((stream redirecting-character-output-stream))
(clear-output (funcall (output-stream-function stream))))
(defmethod stream-advance-to-column ((stream redirecting-character-output-stream) column)
(let ((spaces (- column (column stream))))
(when (plusp spaces)
(write-string (case spaces
((1) " ")
((2) " ")
((3) " ")
((4) " ")
((5) " ")
((6) " ")
((7) " ")
((8) " ")
((9) " ")
((10) " ")
((11) " ")
((12) " ")
(otherwise (make-string spaces :initial-element #\space)))
(funcall (output-stream-function stream))))))
;; ---
(defclass redirecting-character-input-stream (fundamental-character-input-stream)
((input-stream-function :initarg :input-stream-function :reader input-stream-function)))
(defmethod stream-read-char ((stream redirecting-character-input-stream))
(read-char (funcall (input-stream-function stream))))
(defmethod stream-unread-char ((stream redirecting-character-input-stream) character)
(unread-char (funcall (input-stream-function stream)) character))
(defmethod stream-read-char-no-hang ((stream redirecting-character-input-stream))
(read-char-no-hang (funcall (input-stream-function stream))))
(defmethod stream-peek-char ((stream redirecting-character-input-stream))
(peek-char (funcall (input-stream-function stream))))
(defmethod stream-listen ((stream redirecting-character-input-stream))
(listen (funcall (input-stream-function stream))))
(defmethod stream-read-line ((stream redirecting-character-input-stream))
(read-line (funcall (input-stream-function stream))))
(defmethod stream-clear-input ((stream redirecting-character-input-stream))
(clear-input (funcall (input-stream-function stream))))
;;;; THE END ;;;;
| 5,544 | Common Lisp | .lisp | 108 | 45.87963 | 114 | 0.640931 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 5352520b07136f52389350bf14cdbb8a77adc7cbfc6819ff567aa6350fc4dafa | 4,886 | [
-1
] |
4,887 | queue.lisp | informatimago_lisp/clext/queue.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: queue.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A atomic non-negative queue, blocking on decrement at 0.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2017-04-16 <PJB> Added queue-empty-p.
;;;; 2015-08-29 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2017
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.QUEUE"
(:use "COMMON-LISP"
"BORDEAUX-THREADS")
(:export "QUEUE" "QUEUEP"
"MAKE-QUEUE"
"QUEUE-NAME"
"QUEUE-COUNT"
"QUEUE-EMPTYP"
"ENQUEUE"
"DEQUEUE")
(:documentation "Implements a thread-safe message queue."))
(in-package "COM.INFORMATIMAGO.CLEXT.QUEUE")
(defstruct (queue
(:constructor make-queue
(name
&aux
(lock (make-lock (format nil "~A-LOCK" name)))
(not-empty (make-condition-variable :name (format nil "~A-NOT-EMPTY" name)))))
(:copier nil)
(:predicate queuep))
name head tail lock not-empty)
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (documentation 'make-queue 'function) "
RETURN: A new queue named NAME
"
(documentation 'queue-name 'function) "
RETURN: The name of the QUEUE.
"
(documentation 'queue-head 'function) "
RETURN: the head CONS cell of the QUEUE.
"
(documentation 'queue-head 'function) "
RETURN: the tail CONS cell of the QUEUE.
"
(documentation 'queuep 'function) "
RETURN: Predicate for the QUEUE type.
"
(documentation 'queue-lock 'function) "
RETURN: The lock of the QUEUE.
"
(documentation 'queue-not-empty 'function) "
RETURN: The NOT-EMPTY condition variable of the QUEUE.
"))
(defun enqueue (queue message)
"
DO: Atomically enqueues the MESSAGE in the QUEUE. If the
queue was empty, then a condition-notify is sent on the
queue not-empty condition.
RETURN: MESSAGE
"
(with-lock-held ((queue-lock queue))
(if (queue-tail queue)
(setf (cdr (queue-tail queue)) (list message)
(queue-tail queue) (cdr (queue-tail queue)))
(progn
(setf (queue-head queue) (setf (queue-tail queue) (list message)))
(condition-notify (queue-not-empty queue)))))
message)
(defun dequeue (queue)
"
DO: Atomically, dequeue the first message from the QUEUE. If
the queue is empty, then wait on the not-empty condition
of the queue.
RETURN: the dequeued MESSAGE.
"
(with-lock-held ((queue-lock queue))
(loop :until (queue-head queue)
:do (condition-wait (queue-not-empty queue) (queue-lock queue)))
(if (eq (queue-head queue) (queue-tail queue))
(prog1 (car (queue-head queue))
(setf (queue-head queue) nil
(queue-tail queue) nil))
(pop (queue-head queue)))))
(defun queue-count (queue)
"
RETURN: The number of entries in the QUEUE.
NOTE: The result may be falsified immediately, if another thread
enqueues or dequeues.
"
(with-lock-held ((queue-lock queue))
(length (queue-head queue))))
(defun queue-emptyp (queue)
"
RETURN: Whether the queue is empty.
NOTE: The result may be falsified immediately, becoming false if
another thread enqueues, or becoming true if another
thread dequeues.
"
(not (queue-head queue)))
;;;; THE END ;;;;
| 4,644 | Common Lisp | .lisp | 126 | 32.111111 | 97 | 0.613934 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 626783af45dd78aeaf1853ec0330880a20cbbe780e0f16743c8afe5f854e07e5 | 4,887 | [
-1
] |
4,888 | shell.lisp | informatimago_lisp/clext/shell.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: shell.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Exports shell functions.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2020-11-04 <PJB> Extracted from tools.manifest.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2020 - 2020
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.SHELL"
(:use "COMMON-LISP")
(:export "SHELL-COMMAND-TO-STRING"
"MKTEMP-PATH"))
(in-package "COM.INFORMATIMAGO.CLEXT.SHELL")
(defun mktemp-path (&key
(kind :file)
(stem "TEMP")
(type "TXT")
base-directory)
(check-type kind (member :file :directory))
(check-type stem string)
(check-type type (or null string))
(check-type base-directory (or null string pathname))
(let ((name (format nil "~:@(~A~36,8,'0R~)"
stem (random (expt 2 32))))
(type (when type (string-upcase type))))
(namestring
(translate-logical-pathname
(ecase kind
(:file
(cond
(base-directory
(merge-pathnames
(make-pathname :name name :type type :version nil
:case :common)
base-directory))
((ignore-errors (logical-pathname-translations "TMP"))
(make-pathname :host "TMP" :directory '(:absolute)
:name name :type type :version nil
:case :common))
(t
(merge-pathnames
(make-pathname :directory '(:relative)
:name name :type type :version nil
:case :common)
(user-homedir-pathname)))))
(:directory
(cond
(base-directory
(merge-pathnames
(make-pathname :directory (list :relative name)
:name nil :type nil :version nil
:case :common)
base-directory))
((ignore-errors (logical-pathname-translations "TMP"))
(make-pathname :host "TMP" :directory (list :absolute name)
:name nil :type nil :version nil
:case :common))
(t
(merge-pathnames
(make-pathname :directory (list :relative name)
:name nil :type nil :version nil
:case :common)
(user-homedir-pathname))))))))))
#-(and)
(list
(mktemp-path)
(mktemp-path :kind :file)
(mktemp-path :kind :file :stem "foo" :type "bar")
(mktemp-path :kind :file :base-directory "/var/tmp/")
(mktemp-path :kind :directory)
(mktemp-path :kind :directory :stem "foo" :type "bar")
(mktemp-path :kind :directory :base-directory "/var/tmp/"))
(defun shell-command-to-string (command &rest arguments)
"Execute the COMMAND with asdf:run-shell-command and returns its
stdout in a string (going thru a file)."
(let* ((*default-pathname-defaults* #P"")
(path (mktemp-path :stem "OUT-")))
(unwind-protect
(when (zerop (asdf:run-shell-command
(format nil "~? > ~S" command arguments path)))
(with-output-to-string (out)
(with-open-file (file path)
(loop
:for line = (read-line file nil nil)
:while line :do (write-line line out)))))
(ignore-errors (delete-file path)))))
;;;; THE END ;;;;
| 4,537 | Common Lisp | .lisp | 112 | 31.669643 | 83 | 0.544118 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bec73449c1675319343dac4101285dbe1b1b5302e52513309490087071445f77 | 4,888 | [
-1
] |
4,889 | gate.lisp | informatimago_lisp/clext/gate.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: gate.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements multi-threading gates, such as:
;;;;
;;;; - when a thread waits on a gate, it blocks unconditionally.
;;;;
;;;; - when a thread signals this gate, all the threads blocked on
;;;; this gate are unblocked.
;;;;
;;;; - atomicity of unlocking and waiting on the gate is ensured, so
;;;; that no signal is "lost".
;;;;
;;;; It is important that the waiting threads check their external
;;;; condition (in its mutex) in a loop with the gate-wait call, if
;;;; that external condition can be modified by waiting threads
;;;; previously unblocked.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-09-15 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.GATE"
(:use "COMMON-LISP"
"BORDEAUX-THREADS")
(:shadowing-import-from "COM.INFORMATIMAGO.CLEXT.CLOSER-WEAK"
"MAKE-HASH-TABLE")
(:export "MAKE-GATE" "GATE-NAME" "GATE-WAIT" "GATE-SIGNAL")
(:documentation "
The gate API is the same as for condition variables. However, their
semantics differ:
- when a thread waits on a gate, it blocks unconditionally.
- when a thread signals a gate, all the threads blocked on
this gate are unblocked.
- atomicity of unlocking and waiting on the gate is ensured, so that
no signal is \"lost\". On the other hand, gate signals without
blocking threads are ignored.
It is important that the waiting threads check their external
condition (in its mutex) in a loop with the gate-wait call, if
that external condition can be modified by waiting threads
previously unblocked.
"))
(in-package "COM.INFORMATIMAGO.CLEXT.GATE")
#|
The way condition variables are defined in `bordeaux-threads`, and
implemented by `bordeaux-threads` in `ccl` (and possibly in other
implementations) is quite deficient, or to the least, insufficient.
Here is the `bordeaux-threads` specifications:
Resource contention: condition variables
A condition variable provides a mechanism for threads to put
themselves to sleep while waiting for the state of something to
change, then to be subsequently woken by another thread which has
changed the state.
A condition variable must be used in conjunction with a lock to
protect access to the state of the object of interest. The procedure
is as follows:
Suppose two threads A and B, and some kind of notional event channel
C. A is consuming events in C, and B is producing them. CV is a
condition-variable:
1. A acquires the lock that safeguards access to C
2. A threads and removes all events that are available in C
3. When C is empty, A calls CONDITION-WAIT, which atomically
releases the lock and puts A to sleep on CV
4. Wait to be notified; CONDITION-WAIT will acquire the lock again
before returning
5. Loop back to step 2, for as long as threading should continue
When B generates an event E, it:
1. acquires the lock guarding C
2. adds E to the channel
3. calls CONDITION-NOTIFY on CV to wake any sleeping thread
4. releases the lock
To avoid the "lost wakeup" problem, the implementation must guarantee
that CONDITION-WAIT in thread A atomically releases the lock and
sleeps. If this is not guaranteed there is the possibility that thread
B can add an event and call CONDITION-NOTIFY between the lock release
and the sleep - in this case the notify call would not see A, which
would be left sleeping despite there being an event available.
`Bordeaux-threads` ``condition-variables`` are implemented on `ccl`
using ccl ``semaphores``, which contain a counter. This is good since
it avoids losing notifications, which is important given the way
``condition-wait`` is written for `ccl` in `bordeaux-threads`,
ie. without any atomicity.
On the other hand, the user must be careful to check the external
condition corresponding to the condition variable and to loop over
condition-wait, for this lack of atomicity allows the external
condition to be falsified after the awaking of the thread, or merely
between the notification and the awaking of the thread.
Now, in the presence of multiple consumers, or when the number of
times condition-wait is called must not match the number of times
condition-notify is called (eg. when writing to a pipe in different
chunk sizes than read), this abstraction is totally deficient.
We take the following assumptions:
- multiple consumer threads;
- multiple producer threads;
- the consumers want to block when an external condition is not met;
- the external condition can potentially be realized only by another
thread (not "miraculously"), therefore when another thread does
something that might realize this external condition, it will signal
the gate;
- several threads may signal the gate at about the same time;
- when a gate is signaled, all the threads blocked on it need to
run, in their respective mutex blocks, and check the external
condition for themselves;
- the external condition may persist for more or fewer steps,
processed by the consumer threads. Ie. the number of gate
signalings doesn't necessarily match the number of gate waitings.
Once the gate is signaled and the blocked threads are awaken,
the gate signal is forgotten.
|#
(defvar *global-lock* (make-lock "gate-lock"))
(defvar *thread-vars* (make-hash-table :weak :key :test 'eq))
(defstruct (gate
(:constructor %make-gate))
name
lock
(waiting-threads '()))
(defun make-gate (&key (name ""))
(%make-gate :name name
:lock (make-lock (format nil "~A/gate-lock" name))))
(defun %get-thread-condition-variable (thread)
(with-lock-held (*global-lock*)
(or (gethash thread *thread-vars*)
(setf (gethash thread *thread-vars*)
(make-condition-variable
:name (format nil "~A/gate" (thread-name thread)))))))
(defun condition-variable-name (x) x)
(defun gate-wait (gate lock)
(let ((my-var (%get-thread-condition-variable (current-thread))))
(with-lock-held ((gate-lock gate))
(push my-var (gate-waiting-threads gate))
(release-lock lock)
(unwind-protect
(condition-wait my-var (gate-lock gate))
(acquire-lock lock)))))
(defun gate-signal (gate)
(loop :until (acquire-lock (gate-lock gate) nil))
(unwind-protect
(progn
(mapc (function condition-notify) (gate-waiting-threads gate))
(setf (gate-waiting-threads gate) '()))
(release-lock (gate-lock gate))))
;;;; THE END ;;;;
| 7,710 | Common Lisp | .lisp | 168 | 43.392857 | 83 | 0.722408 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 06ef63de0adf03aa2ff6779ced1a7059d438b9af8a7e405ef374caf0270674fa | 4,889 | [
-1
] |
4,890 | association.lisp | informatimago_lisp/clext/association.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: association.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Macros definitions for the objecteering metamodel.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-11-01 <PJB> Changed license from GPL3 to AGPL3.
;;;; 2009-05-20 <PJB> Adapted these macros for the objecteering metamodel.
;;;; 2009-01-09 <PJB> Added this comment.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;*************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.ASSOCIATION"
(:use "COMMON-LISP" "CLOSER-MOP")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL" "SCAT")
(:shadowing-import-from "CLOSER-MOP"
"STANDARD-CLASS" "STANDARD-GENERIC-FUNCTION" "STANDARD-METHOD"
"DEFMETHOD" "DEFGENERIC")
(:export "DEFINE-CLASS" "DEFINE-ASSOCIATION" "CHECK-OBJECT" "CHECK-CHAIN"
"ATTACH" "DETACH" "ASSOCIATEDP" "DID-LINK" "WILL-UNLINK"))
(in-package "COM.INFORMATIMAGO.CLEXT.ASSOCIATION")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; CLASSES
;;;
(defmacro define-class (class-name superclasses &key slots documentation)
"
DO: Define a class, with a slightly different syntax.
Since there are a lot of classes with no additionnal slots,
to make the slots optional, we introduce them with a :slots keyword.
The initarg and accessor are automatically generated with the same
name as the slot by default.
The initform is automatically set to nil by default.
"
`(progn
(defclass ,class-name ,superclasses
,(mapcar
(lambda (slot)
(if (atom slot)
`(,slot
:initarg ,(intern (string slot) "KEYWORD")
:initform 'nil
:accessor ,slot)
(destructuring-bind (slot-name &key initarg initform type accessor documentation) slot
`(,slot-name
:initarg ,(or initarg
(intern (string slot-name) "KEYWORD"))
:initform ,(or initform 'nil)
:accessor ,(or accessor slot-name)
,@(when documentation (list :documentation documentation))
,@(when type (list :type type))))))
slots)
,@(when documentation `((:documentation ,documentation))))
',class-name))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; ASSOCIATIONS
;;;
;;; This kind of association will modify the class of the objects they
;;; associate, adding the needed slots.
;;;
(defun add-new-element (list element &key (key (function identity)) lessp test)
"
DO: Modify the list, adding the element if it is not already in the list.
LESSP and TEST are mutually exclusive.
When LESSP is provided, the element is inserted in the middle of the list.
When TEST is provided, the element is inserted at the end.
If LIST is NIL, then a new list is returned.
KEY: a key function. Default IDENTITY.
LESSP: a lessp function. Default NIL.
TEST: an equal function. Default EQL.
"
(assert (or (null lessp) (null test)))
(cond
((null list) (list element))
((null lessp)
(let ((test (or test (function eql))))
(loop
:with element-key = (funcall key element)
:for cell :on (cons nil list)
:while (and (cdr cell)
(not (funcall test
element-key
(funcall key (cadr cell)))))
:finally (progn
(unless (cdr cell)
(setf (cdr cell) (list element)))
(return list)))))
(t
(loop
:with element-key = (funcall key element)
:with result = (cons nil list)
:for cell :on result
:while (and (cdr cell)
(funcall lessp
(funcall key (cadr cell))
element-key))
:finally (progn
(cond
((null (cdr cell))
(setf (cdr cell) (list element)))
((funcall lessp
element-key
(funcall key (cadr cell)))
(push element (cdr cell))))
(return (cdr result)))))))
(eval-when (:load-toplevel :compile-toplevel :execute)
(defun variations (item list)
(if (null list)
(list (list item))
(cons (cons item list)
(mapcar (lambda (rest) (cons (car list) rest))
(variations item (cdr list))))))
(defun permutations (elements)
(cond
((null elements) (list elements))
((null (cdr elements)) (list elements))
(t (mapcan (lambda (subperm) (variations (car elements) subperm))
(permutations (cdr elements))))))
(defun multiplicity (multiplicity)
"
DO: Decodes the multiplicity.
MULTIPLICITY: may be either an integer, or a string designator
the form \"*\" or \"MIN-MAX\" or \"MIN..MAX\".
(beware that the token 0..1 is a 'potential number').
RETURN: MIN; MAX"
(multiple-value-bind (min max)
(if (integerp multiplicity)
(values multiplicity multiplicity)
(let* ((smul (string multiplicity))
(dash (position #\- smul))
(dotdot (search ".." smul))
(*read-eval* nil)
(*read-base* 10.))
(cond
(dash
(values (read-from-string smul t nil :end dash)
(read-from-string smul t nil :start (1+ dash))))
(dotdot
(values (read-from-string smul t nil :end dotdot)
(read-from-string smul t nil :start (+ 2 dotdot))))
(t
(let ((star (read-from-string smul)))
(if (eq '* star)
(values 0 '*)
(error "Missing a '-' or '..' in the multiplicity: ~A"
multiplicity)))))))
;; (print (list min max (and (integerp min) (not (minusp min))
;; (or (eq max '*)
;; (and (integerp max) (<= min max))))))
(assert (and (integerp min) (not (minusp min))
(or (eq max '*)
(and (integerp max) (<= min max))))
(min max) "Invalid multiplicity ~A" multiplicity)
(values min max)))
(defun xor (a b) (if a (not b) b))
(defun imply (p q) (or (not p) q))
(defun generate-link-parameters (endpoints)
(mapcar (function first) endpoints))
(defun generate-link-arguments (endpoints)
(let ((keyword (find-package "KEYWORD")))
(mapcan (lambda (endpoint)
(destructuring-bind (role &key &allow-other-keys) endpoint
(list (intern (string role) keyword) role)))
endpoints)))
(defun generate-attach-parameters (endpoints)
(mapcar (lambda (endpoint)
(destructuring-bind (role &key type accessor slot
&allow-other-keys) endpoint
(assert (not (and accessor slot)) (accessor slot)
"ACCESSOR and SLOT are mutually exclusive.")
(list role type)))
endpoints))
;; 0
;; 1
;; n
;; 0..1
;; 0..n
;; 1..1
;; n..m
;; 0..*
;; 1..*
;; n..*
;;
;; n-1 n-m,1<m
;; set o (k o)
;; add o (k o)
;; remove o o
;; contains o o
;; get x x
;; size x x
;; clear x x
;; remove-key k
;; contains-key k
;;
;; (a . role . set b) (asso-link a b) (b . role . set a)
;; (a . role . add b) (asso-link a b) (b . role . add a)
;; (a . role . remove b) (asso-unlink a b) (b . role . remove a)
;; (a . role . contains b) (asso-contains-p a b) (b . role . contains a)
;; (a . role . get) -> b =/= (b . role . get) -> a
;; (a . role . size) -> n1 =/= (asso-size) =/= (b . role . size) -> n2
;; (a . role . clear) =/= (asso-clear) =/= (b . role . clear)
;; (a . role . remove-key k1) =/= (b . role . remove-key k2)
;; (a . role . contains-key k1) =/= (b . role . contains-key k2)
;; (a . role . add k1 b) =/= (asso-link k2 a k1 b) =/= (b . role . add k2 b)
;; (a . role . add k1 b) =/= (asso-link k2 a k1 b) =/= (b . role . add k2 b)
;;
;; Currently implemented:
;; ASSO-LINK, ASSO-UNLINK, ASSO-CONTAINS-P
;; GET and SIZE are implemented by using directly the accessor for the role
(defun generate-single-setter (accessor slot copier object value)
(if accessor
`(setf (,accessor ,object) (,copier ,value))
`(setf (slot-value ,object ',slot) (,copier ,value))))
(defun generate-multi-adder (accessor slot copier test object value)
`(pushnew (funcall ,copier ,value)
(if accessor
(,accessor ,object)
(slot-value ,object ',slot))
:test ,test))
(defun generate-getter (accessor slot copier object value)
(declare (ignore value))
(if (eq copier 'identity)
(if accessor
`(,accessor ,object)
`(slot-value ,object ',slot))
`(,copier ,(if accessor
`(,accessor ,object)
`(slot-value ,object ',slot)))))
(defgeneric did-link (association-name left right)
(:documentation
"Hook called after a new link for the association is created between LEFT and RIGHT.")
(:method (association-name (left t) (right t))
(declare (ignorable association-name))
(values)))
(defgeneric will-unlink (association-name left right)
(:documentation
"Hook called before an old link for the association is removed between LEFT and RIGHT.")
(:method (association-name (left t) (right t))
(declare (ignorable association-name))
(values)))
(defun generate-addset (association-name value object this)
(destructuring-bind (this-role &key
((:slot this-slot))
((:accessor this-accessor))
((:multiplicity this-multiplicity))
((:implementation this-implementation))
((:ordered this-ordered))
((:test this-test) '(function eql))
((:lessp this-lessp) nil this-lessp-givenp)
((:key this-key) '(function identity))
((:copy this-copy) '(function identity))
&allow-other-keys) this
(multiple-value-bind (this-min this-max) (multiplicity this-multiplicity)
(declare (ignore this-min))
(let ((this-implementation (or this-implementation
(if (equal 1 this-max) 'reference 'list)))
(this-test (if this-lessp-givenp
(let ((a (gensym))
(b (gensym))
(lessp (gensym)))
`(lambda (,a ,b)
(let ((,lessp ,this-lessp))
(and (not (funcall ,lessp ,a ,b))
(not (funcall ,lessp ,b ,a))))))
this-test)))
(assert (member this-implementation '(list reference))
(this-implementation)
"IMPLEMENTATION other than REFERENCE, LIST are ~
not implemented yet.")
(assert (imply (eq this-implementation 'reference) (equal 1 this-max))
(this-implementation this-max)
"THIS-IMPLEMENTATION must be LIST when THIS-MAX is not 1")
(flet ((slot () (if this-accessor
`(,this-accessor ,object)
`(slot-value ,object ',this-slot)))
(value () (if (or (equal '(function identity) this-copy)
(eq 'identity this-copy))
value
`(,this-copy ,value))))
;; 0-1 link reference (setf as (copy o))
;; 1-1 link reference (setf as (copy o))
;;
;; n-m link list (if (and (< (length as) m) (not (containsp o as))) (push o as) (error "full"))
;; 0-* link list (pushnew o as :test test)
;; 1-* link list (pushnew o as :test test)
;; n-* link list (pushnew o as :test test)
;; 0-1 link list (setf as (list (copy o)))
;; 1-1 link list (setf as (list (copy o)))
(ecase this-implementation
((reference)
`(progn (assert (null ,(slot)))
(setf ,(slot) ,(value))))
((list)
(cond
((eql 1 this-max)
`(progn (assert null ,(slot))
(setf ,(slot) (list ,(value)))))
((eql '* this-max)
(if this-ordered
`(progn (assert (not (find ,value ,(slot) :test ,this-test :key ,this-key)))
(setf ,(slot) (add-new-element ,(slot) ,(value)
,@(if this-lessp-givenp
`(:lessp ,this-lessp)
`(:test ,this-test))
:key ,this-key)))
`(progn (assert (not (find ,value ,(slot) :test ,this-test :key ,this-key)))
(pushnew ,(value) ,(slot) :test ,this-test :key ,this-key))))
(t
(let ((vendpoint (gensym)))
`(let ((,vendpoint ,(slot)))
(if (and (< (length ,vendpoint) ,this-max)
(not (find ,value ,vendpoint :test ,this-test :key ,this-key)))
,(if this-ordered
`(setf ,(slot) (add-new-element ,(slot) ,(value)
,@(if this-lessp-givenp
`(:lessp ,this-lessp)
`(:test ,this-test))
:key ,this-key))
`(push ,(value) ,(slot)))
(cerror "Endpoint ~A of association ~A is full, maximum multiplicity is ~A is reached."
',this-role ',association-name ',this-max)))))))))))))
(defun generate-remove (association-name value object this)
(destructuring-bind (this-role &key
((:slot this-slot))
((:accessor this-accessor))
((:multiplicity this-multiplicity))
((:implementation this-implementation))
;; ((:ordered this-ordered))
((:test this-test) '(function eql))
((:lessp this-lessp) nil this-lessp-givenp)
((:key this-key) '(function identity))
((:copy this-copy) '(function identity))
&allow-other-keys) this
(multiple-value-bind (this-min this-max) (multiplicity this-multiplicity)
(let ((this-implementation (or this-implementation
(if (equal 1 this-max) 'reference 'list)))
(this-test (if this-lessp-givenp
(let ((a (gensym))
(b (gensym))
(lessp (gensym)))
`(lambda (,a ,b)
(let ((,lessp ,this-lessp))
(and (not (funcall ,lessp ,a ,b))
(not (funcall ,lessp ,b ,a))))))
this-test)))
(assert (member this-implementation '(list reference))
(this-implementation)
"IMPLEMENTATION other than REFERENCE or LIST ~
are not implemented yet.")
(assert (imply (eq this-implementation 'reference) (equal 1 this-max))
(this-implementation this-max)
"THIS-IMPLEMENTATION must be LIST when THIS-MAX is not 1")
(flet ((slot () (if this-accessor
`(,this-accessor ,object)
`(slot-value ,object ',this-slot)))
(value () (if (or (equal '(function identity) this-copy)
(eq 'identity this-copy))
value
`(,this-copy ,value))))
;; 1-1 unlink reference (error)
;; 0-1 unlink reference (setf as nil)
;;
;; 1-* unlink list (if (< 1 (length as)) (setf as (delete o as :test test)) (error))
;; 1-1 unlink list (if (< 1 (length as)) (setf as (delete o as :test test)) (error))
;; n-* unlink list (if (< n (length as)) (setf as (delete o as :test test)) (error))
;; n-m unlink list (if (< n (length as)) (setf as (delete o as :test test)) (error))
;; 0-* unlink list (setf as (delete o as :test test))
;; 0-1 unlink list (setf as (delete o as :test test))
(ecase this-implementation
((reference)
`(when (funcall ,this-test ,value ,(slot))
,(if (eql 1 this-min)
`(error "Cannot remove the only ~A from the ~
association ~A of minimum multiplicity ~A."
',this-role ',association-name ',this-min)
`(setf ,(slot) nil))))
((list)
(let ((vendpoint (gensym)))
`(let ((,vendpoint ,(slot)))
(when (find ,value ,vendpoint :test ,this-test :key ,this-key)
,(if (zerop this-min)
`(setf ,(slot) (delete ,value ,vendpoint
:test ,this-test :key ,this-key :count 1))
`(if (< ,this-min (length ,vendpoint))
(setf ,(slot) (delete ,value ,vendpoint
:test ,this-test :key ,this-key :count 1))
(error "The role ~A of the association ~A ~
has reached its minimum multiplicity ~A."
',this-role ',association-name
',this-min)))))))))))))
(defun generate-contains-p (association-name value object this)
(declare (ignore association-name))
(destructuring-bind (this-role &key
((:slot this-slot))
((:accessor this-accessor))
((:multiplicity this-multiplicity))
((:implementation this-implementation))
((:test this-test) '(function eql))
((:copy this-copy) '(function identity))
&allow-other-keys) this
(declare (ignore this-role))
(multiple-value-bind (this-min this-max) (multiplicity this-multiplicity)
(declare (ignore this-min))
(let ((this-implementation (or this-implementation
(if (equal 1 this-max) 'reference 'list))))
(assert (member this-implementation '(list reference))
(this-implementation)
"IMPLEMENTATION other than REFERENCE or LIST ~
are not implemented yet.")
(assert (imply (eq this-implementation 'reference) (equal 1 this-max))
(this-implementation this-max)
"THIS-IMPLEMENTATION must be LIST when THIS-MAX is not 1")
(flet ((slot () (if this-accessor
`(,this-accessor ,object)
`(slot-value ,object ',this-slot)))
(value () (if (or (equal '(function identity) this-copy)
(eq 'identity this-copy))
value
`(,this-copy ,value))))
;; 0-1 containsp reference (test as o)
;; 1-1 containsp reference (test as o)
;;
;; 0-* containsp list (find o as :test test)
;; 0-1 containsp list (find o as :test test)
;; 1-* containsp list (find o as :test test)
;; 1-1 containsp list (find o as :test test)
;; n-* containsp list (find o as :test test)
;; n-m containsp list (find o as :test test)
(ecase this-implementation
((reference) `(funcall ,this-test ,value ,(slot)))
((list) `(member ,value ,(slot) :test ,this-test))))))))
'#:eval-when/functions-for-macro)
(defun convert-to-direct-slot-definition (class canonicalized-slot)
(apply (function make-instance)
(apply (function closer-mop:direct-slot-definition-class) class canonicalized-slot)
canonicalized-slot))
(defun canonicalize-slot-definition (slotdef)
(list :name (closer-mop:slot-definition-name slotdef)
:readers (closer-mop:slot-definition-readers slotdef)
:writers (closer-mop:slot-definition-writers slotdef)
:type (closer-mop:slot-definition-type slotdef)
:allocation (closer-mop:slot-definition-allocation slotdef)
:initargs (closer-mop:slot-definition-initargs slotdef)
:initform (closer-mop:slot-definition-initform slotdef)
:initfunction (closer-mop:slot-definition-initfunction slotdef)))
(defun ensure-class-slot (class-name slot-name)
(let ((class (find-class class-name)))
(when class
;; finalize it before calling CLOSER-MOP:CLASS-SLOTS
(make-instance class-name)
(unless (find slot-name (closer-mop:class-slots class)
:key (function closer-mop:slot-definition-name))
(closer-mop:ensure-class
class-name
:direct-slots
(append (mapcar (function canonicalize-slot-definition) (closer-mop:class-direct-slots class))
(list (list :name slot-name
:initform 'nil
:initfunction (constantly nil)
:initargs (list (intern (string slot-name) "KEYWORD"))
:readers (list slot-name)
:writers (list `(setf ,slot-name))
:documentation "Generated by define-association"))))))
class))
;; (defmacro define-association (name ((role &key type slot accessor
;; multiplicity implementation
;; multiple ordered qualifier
;; test lessp key copy
;; &allow-other-keys)
;; &rest other-endpoints)
;; &key documentation)
;; "
;; SLOT xor ACCESSOR
;; QUALIFIER
;; "
;; )
;;
;; (defclass employer ()
;; ())
;;
;; (defclass employee ()
;; ())
;;
;; (define-association employs
;; (employers :type employer
;; :multiplicity 0-*
;; :multiple nil)
;; (employees :type employee
;; :qualifier emp-number
;; :multiplicity 1
;; :implementation hash-table))
;;
;; (defclass employer ()
;; ((employees :initform (make-hash-table))))
;;
;; (defclass employee ()
;; ((employers :initform '())))
(defmacro define-association (name endpoints &rest options)
"
Define functions to manage the association:
(name-LINK a b ...)
(name-UNLINK a b ...)
(name-CONTAINS-P a b ...) --> BOOLEAN
(name-SIZE) --> INTEGER
(name-CLEAR) --> INTEGER
taking &KEY arguments named for the ROLE names.
There may be more than two endpoints, in case of ternary, etc associations.
ENDPOINTS a list of (ROLE &KEY TYPE ACCESSOR SLOT MULTIPLICITY MULTIPLE
IMPLEMENTATION COPY TEST ORDERED).
TYPE needed for ATTACH and DETACH.
If all the types are present and different, then ATTACH and
DETACH methods are created for the arguments in any order.
Note: we should review this macro for TYPE vs. CLASS.
Slots may be accessed only in instances of standard-class classes.
Accessors may be used with any type.
ACCESSOR and SLOT are optional, and mutually exclusive.
-------- --------- ---------- ------------- ------- ------ --------
ACCESSOR SLOT Slot Accessor CreSlot CreAcc Use
-------- --------- ---------- ------------- ------- ------ --------
absent absent Role name Role Name Yes Yes slot
When both :accessor and :slot are absent, the role
name is used to create a slot with an accessor in
the associated class.
Note: In this case, :type must be given a class.
-------- --------- ---------- ------------- ------- ------ --------
absent present Given slot N/A No No slot
The associated class is not changed. The given slot
is directly used.
-------- --------- ---------- ------------- ------- ------ --------
present absent N/A Given Accessor No No accessor
The associated class is not changed. The given
accessor is used.
-------- --------- ---------- ------------- ------- ------ --------
present present ...................FORBIDDEN........................
-------- --------- ---------- ------------- ------- ------ --------
MULTIPLICITY may be either an integer, or a string designator the form \"MIN-MAX\"
MIN, MAX an integer or * representing infinity; PRE: (< MIN MAX)
MULTIPLE boolean default NIL indicates whether the same objects may be
in relation together several times.
COPY if not NIL, a function used to copy the objects before storing
or returning them.
LESSP default is NIL. A function used to compare the objects
put into the relation.
TEST default is (FUNCTION EQL), the function used to compare
the objects put into the relation.
Note: If you set COPY, you will probably want to set TEST or LESSP too.
TEST and LESSP are mutually exclusive.
For strings, you may want to set TEST to EQUAL or EQUALP or
LESSP to STRING< or STRING-LESSP
For numbers, you may want to set TEST to =, or LESSP to <.
COPY, TEST and LESSP are evaluated, so you can pass 'fun,
(function fun) or (lambda (x) (fun x)).
ORDERED (only for REFERENCE, LIST, VECTOR and REIFIED).
NIL: the objects are not ordered in the containers.
T: If LESSP is not given, then the objects are kept
in the order of association in the containers.
The KEY of the objects are compared with the TEST
function.
If LESSP is given, then the objects are kept in
the order specified by LESSP applied on the KEY
of the objects.
IMPLEMENTATION is (OR (MEMBER REFERENCE LIST VECTOR HASH-TABLE A-LIST P-LIST REIFIED)
(CONS (HASH-TABLE A-LIST P-LIST)
(CONS (MEMBER REFERENCE LIST VECTOR) NIL)))
indicates the kind of slot used to implement the role.
REFERENCE only when (= 1 MAX) : the related object is stored in the slot.
LIST the related objects are stored in a list.
VECTOR the related objects are stored in a vector.
If MAX is finite, then the size of the vector must be = MAX
else the VECTOR must be adjustable and may have a fill-pointer.
A-LIST the related keys and objects are stored in an a-list.
For qualified roles.
P-LIST the related keys and objects are stored in a p-list.
For qualified roles.
HASH-TABLE the related keys and objects are stored in a HASH-TABLE.
For qualified roles.
REIFIED the association is reified and nothing is stored in the
related objects.
For qualified roles, the multiplicity is per key.
(persons :multiplicity 0-* :implementation hash-table)
gives several persons per key (name -> homonyms).
In case of qualified roles and (< 1 MAX), the IMPLEMENTATION can be given
as a list of two items, the first giving the implementation of the role,
and the second the implementation of the values. (HASH-TABLE VECTOR) maps
with an hash-table keys to vectors of associated objects.
Currently implemented: REFERENCE and LIST.
MULTIPLE is not implemented yet.
OPTIONS a list of (:keyword ...) options.
(:DOCUMENTATION string)
BUGS: If there is an error in handling one association end, after
handling the other end, the state becomes invalid. No transaction :-(
"
(declare (ignore options)) ; for now
(when (endp (rest endpoints))
(error "The association ~A needs at least two endpoints." name))
(assert (= 2 (length endpoints)) ()
"Sorry, associations with more than two endpoints such ~
as ~A are not implemented yet." name)
(let* ((endpoints (mapcar (lambda (endpoint)
(destructuring-bind (role &rest others
&key slot accessor type
&allow-other-keys) endpoint
(unless (or slot accessor)
(assert type (type)
"A :TYPE for the association end must be given ~
when there's no :ACCESSOR or :SLOT.")
(unless slot
(setf slot role)))
(list* role :slot slot :accessor accessor :type type others)))
endpoints))
(link-parameters (generate-link-parameters endpoints))
;; (link-arguments (generate-link-arguments endpoints))
(types (loop :for endpoint :in endpoints
:for type = (getf (rest endpoint) :type)
:when type :collect type))
(attachp (= (length endpoints)
(length (remove-duplicates types))))
(attach-args-permutations
(and attachp (permutations (generate-attach-parameters endpoints))))
(link (scat name '-link))
(unlink (scat name '-unlink))
(contains-p (scat name '-contains-p)))
`(progn
,@(let ((troles (mapcar (lambda (endpoint)
(destructuring-bind (role &key type &allow-other-keys) endpoint
(list type role)))
endpoints)))
(append
(when (first (second troles))
(list `(ensure-class-slot ',(first (first troles)) ',(second (second troles)))))
(when (first (first troles))
(list `(ensure-class-slot ',(first (second troles)) ',(second (first troles)))))))
(defun ,link (&key ,@link-parameters)
,(generate-addset name
(first link-parameters) (second link-parameters)
(first endpoints))
,(generate-addset name
(second link-parameters) (first link-parameters)
(second endpoints))
(did-link ',name ,(first link-parameters) ,(second link-parameters)))
(defun ,unlink (&key ,@link-parameters)
(multiple-value-prog1 (will-unlink ',name
,(first link-parameters)
,(second link-parameters))
,(generate-remove name
(first link-parameters) (second link-parameters)
(first endpoints))
,(generate-remove name
(second link-parameters) (first link-parameters)
(second endpoints))))
(defun ,contains-p (&key ,@link-parameters)
(and ,(generate-contains-p name
(first link-parameters) (second link-parameters)
(first endpoints))
,(generate-contains-p name
(second link-parameters) (first link-parameters)
(second endpoints))
t))
,@ (when attachp
(let ((link-arguments
(generate-link-arguments endpoints ;; (first attach-args-permutations)
)))
(mapcar (lambda (arguments)
(let ((arguments (cons `(asso (eql ',name)) arguments)))
`(progn
(defmethod attach ,arguments
(declare (ignore asso))
(,link ,@link-arguments))
(defmethod detach ,arguments
(declare (ignore asso))
(,unlink ,@link-arguments))
(defmethod associatedp ,arguments
(declare (ignore asso))
(,contains-p ,@link-arguments)))))
attach-args-permutations)))
',name)))
#-(and)
(let* ((class-name type))
(let* ((class (find-class class-name))
(slots (mop:compute-slots class)))
(unless (find role slots :key (function mop:slot-description-name))
(mop:ensure-class
class-name
:direct-default-initargs (mop:class-direct-default-initargs class)
:direct-slots (mop:class-direct-slots class)
:direct-superclasses (mop:class-direct-superclasses class)
:name class-name
:metaclass (class-of class)))))
(defmacro check-object (expression)
"Evaluates the expression and reports an error if it's NIL."
`(or ,expression (error "~S returned NIL" ',expression)))
(defmacro check-chain (expression)
(flet ((chain-expression-p (expression)
"An expression that is a function call of a single other
chain-expression or a simple-expression."
;; Actually, we only check the toplevel...
(and (listp expression)
(= 2 (length expression))
(consp (second expression)))))
(let ((vvalue (gensym)))
(if (chain-expression-p expression)
`(let ((,vvalue (check-chain ,(second expression))))
(or (,(first expression) ,vvalue)
(error "~S returned NIL" ',expression)))
`(check-object ,expression)))))
;;;; THE END ;;;;
| 38,198 | Common Lisp | .lisp | 731 | 37.759234 | 126 | 0.490742 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e9662c0bbad4da1753884ba8cf192fb3b873ef2f759aea7758fbd954d0692204 | 4,890 | [
-1
] |
4,891 | association-test.lisp | informatimago_lisp/clext/association-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: association-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Tests the associations.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-02-22 <PJB> Extracted from association.lisp.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.ASSOCIATION.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.CLEXT.ASSOCIATION"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")
(:import-from "COM.INFORMATIMAGO.CLEXT.ASSOCIATION"
"ADD-NEW-ELEMENT" "MULTIPLICITY")
(:export "TEST/ALL"
"TEST/ADD-NEW-ELEMENT" "TEST/MULTIPLICITY"))
(in-package "COM.INFORMATIMAGO.CLEXT.ASSOCIATION.TEST")
(define-test test/add-new-element ()
(assert-true (equal '(x) (add-new-element nil 'x)))
(assert-true (equal '(x) (add-new-element nil 'x :test (function equal))))
(assert-true (equal '(x) (add-new-element nil 'x :lessp (function string<))))
(assert-true (equal '(x) (add-new-element (list 'x) 'x)))
(assert-true (equal '(x) (add-new-element (list 'x) 'x :test (function equal))))
(assert-true (equal '(x) (add-new-element (list 'x) 'x :lessp (function string<))))
(progn (let* ((list (list 1 2 3))
(result (add-new-element list 0 :test #'=)))
(assert-true (equal result '(1 2 3 0)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3)) (result (add-new-element list 0)))
(assert-true (equal result '(1 2 3 0)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3))
(result (add-new-element list 4 :lessp #'<)))
(assert-true (equal result '(1 2 3 4)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3))
(result (add-new-element list 1 :lessp #'<)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3)) (result (add-new-element list 1)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3))
(result (add-new-element list 1.0 :test #'=)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3)) (result (add-new-element list 2)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3))
(result (add-new-element list 2.0 :test #'=)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3)) (result (add-new-element list 3)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 3))
(result (add-new-element list 3.0 :test #'=)))
(assert-true (equal result '(1 2 3)))
(assert-true (eql result list)))
(let* ((list (list 1 2 4))
(result (add-new-element list 3 :lessp #'<)))
(assert-true (equal result '(1 2 3 4)))
(assert-true (eql result list)))
(let* ((list (list 1 2 4))
(result (add-new-element list 2 :lessp #'<)))
(assert-true (equal result '(1 2 4)))
(assert-true (eql result list)))
(let* ((list (list 1 3 4))
(result (add-new-element list 2 :lessp #'<)))
(assert-true (equal result '(1 2 3 4)))
(assert-true (eql result list)))
(let* ((list (list 1 3 4))
(result (add-new-element list 3 :lessp #'<)))
(assert-true (equal result '(1 3 4)))
(assert-true (eql result list))))
(let ((list (list 2 3 4)))
(assert-true (equal '(1 2 3 4) (add-new-element list 1 :lessp (function <)))))
(let ((list (list 2 3 4)))
(assert-true (equal '(1 2 3 4) (add-new-element list 1 :lessp (function <))))))
(defun test/multiplicity ()
(assert-true (equal (mapcar (lambda (test) (multiple-value-list (multiplicity test)))
'(0 1 2 3
0-1 1-1 0-4 2-4
* 0-* 1-* 4-* ; 34-2
0..1 1..1 0..4 2..4
* 0..* 1..* 4..* ; 34..2
))
'((0 0) (1 1) (2 2) (3 3)
(0 1) (1 1) (0 4) (2 4)
(0 *) (0 *) (1 *) (4 *) ; (34 2)
(0 1) (1 1) (0 4) (2 4)
(0 *) (0 *) (1 *) (4 *) ; (34 2)
))))
(define-test test/all ()
(test/add-new-element)
(test/multiplicity))
;;;; THE END ;;;;
| 5,972 | Common Lisp | .lisp | 125 | 38.704 | 87 | 0.518842 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | fbb91c970b37ff3502b9f88a3426b600f7747f0049e90ab57e416060e64056b7 | 4,891 | [
-1
] |
4,892 | filter-stream.lisp | informatimago_lisp/clext/filter-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: filter-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Filter streams are stream wrappers with a function to process
;;;; the data being input or output.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2017-04-16 <PJB> Close is also defered to the filter function.
;;;; Now all operations can be performed by the filter
;;;; function and the filter-stream stream can be any
;;;; object, not necessarily a stream.
;;;; 2016-12-22 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2016 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.FILTER-STREAM"
(:use "COMMON-LISP"
"TRIVIAL-GRAY-STREAMS")
(:export "MAKE-INPUT-FILTER-STREAM"
"MAKE-OUTPUT-FILTER-STREAM"
"FILTER-STREAM-STREAM"
"FILTER-STREAM-FUNCTION"
"FILTER-ELEMENT-TYPE"
"NO-FILTER"))
(in-package "COM.INFORMATIMAGO.CLEXT.FILTER-STREAM")
(defclass filter ()
((function :initarg :function :accessor filter-stream-function)
(stream :initarg :stream :accessor filter-stream-stream)
(element-type :initarg :element-type :reader filter-stream-element-type)))
(defclass filter-character-input-stream (filter fundamental-character-input-stream)
((column :initform 0 :accessor column)))
(defclass filter-character-output-stream (filter fundamental-character-output-stream)
((column :initform 0 :accessor column)))
(defclass filter-binary-input-stream (filter fundamental-binary-input-stream)
())
(defclass filter-binary-output-stream (filter fundamental-binary-output-stream)
())
(defun make-input-filter-stream (stream filter-function &key element-type)
(let ((element-type (or element-type (stream-element-type stream))))
(make-instance (if (subtypep element-type 'character)
'filter-character-input-stream
'filter-binary-input-stream)
:function filter-function
:stream stream)))
(defun make-output-filter-stream (stream filter-function &key element-type)
(let ((element-type (or element-type (stream-element-type stream))))
(make-instance (if (subtypep element-type 'character)
'filter-character-output-stream
'filter-binary-output-stream)
:function filter-function
:stream stream)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; stream methods
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun check-stream-open (stream where)
(unless (open-stream-p stream)
(error "~S cannot deal with closed stream ~S"
where stream)))
;;; character input
(declaim (inline update-column))
(defun update-column (stream ch)
(when (characterp ch)
(if (char= ch #\newline)
(setf (column stream) 0)
(incf (column stream))))
ch)
(defmethod stream-read-char ((stream filter-character-input-stream))
(check-stream-open stream 'stream-read-char)
(funcall (filter-stream-function stream)
'read-char
(filter-stream-stream stream)))
(defmethod stream-read-char-no-hang ((stream filter-character-input-stream))
(check-stream-open stream 'stream-read-char-no-hang)
(funcall (filter-stream-function stream)
'read-char-no-hang
(filter-stream-stream stream)))
(defmethod stream-peek-char ((stream filter-character-input-stream))
(check-stream-open stream 'stream-peek-char)
(funcall (filter-stream-function stream)
'peek-char
(filter-stream-stream stream)))
(defmethod stream-read-line ((stream filter-character-input-stream))
(check-stream-open stream 'stream-read-line)
(funcall (filter-stream-function stream)
'read-line
(filter-stream-stream stream)))
(defmethod stream-listen ((stream filter-character-input-stream))
(check-stream-open stream 'stream-listen)
(funcall (filter-stream-function stream)
'listen
(filter-stream-stream stream)))
(defmethod stream-unread-char ((stream filter-character-input-stream) ch)
(check-stream-open stream 'stream-unread-char)
(funcall (filter-stream-function stream)
'unread-char
(filter-stream-stream stream)
ch)
ch)
;;; character output
(defmethod stream-write-char ((stream filter-character-output-stream) ch)
(check-stream-open stream 'stream-write-char)
(funcall (filter-stream-function stream)
'write-char
(filter-stream-stream stream)
ch)
(if (char= #\newline ch)
(setf (column stream) 0)
(incf (column stream)))
ch)
(defmethod stream-terpri ((stream filter-character-output-stream))
(check-stream-open stream 'stream-terpri)
(stream-write-char stream #\newline)
nil)
(defmethod stream-write-string ((stream filter-character-output-stream) string &optional (start 0) end)
(check-stream-open stream 'stream-write-string)
(let* ((end (or end (length string)))
(nlp (position #\newline string :start start :end end :from-end t)))
(funcall (filter-stream-function stream)
'write-string
(filter-stream-stream stream)
string start (or end (length string)))
(if nlp
(setf (column stream) (- end nlp))
(incf (column stream) (- end start))))
string)
(defmethod stream-line-column ((stream filter-character-output-stream))
(column stream))
(defmethod stream-start-line-p ((stream filter-character-output-stream))
(zerop (column stream)))
(defmethod stream-advance-to-column ((stream filter-character-output-stream) column)
(check-stream-open stream 'stream-advance-to-column)
(let ((delta (- column (column stream))))
(when (plusp delta)
(stream-write-string stream (make-string delta :initial-element #\space))
delta)))
(defmethod close ((stream filter-character-output-stream) &key abort)
(funcall (filter-stream-function stream)
'close
(filter-stream-stream stream)
abort))
(defmethod close ((stream filter-binary-output-stream) &key abort)
(funcall (filter-stream-function stream)
'close
(filter-stream-stream stream)
abort))
(defmethod close ((stream filter-character-input-stream) &key abort)
(funcall (filter-stream-function stream)
'close
(filter-stream-stream stream)
abort))
(defmethod close ((stream filter-binary-input-stream) &key abort)
(funcall (filter-stream-function stream)
'close
(filter-stream-stream stream)
abort))
;; binary input
(defmethod stream-read-byte ((stream filter-binary-input-stream))
(check-stream-open stream 'stream-read-byte)
(funcall (filter-stream-function stream)
'read-byte
(filter-stream-stream stream)))
;; binary output
(defmethod stream-write-byte ((stream filter-binary-output-stream) byte)
(check-stream-open stream 'stream-write-byte)
(funcall (filter-stream-function stream)
'write-byte
(filter-stream-stream stream)
byte)
byte)
;;; sequence I/O
(defun check-sequence-arguments (direction stream sequence start end)
(assert (<= 0 start end (length sequence))
(sequence start end)
"START = ~D or END = ~D are not sequence bounding indexes for a ~S of length ~D"
start end (type-of sequence) (length sequence))
(ecase direction
(:read
(assert (or (listp sequence)
(and (vectorp sequence)
(subtypep (filter-stream-element-type stream) (array-element-type sequence))))
(sequence)
"For reading, the sequence element type ~S should be a supertype of the stream element type ~S"
(array-element-type sequence) (filter-stream-element-type stream)))
(:write
(assert (or (listp sequence)
(and (vectorp sequence)
(subtypep (array-element-type sequence) (filter-stream-element-type stream))))
(sequence)
"For writing, the sequence element type ~S should be a subtype of the stream element type ~S"
(array-element-type sequence) (filter-stream-element-type stream)))))
(defun %stream-read-sequence (stream sequence start end)
(check-sequence-arguments :read stream sequence start end)
(funcall (filter-stream-function stream)
'read-sequence
(filter-stream-stream stream)
sequence start end))
(defun %stream-write-sequence (stream sequence start end)
(check-sequence-arguments :write stream sequence start end)
(funcall (filter-stream-function stream)
'write-sequence
(filter-stream-stream stream)
sequence start end)
sequence)
(defmethod stream-read-sequence ((stream filter-character-input-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-read-sequence)
(%stream-read-sequence stream sequence start end))
(defmethod stream-read-sequence ((stream filter-binary-input-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-read-sequence)
(%stream-read-sequence stream sequence start end))
(defmethod stream-write-sequence ((stream filter-character-output-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-write-sequence)
(%stream-write-sequence stream sequence start end))
(defmethod stream-write-sequence ((stream filter-binary-output-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-write-sequence)
(%stream-write-sequence stream sequence start end))
(defun no-filter (operation stream &rest arguments)
(ecase operation
;; character
(read-char (read-char stream nil :eof))
(read-char-no-hang (read-char-no-hang stream nil :eof))
(peek-char (peek-char nil stream nil :eof))
(read-line (read-line stream nil :eof))
(listen (listen stream))
(unread-char (unread-char (first arguments) stream))
(write-char (write-char (first arguments) stream))
(write-string (write-string (first arguments) stream :start (second arguments) :end (third arguments)))
;; binary:
(read-byte (read-byte stream nil :eof))
(write-byte (write-byte (first arguments) stream))
;; both:
(read-sequence (read-sequence (first arguments) stream :start (second arguments) :end (third arguments)))
(write-sequence (write-sequence (first arguments) stream :start (second arguments) :end (third arguments)))
(close (close stream :abort (first arguments)))))
;;;; THE END ;;;;
| 12,143 | Common Lisp | .lisp | 261 | 40.651341 | 120 | 0.650858 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 944eedabcb07b67bb4f4cad6eabe4d894846c85c3ab0b2d14425afb62d34f22a | 4,892 | [
-1
] |
4,893 | filter.lisp | informatimago_lisp/clext/filter.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: filter.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This package exports a grep I/O filter,
;;;; and a macro to build unix-like pipes, using
;;;; com.informatimago.clext.pipe.
;;;; Note com.informatimago.interactive.browser:{cat,more,less}
;;;; as any other expression reading *standard-input* and writing
;;;; *standard-output* can be used in a filter,
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-10-10 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2015 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.FILTER"
(:use "COMMON-LISP"
"BORDEAUX-THREADS"
"CL-PPCRE"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM"
"COM.INFORMATIMAGO.CLEXT.PIPE")
(:export "FILTER" "IN" "GREP" "OUT")
(:documentation "
This package exports a grep I/O filter,
and a macro to build unix-like pipes, using
com.informatimago.clext.pipe.
Note com.informatimago.interactive.browser:{cat,more,less}
as any other expression reading *standard-input* and writing
*standard-output* can be used in a filter,
LEGAL
Copyright Pascal J. Bourguignon 2015 - 2015
AGPL3
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 WARRANTYwithout even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"))
(in-package "COM.INFORMATIMAGO.CLEXT.FILTER")
(defun in (pathname &key (external-format :default) (if-does-not-exist :error))
"
DO: Reads the text file at PATHNAME and writes it out
to *STANDARD-OUTPUT*.
EXTERNAL-FORMAT: The external-format for the file.
IF-DOES-NOT-EXIST: (or (member :ERROR :END-OF-FILE NIL) string stream)
If the file doesn't exist, by default an error is
signaled. Alternatives are:
:END-OF-FILE closes the stream bound to
*STANDARD-OUTPUT* Note: you probably should don't
do that on the system standard output.
NIL: do nothing.
a STRING: writes the string to *STANDARD-OUTPUT*.
a STREAM: copy the stream to *STANDARD-OUTPUT*.
SEE ALSO: COM.INFORMATIMAGO.COMMON-LISP.INTERACTIVE.BROWSER:CAT
"
(with-open-file (input pathname
:direction :input
:external-format external-format
:if-does-not-exist (if (eq :error if-does-not-exist)
:error
nil))
(if input
(copy-stream input *standard-output*)
(etypecase if-does-not-exist
(null #|do nothing|#)
(string (write-string if-does-not-exist *standard-output*))
(stream (copy-stream if-does-not-exist *standard-output*))))))
(defun out (pathname &key (external-format :default) (if-exists :error))
"
DO: Writes the data from *STANDARD-INPUT* into the
text file at PATHNAME.
EXTERNAL-FORMAT: The external-format for the file.
IF-EXISTS: same as for OPEN.
"
(with-open-file (output pathname
:direction :output
:external-format external-format
:if-does-not-exist :create
:if-exists if-exists)
(when output
(copy-stream *standard-input* output))))
(defun grep (regexp &key case-insensitive (extended t) count line-number filename)
(loop
:with filename := (typecase filename
((or string pathname) filename)
(null nil)
(t (if (typep *standard-input* 'file-stream)
(pathname *standard-input*)
(princ-to-string *standard-input*))))
:with scanner := (create-scanner regexp
:case-insensitive-mode case-insensitive
:single-line-mode t
:extended-mode extended
:destructive nil)
:with counter := 0
:for line := (read-line *standard-input* nil nil)
:for linum :from 1
:while line
:when (scan scanner line)
:do (if count
(incf counter)
(if line-number
(if filename
(format t "~A:~D:~A~%" filename linum line)
(format t "~D:~A~%" linum line))
(if filename
(format t "~A:~A~%" filename line)
(write-line line))))
:finally (when count
(format t "~D line~:*~P match~:[~;es~]~%"
counter (= 1 counter)))))
(defvar *buffer-size* 4000)
(defmacro filter (&body filter-forms)
(let* ((vpipe (gensym "pipe")))
;; *standard-input* a pipe b pipe c *standard-output* main thread.
;; - -
(if (rest filter-forms)
`(let ((,vpipe (make-pipe :buffer-size *buffer-size*)))
(bt:make-thread (lambda ()
(unwind-protect
(filter ,@(butlast filter-forms))
(close *standard-output*)))
:initial-bindings (list (cons '*standard-output* (pipe-output-stream ,vpipe))
(cons '*standard-input* *standard-input*)))
(let ((*standard-input* (pipe-input-stream ,vpipe)))
,@(last filter-forms)))
(first filter-forms))))
;; (pprint (macroexpand-1 '(filter (in "/etc/passwd") (out "/tmp/p"))))
;; (filter (in "/etc/passwd") (out "/tmp/p"))
;;;; THE END ;;;;
| 7,414 | Common Lisp | .lisp | 160 | 36.9125 | 104 | 0.574893 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a15cb872ea46a818b218470231a0de0b656c115baac34699819247e9cc7ae2e6 | 4,893 | [
-1
] |
4,894 | init.lisp | informatimago_lisp/clext/init.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: init.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Initialization for clext packages.
;;;;
;;;; This files remove some specificities from the lisp environment
;;;; (to make it more Common Lisp),
;;;; initialize the environment
;;;; and add logical pathname translations to help find the other packages.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2006-06-05 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2006 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(setq *load-verbose* nil)
;; clean the imported packages:
(mapc (lambda (used) (unuse-package used "COMMON-LISP-USER"))
(remove (find-package "COMMON-LISP")
(copy-seq (package-use-list "COMMON-LISP-USER"))))
(progn
(defvar *directories* '())
(defun get-directory (key &optional (subpath ""))
(unless *directories*
(with-open-file (dirs (make-pathname :name "DIRECTORIES" :type "TXT"
:version nil :case :common
:defaults (user-homedir-pathname)))
(loop
:for k = (read dirs nil dirs)
:until (eq k dirs)
:do (push (string-trim " " (read-line dirs)) *directories*)
:do (push (intern (substitute #\- #\_ (string k))
"KEYWORD") *directories*))))
(unless (getf *directories* key)
(error "~S: No directory keyed ~S" 'get-directory key))
(merge-pathnames subpath (getf *directories* key) nil)))
#+clisp
(when (string= (lisp-implementation-version) "2.33.83"
:end1 (min (length (lisp-implementation-version)) 7))
(ext:without-package-lock ("COMMON-LISP")
(let ((oldload (function cl:load)))
(fmakunbound 'cl:load)
(defun cl:load (filespec &key (verbose *load-verbose*)
(print *load-print*)
(if-does-not-exist t)
(external-format :default))
(handler-case (funcall oldload filespec :verbose verbose
:print print :if-does-not-exist if-does-not-exist
:external-format external-format)
(system::simple-parse-error
()
(funcall oldload (translate-logical-pathname filespec)
:verbose verbose
:print print :if-does-not-exist if-does-not-exist
:external-format external-format)))))))
(defparameter *default-version*
#+clisp nil
#+sbcl nil
#-(or clisp sbcl) (progn (warn "What default version to use in ~A?"
(lisp-implementation-type))
:newest))
(defparameter *project-directory*
(truename
(merge-pathnames
(make-pathname :directory '(:relative))
(make-pathname :name nil :type nil :version nil
:defaults *load-truename*) *default-version*))
"The directory of this project.")
(defun make-translations (host logical-dir physical-dir)
(mapcar
(lambda (item)
(destructuring-bind (logical-tail physical-tail) item
(list (apply (function make-pathname)
:host host
:directory `(:absolute ,@logical-dir :wild-inferiors)
logical-tail)
(format nil "~A**/~A" physical-dir physical-tail))))
#+clisp
'(((:name :wild :type :wild :version nil) "*.*")
((:name :wild :type nil :version nil) "*"))
#+sbcl
'(((:name :wild :type :wild :version :wild) "*.*"))
#-(or clisp sbcl)
'(((:name :wild :type nil :version nil) "*")
((:name :wild :type :wild :version nil) "*.*")
((:name :wild :type :wild :version :wild) "*.*"))))
(setf (logical-pathname-translations "PACKAGES") nil
(logical-pathname-translations "PACKAGES")
(append
(make-translations "PACKAGES" '("COM" "INFORMATIMAGO" "CLEXT")
*project-directory*)
;; clext packages dont depend on com.informatimago.common-lisp (yet)
;; but compile.lisp uses com.informatimago.common-lisp.make-depends.make-depends
(make-translations "PACKAGES" '() (get-directory :share-lisp "packages/"))))
(handler-case (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE")
(t () (load "PACKAGES:COM;INFORMATIMAGO;COMMON-LISP;PACKAGE.LISP")))
(import 'package:define-package)
;;;; init.lisp -- -- ;;;;
| 5,620 | Common Lisp | .lisp | 123 | 38.219512 | 87 | 0.579879 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d6039513c56b071d0a05abc87bbf04614405cf486369db7054c040a4a54df61a | 4,894 | [
-1
] |
4,895 | telnet-repl.lisp | informatimago_lisp/clext/telnet/telnet-repl.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: telnet-repl.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Implements a Telnet REPL server.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.REPL")
;;;
;;; The REPL:
;;;
;; TODO: Securize the *readtable* and the *package* (cf. something like ibcl)
(defun make-repl-readtable (cn)
(declare (ignore cn))
(copy-readtable))
(defun make-repl-package (cn)
(mkupack :name (format nil "USER-~D" cn)
:use '("COMMON-LISP")))
(defun telnet-repl (stream cn must-stop-it)
(let* ((*terminal-io* stream)
(*debug-io* (make-synonym-stream '*terminal-io*))
(*query-io* (make-synonym-stream '*terminal-io*))
(*standard-input* (stream-input-stream stream))
(*standard-output* (stream-output-stream stream))
(*trace-output* (stream-output-stream stream))
(*error-output* (stream-output-stream stream))
(package (make-repl-package cn))
(*readtable* (make-repl-readtable cn))
(*package* package)
(*debugger-hook* nil) ; disable swank-debugger-hook.
(com.informatimago.common-lisp.interactive.interactive::*repl-history*
(make-array 128 :adjustable t :fill-pointer 0)))
(catch 'repl
(unwind-protect
(with-interrupt-handler
(let ((+eof+ (gensym))
(hist 1))
(set-macro-character #\! (function repl-history-reader-macro) t)
(loop
(with-resume-restart ("Resume REPL")
(when (funcall must-stop-it)
(format *terminal-io* "~&Server is shutting down.~%")
(finish-output *terminal-io*)
(throw 'repl nil))
(handler-case
(progn
(format *terminal-io* "~%~A[~D]> " (package-name *package*) hist)
(finish-output *terminal-io*)
(com.informatimago.common-lisp.interactive.interactive::%rep +eof+ hist))
(error (err)
(format stream "~%Fatal Error: ~A~%" err)
(finish-output stream)
(throw 'repl nil)))))))
(close *terminal-io*)
(delete-package package)))))
;;;
;;; Client
;;;
(defclass repl-client ()
((name :initarg :name :reader name)
(thread :initarg :thread :reader repl-client-thread
:initform nil)
(number :initarg :number :reader repl-client-number)
(socket :initarg :socket :reader repl-client-socket)
(banner-function :initarg :banner-function :reader banner-function)
(login-function :initarg :login-function :reader login-function)
(repl-function :initarg :repl-function :reader repl-function)
(stop-closure :initarg :stop-closure :reader stop-closure)
(terminate-closure :initarg :terminate-closure :reader terminate-closure)
(stream :initarg :stream :reader repl-client-stream)))
(defvar *stream* nil)
(defun run-client-loop (client)
(with-telnet-on-stream (stream (socket-stream (repl-client-socket client))
client)
(setf *stream* stream)
(setf (slot-value client 'stream) stream)
(setf (telnet-stream-thread stream) (bt:current-thread))
(format *log-output* "~&client ~D telnet on stream ~S~%" (repl-client-number client) stream)
(print (list :not-stop (not (stop-closure client))
:banner (banner-function client)
:login (login-function client))
*log-output*)
(terpri *log-output*)
(when (and (not (funcall (stop-closure client)))
(banner-function client))
(funcall (banner-function client) stream (repl-client-number client) (name client)))
(when (and (not (funcall (stop-closure client)))
(or (null (login-function client))
(funcall (login-function client) stream)))
(funcall (repl-function client) stream (repl-client-number client) (stop-closure client))
(format *log-output* "~&client ~D repl-function returned~%" (repl-client-number client)))))
(defmethod initialize-instance :after ((client repl-client) &key &allow-other-keys)
(setf (slot-value client 'thread)
(make-thread (lambda ()
(unwind-protect (run-client-loop client)
(funcall (terminate-closure client) client)))
:name (name client))))
;;;
;;; Server
;;;
;;; The server listens on one TCP port (one or multiple interfaces).
;;; When receiving a connection it creates a new client thread to handle it.
;;; Once max-clients are active, it waits for clients to stop before
;;; handling a new client connection.
(defclass repl-server ()
((name :initarg :name :reader name)
(thread :initarg :thread :reader repl-server-thread
:initform nil)
(lock :initform nil :reader repl-server-lock)
(more-clients :initform nil :reader for-more-clients)
(stop-closure :initform nil :reader must-stop-p)
(banner-function :initarg :banner-function :reader banner-function)
(login-function :initarg :login-function :reader login-function)
(repl-function :initarg :repl-function :reader repl-function)
(port :initarg :port :reader repl-server-port)
(interface :initarg :interface :reader repl-server-interface)
(max-clients :initarg :max-clients :reader repl-server-max-clients)
(clients :initform '())))
(defmethod %clean-up ((server repl-server))
(loop :for slot :in '(thread lock more-clients stop-closure)
:do (setf (slot-value server slot) nil)))
(defmethod %add-client ((server repl-server) new-client)
(push new-client (slot-value server 'clients)))
(defmethod remove-client ((server repl-server) old-client)
(with-lock-held ((repl-server-lock server))
(socket-close (repl-client-socket old-client))
(setf (slot-value server 'clients)
(delete old-client (slot-value server 'clients)))
(condition-notify (for-more-clients server))))
(defmethod wait-for-free-client-slot ((server repl-server))
(with-lock-held ((repl-server-lock server))
(loop :while (and (< (repl-server-max-clients server)
(length (slot-value server 'clients)))
(not (funcall (must-stop-p server))))
:do (condition-wait (for-more-clients server)
(repl-server-lock server)
:timeout 1 #| check for stop |#))))
(deftype octet () '(unsigned-byte 8))
(defun run-server-loop (server)
(with-socket-listener (server-socket (repl-server-interface server)
(repl-server-port server)
:element-type 'octet)
(loop
:for cn :from 1
:for client-socket := (socket-accept server-socket
:element-type 'octet)
:when client-socket
:do (format *log-output* "~&connection from ~S~%" client-socket)
:do (with-lock-held ((repl-server-lock server))
(let ((client (make-instance
'repl-client
:name (format nil "~A Client #~D"
(name server) cn)
:number cn
:socket client-socket
:banner-function (banner-function server)
:login-function (login-function server)
:repl-function (repl-function server)
:stop-closure (lambda () (funcall (must-stop-p server)))
:terminate-closure (lambda (client) (remove-client server client)))))
(%add-client server client)))
:do (wait-for-free-client-slot server)
:until (funcall (must-stop-p server))
:finally (loop
:while (slot-value server 'clients)
:do (wait-for-free-client-slot server))
(return cn))))
(defmethod initialize-instance :after ((server repl-server) &key &allow-other-keys)
(let ((stop nil))
(setf (slot-value server 'stop-closure)
(lambda (&optional stop-it)
(when stop-it
(setf stop t))
stop)
(slot-value server 'lock)
(make-lock (format nil "~A Server Lock" (name server)))
(slot-value server 'more-clients)
(make-condition-variable :name (format nil "~A Server More Clients" (name server)))
(slot-value server 'thread)
(make-thread (lambda () (run-server-loop server))
:name (format nil "~A Server" (name server))))))
(defvar *password* (format nil "~(~36r~)" (random (expt 36 8))))
(defun valid-password-p (user password)
(and (string= user "guest")
(string= password *password*)))
(defun simple-login (stream)
(format stream "~&User: ")
(finish-output stream)
(clear-input stream)
(let ((user (read-line stream)))
(unwind-protect
(progn
(setf (stream-echo-mode stream) nil)
(format stream "~&Password: ")
(finish-output stream)
(clear-input stream)
(let ((password (read-line stream)))
(if (valid-password-p user password)
(progn
(format stream "~&Welcome~%")
(force-output stream)
t)
(progn
(format stream "~&Invalid account~%")
(force-output stream)
nil))))
(setf (stream-echo-mode stream) t))))
(defun start-repl-server (&key (name "Telnet REPL")
(port 10023) (interface "0.0.0.0")
(max-clients 10)
(banner-function nil)
(login-function (function simple-login))
(repl-function (function telnet-repl)))
"Starts a Telnet REPL server thread, listening for incoming
connections on the specified PORT, and on the specified INTERFACE.
At most MAX-CLIENTS at a time are allowed connected.
The clients will start running the BANNER-FUNCTION which takes a
stream, a client number and a client name.
Then the LOGIN-FUNCTION is called with a stream. It should return true
to allow the connection to go on.
If the LOGIN-FUNCTION returns true, then the REPL-FUNCTION is called
with the stream, the client number, and a stop closure that should be
called periodically to know when the REPL should be stopped.
RETURN: The server instance. Several servers may be run on different
ports (with possibly different functions).
"
(make-instance 'repl-server
:name name
:banner-function banner-function
:login-function login-function
:repl-function repl-function
:port port
:interface interface
:max-clients max-clients))
(defun stop-repl-server (server)
"Stops the REPL server. It make take some time top shut down all
the REPL clients, but the REPL server should not accept new
connections right away."
(when (repl-server-thread server)
(funcall (must-stop-p server) t)
(%clean-up server))
nil)
;;;; THE END ;;;;
| 12,978 | Common Lisp | .lisp | 269 | 38.542751 | 99 | 0.577011 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bd9cfe0b91614c92ad538a80aa450a14f97300c966ad8a77c9bc8b7e133e0532 | 4,895 | [
-1
] |
4,896 | bt-patch.lisp | informatimago_lisp/clext/telnet/bt-patch.lisp |
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *names* (make-hash-table :weak :key :test 'eq))
(defun make-condition-variable (&key name)
(let ((semaphore (ccl:make-semaphore)))
(setf (gethash semaphore *names*) name)
semaphore))
(defmethod print-object :around ((semaphore ccl:semaphore) stream)
(let ((name (gethash semaphore *names*)))
(if name
(print-unreadable-object (semaphore stream :identity t :type t)
(format stream ":NAME ~S" name))
(call-next-method))))
(defvar *status* (make-hash-table :weak :key :test 'eq))
(defun caller () (third (ccl:backtrace-as-list)))
(defmacro with-lock-held ((place) &body body)
(let ((vlock (gensym)))
`(let ((,vlock ,place))
(ccl:with-lock-grabbed (,vlock)
(push (list :locking (caller) (bt:current-thread)) (gethash ,vlock *status* '()))
(unwind-protect
(progn ,@body)
(pop (gethash ,vlock *status* '())))))))
(defmethod print-object :around ((lock ccl::recursive-lock) stream)
(let ((status (gethash lock *status*)))
(if status
(print-unreadable-object (lock stream :identity t :type t)
(format stream "~S :status ~S" (ccl:lock-name lock) status))
(call-next-method))))
#-(and)
(ignore
bt:make-condition-variable
(com.informatimago.common-lisp.cesarum.utility:hash-table-entries *names*)
(map nil 'print (com.informatimago.common-lisp.cesarum.utility:hash-table-entries *status*))
#|
(#<recursive-lock "down-layer" [ptr @ #x605080] #x3020028D45FD>)
(#<recursive-lock "Telnet REPL Server Lock" [ptr @ #x10D880] #x30200279729D>)
(#<recursive-lock "telnet-stream" :status ((:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) #x3020028D74BD>
(:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) nil
|#
)
#|
# -*- mode:org -*-
* Debugging a dead-lock in a program using =bordeaux-threads= in =ccl=.
We have a program with three threads:
#+BEGIN_EXAMPLE
cl-user> (list-threads)
1) #<process Telnet REPL Client #1 DOWN LAYER(22) [semaphore wait] #x302002A4903D>
2) #<process Telnet REPL Client #1(21) [semaphore wait] #x302002A469FD>
3) #<process Telnet REPL Server(20) [Active] #x30200291EB5D>
4) …
#+END_EXAMPLE
The server thread listens to connections and forks client threads for
accepted connections.
The client thread forks a down layer thread that loops reading bytes
from the client socket, and forwarding them up the protocol layers, up
to a buffer in a =TELNET-STREAM= Gray stream.
The client thread then goes on into a REPL loop using the
=TELNET-STREAM= Gray stream as =*TERMINAL-IO*=. Writing back to
=*TERMINAL-IO*= goes down to the client socket in this client thread.
Unfortunately, when sending a byte to the upper layer, the down layer
thread hangs waiting for the stream-lock. Who has locked this stream?
Neither =ccl= nor =bordeaux-threads= are very helpful in debugging that…
What we'd want, is to know what thread are holding a lock. So we will
implement a macro shadowing =BT:WITH-LOCK-HELD=, to record that
information into a weak hash-table. Happily, =ccl= has native weak
hash-tables so we don't have to use
=com.informatimago.clext.closer-weak=.
#+BEGIN_CODE lisp
#+(and ccl debug-condition-variables)
(defpackage "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
(:use "COMMON-LISP" "BORDEAUX-THREADS")
(:shadow "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:documentation "Implements MAKE-CONDITION-VARIABLE on ccl to print the name,
and WITH-LOCK-HELD to record the locking thread."))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
(:use "COMMON-LISP" "BORDEAUX-THREADS" …)
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "TELNET-STREAM" …))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.REPL"
(:use "COMMON-LISP" "BORDEAUX-THREADS" …)
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "START-REPL-SERVER" …))
#+END_CODE
#+BEGIN_CODE lisp
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *status* (make-hash-table :weak :key :test 'eq))
(defun caller () (third (ccl:backtrace-as-list)))
(defmacro with-lock-held ((place) &body body)
(let ((vlock (gensym)))
`(let ((,vlock ,place))
(ccl:with-lock-grabbed (,vlock)
(push (list :locking (caller) (bt:current-thread)) (gethash ,vlock *status* '()))
(unwind-protect
(progn ,@body)
(pop (gethash ,vlock *status* '())))))))
(defmethod print-object :around ((lock ccl::recursive-lock) stream)
(let ((status (gethash lock *status*)))
(if status
(print-unreadable-object (lock stream :identity t :type t)
(format stream "~S :status ~S" (ccl:lock-name lock) status))
(call-next-method))))
#+END_CODE
#+BEGIN_EXAMPLE
(map nil 'print (com.informatimago.common-lisp.cesarum.utility:hash-table-entries *status*))
(#<recursive-lock "down-layer" [ptr @ #x605080] #x3020028D45FD>)
(#<recursive-lock "Telnet REPL Server Lock" [ptr @ #x10D880] #x30200279729D>)
(#<recursive-lock "telnet-stream" :status ((:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) #x3020028D74BD>
(:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) nil
#+END_EXAMPLE
ccl condition-variables are not named;
bordeaux-threads ignores the name parameter.
So we shadow make-condition-variable and record the name
of the condition variables in a
#+BEGIN_CODE lisp
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *names* (make-hash-table :weak :key :test 'eq))
(defun make-condition-variable (&key name)
(let ((semaphore (ccl:make-semaphore)))
(setf (gethash semaphore *names*) name)
semaphore))
(defmethod print-object :around ((semaphore ccl:semaphore) stream)
(let ((name (gethash semaphore *names*)))
(if name
(print-unreadable-object (semaphore stream :identity t :type t)
(format stream ":NAME ~S" name))
(call-next-method))))
#+END_CODE
|#
| 8,193 | Common Lisp | .lisp | 153 | 47.568627 | 236 | 0.687375 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d49f58ce6464ee86e9327a159d9ba5942677256db6969b6d8ec4da3f2a65ea7d | 4,896 | [
-1
] |
4,897 | bt-ccl-debug.lisp | informatimago_lisp/clext/telnet/bt-ccl-debug.lisp |
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *names* (make-hash-table :weak :key :test 'eq))
(defun make-condition-variable (&key name)
(let ((semaphore (ccl:make-semaphore)))
(setf (gethash semaphore *names*) name)
semaphore))
(defmethod print-object :around ((semaphore ccl:semaphore) stream)
(let ((name (gethash semaphore *names*)))
(if name
(print-unreadable-object (semaphore stream :identity t :type t)
(format stream ":NAME ~S" name))
(call-next-method))))
(defvar *status* (make-hash-table :weak :key :test 'eq))
(defun caller () (third (ccl:backtrace-as-list)))
(defmacro with-lock-held ((place) &body body)
(let ((vlock (gensym)))
`(let ((,vlock ,place))
(ccl:with-lock-grabbed (,vlock)
(push (list :locking (caller) (bt:current-thread)) (gethash ,vlock *status* '()))
(unwind-protect
(progn ,@body)
(pop (gethash ,vlock *status* '())))))))
(defmethod print-object :around ((lock ccl::recursive-lock) stream)
(let ((status (gethash lock *status*)))
(if status
(print-unreadable-object (lock stream :identity t :type t)
(format stream "~S :status ~S" (ccl:lock-name lock) status))
(call-next-method))))
#-(and)
(ignore
bt:make-condition-variable
(com.informatimago.common-lisp.cesarum.utility:hash-table-entries *names*)
(map nil 'print (com.informatimago.common-lisp.cesarum.utility:hash-table-entries *status*))
(#<recursive-lock "down-layer" [ptr @ #x605080] #x3020028D45FD>)
(#<recursive-lock "Telnet REPL Server Lock" [ptr @ #x10D880] #x30200279729D>)
(#<recursive-lock "telnet-stream" :status ((:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) #x3020028D74BD>
(:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) nil
)
#|
# -*- mode:org -*-
* Debugging a dead-lock in a program using =bordeaux-threads= in =ccl=.
We have a program with three threads:
#+BEGIN_EXAMPLE
cl-user> (list-threads)
1) #<process Telnet REPL Client #1 DOWN LAYER(22) [semaphore wait] #x302002A4903D>
2) #<process Telnet REPL Client #1(21) [semaphore wait] #x302002A469FD>
3) #<process Telnet REPL Server(20) [Active] #x30200291EB5D>
4) …
#+END_EXAMPLE
The server thread listens to connections and forks client threads for
accepted connections.
The client thread forks a down layer thread that loops reading bytes
from the client socket, and forwarding them up the protocol layers, up
to a buffer in a =TELNET-STREAM= Gray stream.
The client thread then goes on into a REPL loop using the
=TELNET-STREAM= Gray stream as =*TERMINAL-IO*=. Writing back to
=*TERMINAL-IO*= goes down to the client socket in this client thread.
Unfortunately, when sending a byte to the upper layer, the down layer
thread hangs waiting for the stream-lock. Who has locked this stream?
Neither =ccl= nor =bordeaux-threads= are very helpful in debugging that…
** Recording the thread and function that holds an lock
What we'd want, is to know what thread are holding a lock. So we will
implement a macro shadowing =BT:WITH-LOCK-HELD=, to record that
information into a weak hash-table. Happily, =ccl= has native weak
hash-tables so we don't have to use
=com.informatimago.clext.closer-weak=.
#+BEGIN_CODE lisp
#+(and ccl debug-condition-variables)
(defpackage "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
(:use "COMMON-LISP" "BORDEAUX-THREADS")
(:shadow "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:documentation "Implements MAKE-CONDITION-VARIABLE on ccl to print the name,
and WITH-LOCK-HELD to record the locking thread."))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
(:use "COMMON-LISP" "BORDEAUX-THREADS" …)
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "TELNET-STREAM" …))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.REPL"
(:use "COMMON-LISP" "BORDEAUX-THREADS" …)
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "START-REPL-SERVER" …))
#+END_CODE
In addition to recording the current thread, we also get the name of
the caller function from =ccl:backtrace-as-list=.
We use a =PRINT-OBJECT :AROUND= method to print the locking threads
when it's available
#+BEGIN_CODE lisp
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *status* (make-hash-table :weak :key :test 'eq))
(defun caller () (third (ccl:backtrace-as-list)))
(defmacro with-lock-held ((place) &body body)
(let ((vlock (gensym)))
`(let ((,vlock ,place))
(ccl:with-lock-grabbed (,vlock)
(push (list :locking (caller) (bt:current-thread)) (gethash ,vlock *status* '()))
(unwind-protect
(progn ,@body)
(pop (gethash ,vlock *status* '())))))))
(defmethod print-object :around ((lock ccl::recursive-lock) stream)
(let ((status (gethash lock *status*)))
(if status
(print-unreadable-object (lock stream :identity t :type t)
(format stream "~S :status ~S" (ccl:lock-name lock) status))
(call-next-method))))
#+END_CODE
Then when the dead-lock occurs, we can have a look at the status of
the various locks, and notice immediately our culprit stream lock that
is held by not once but TWICE by the same thread! =ccl= only has
recursive locks, and =bt:with-lock-held= uses the native locking
mechanism, which is a recursive lock. But now, it is clear what
functions are involved in this double locking and the solution will be
obvious: split =input-buffer-fetch-octet= into an inner function that
assumes the lock is already held, and use this in %stream-read-char.
Problem solved.
#+BEGIN_EXAMPLE
(map nil 'print (com.informatimago.common-lisp.cesarum.utility:hash-table-entries *status*))
(#<recursive-lock "down-layer" [ptr @ #x605080] #x3020028D45FD>)
(#<recursive-lock "Telnet REPL Server Lock" [ptr @ #x10D880] #x30200279729D>)
(#<recursive-lock "telnet-stream" :status ((:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) #x3020028D74BD>
(:locking
(funcall "#<STANDARD-METHOD COM.INFORMATIMAGO.CLEXT.TELNET.STREAM::INPUT-BUFFER-FETCH-OCTET (COM.INFORMATIMAGO.CLEXT.TELNET.STREAM:TELNET-STREAM T)>" "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)
(:locking
(com.informatimago.clext.telnet.stream::%stream-read-char "#<TELNET-STREAM #x3020028D75CD>" "NIL")
#<process Telnet REPL Client #1(21) [semaphore wait] #x3020028D192D>)) nil
#+END_EXAMPLE
** Naming Condition Variables
In addition, =ccl= condition-variables are not named;
=bordeaux-threads= ignores the name parameter. So we shadow
=make-condition-variable= and record the name of the condition
variables in a weak hash-table, and add a =print-object :around=
method to print this name when available. This is very convenient
when *inspecting* threads, to see on what condition variable they're
actually waiting.
#+BEGIN_CODE lisp
(in-package "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH")
(defvar *names* (make-hash-table :weak :key :test 'eq))
(defun make-condition-variable (&key name)
(let ((semaphore (ccl:make-semaphore)))
(setf (gethash semaphore *names*) name)
semaphore))
(defmethod print-object :around ((semaphore ccl:semaphore) stream)
(let ((name (gethash semaphore *names*)))
(if name
(print-unreadable-object (semaphore stream :identity t :type t)
(format stream ":NAME ~S" name))
(call-next-method))))
#+END_CODE
| 9,604 | Common Lisp | .lisp | 168 | 49.595238 | 236 | 0.675056 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | cc4b5b0bcf6a0b5bb5fcd3e0ef7c241f873bbaf9689f54ea1a5f66c5815c5ef7 | 4,897 | [
-1
] |
4,898 | interrupt-test.lisp | informatimago_lisp/clext/telnet/interrupt-test.lisp | (define-condition interrupt-condition (condition)
((source :initarg :source
:initform nil
:reader interrupt-condition-source))
(:report (lambda (condition stream)
(format stream "Interrupted~@[ from ~A~]"
(interrupt-condition-source condition)))))
(defvar *debug-on-interrupt* nil)
(defun interrupt-handler (condition)
(format t "~S ~A ~%~S = ~A~%"
'interrupt-handler condition
'*debug-on-interrupt* *debug-on-interrupt*)
(force-output)
(if *debug-on-interrupt*
(break "~@[~:(~A~) ~]Interrupt"
(interrupt-condition-source condition))
(invoke-restart (find-restart 'resume condition))))
(defmacro with-interrupt-handler (&body body)
`(handler-bind ((interrupt-condition
(function interrupt-handler)))
(macrolet ((with-resume-restart (&body body)
`(with-simple-restart (resume "Resume")
,@body)))
,@body)))
(defun caller ()
#+ccl (third (ccl:backtrace-as-list))
#-ccl nil)
(defun signal-interrupt (thread &optional source)
(let ((source (or source (caller))))
(bt:interrupt-thread thread (function signal)
(make-condition 'interrupt-condition
:source source))))
(defun test/interrupt (&optional debug-on-interrupt)
;; we must set the global variable for the benefit of the running thread.
(setf *debug-on-interrupt* debug-on-interrupt)
(let* ((iota (bt:make-thread (lambda ()
(unwind-protect
(with-interrupt-handler
(loop
:for i :from 1
:do (with-resume-restart
(sleep 1)
(princ i) (princ " ")
(finish-output))))
(princ "Iota Done") (terpri)
(finish-output)))
:initial-bindings (list (cons '*standard-output* *standard-output*))
:name "iota runner")))
(sleep 10)
(signal-interrupt iota "keyboard")
(princ "Interrupter Complete.") (terpri) (force-output)
(unless *debug-on-interrupt*
(sleep 5)
(bt:destroy-thread iota)
(princ "Killed iota runner.") (terpri) (force-output))))
;; #-(and)
;; (map nil 'print
;; (sort (map 'list
;; (lambda (name)
;; (let ((ce (babel::get-character-encoding name)))
;; (list (babel::enc-name ce)
;; (babel::enc-max-units-per-char ce))))
;; (babel::list-character-encodings)) (function <) :key (function second)))
| 2,892 | Common Lisp | .lisp | 63 | 32.52381 | 99 | 0.513657 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 86cbe49fb0c2f3b34db73d0e2c41e80d1778a0bdec58f90df802403c3211295f | 4,898 | [
-1
] |
4,899 | interrupt.lisp | informatimago_lisp/clext/telnet/interrupt.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: interrupt.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Manage thread interruption.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-24 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.INTERRUPT"
(:use "COMMON-LISP"
"BORDEAUX-THREADS")
(:export "INTERRUPT-CONDITION"
"INTERRUPT-CONDITION-SOURCE"
"*DEBUG-ON-INTERRUPT*"
"WITH-INTERRUPT-HANDLER"
"WITH-RESUME-RESTART"
"SIGNAL-INTERRUPT"))
(in-package "COM.INFORMATIMAGO.CLEXT.INTERRUPT")
(define-condition interrupt-condition (condition)
((source :initarg :source
:initform nil
:reader interrupt-condition-source)
(action :initarg :action
:initform :resume
:reader interrupt-condition-action))
(:report (lambda (condition stream)
(format stream "Interrupted~@[ from ~A~]"
(interrupt-condition-source condition)))))
(defvar *debug-on-interrupt* nil
"Whether all interruptions should invoke the debugger
\(instead of invoking the RESUME restart).")
(defun interrupt-handler (condition)
;; (format t "~S ~A ~%~S = ~A~%"
;; 'interrupt-handler condition
;; '*debug-on-interrupt* *debug-on-interrupt*)
;; (force-output)
(if (or *debug-on-interrupt*
(eql :debug (interrupt-condition-action condition)))
(break "~@[~:(~A~) ~]Interrupt"
(interrupt-condition-source condition))
(invoke-restart (find-restart 'resume condition))))
(defmacro with-interrupt-handler (&body body)
"Evaluates body in an environment where a handler for the INTERRUPT-CONDITION is set,
to call the INTERRUPT-HANDLER function,
and where a WITH-RESUME-RESTART macro is bound to set up a RESUME restart."
`(handler-bind ((interrupt-condition
(function interrupt-handler)))
(macrolet ((with-resume-restart ((&optional (format-control "Resume")
&rest format-arguments)
&body body)
`(with-simple-restart (resume ,format-control ,@format-arguments)
,@body)))
,@body)))
(declaim (notinline caller))
(defun caller ()
"Return the name of the function that called the caller of caller."
#+ccl (third (ccl:backtrace-as-list))
#-ccl nil)
(defun signal-interrupt (thread &key (action :resume) source)
"Interrupt the thread with an INTERRUPT-CONDITION initialized with the ACTION and SOURCE.
If ACTION is :RESUME and *DEBUG-ON-INTERRUPT* is false,
the INTERRUPT-HANDLER will invoke the RESUME restart.
If ACTION is :DEBUG or *DEBUG-ON-INTERRUPT* is true,
the INTERRUPT-HANDLER will invoke the debugger
thru a call to BREAK."
(check-type action (member :resume :debug))
(let ((source (or source (caller))))
(bt:interrupt-thread thread (function signal)
(make-condition 'interrupt-condition
:action action
:source source))))
;;;; THE END ;;;;
| 4,261 | Common Lisp | .lisp | 97 | 37.608247 | 91 | 0.614293 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7b24c2f6d0b9616f8989c28235dbd62339ae0540a7fc22ced75231882b565820 | 4,899 | [
-1
] |
4,900 | telnet-stream.lisp | informatimago_lisp/clext/telnet/telnet-stream.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: telnet-stream.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Wraps a socket stream running the telnet protocol in a pair of
;;;; bivalent gray-streams.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-14 <PJB> Created
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM")
(declaim (declaration stepper))
(defvar *log-output* *trace-output*)
;; We cannot use *trace-output* while debugging the telnet-repl, since
;; it's dynamically bound to the telnet-stream for the user.
(defun format-log (control-string &rest arguments)
(format *log-output* "~?" control-string arguments)
(finish-output *log-output*))
#|
# -*- mode:org -*-
** Telnet Controls
These controls may be received from the telnet layer into the
up:GSTREAM. The telnet-stream must process them.
| Controls | I/O | Description |
|-------------------+------------+--------------------------------------------------|
| are-you-there | output | should send an answer |
| | | at the REPL we could send the prompt |
| | | when reading, could issue a message or a prompt? |
| | | when processing, could issue a message about the |
| | | current function (short backtrace?) |
| | | |
| abort-output | output | clear output buffer (send-buffer, output buffer) |
| | | |
| interrupt-process | interrupt | enter the debugger, or resume REPL |
| | | |
| go-ahead | output | for half-duplex, resume sending. |
| | | |
| erase-line | input | erase the input buffer |
| | | |
| erase-character | input | erase the previous character in the input buffer |
| | | |
| break | interrupt? | enter the debugger, or resume REPL |
| | | at the REPL prompt, break could reissue |
| | | the prompt without entering the debugger. |
| | | |
| end-of-record | input | EOF? |
Note: the input buffer may contain multiple lines. ERASE-LINE erase
back up to the previous newline, but cannot erase the previous line.
ERASE-CHARACTER cannot erase a newline in the buffer either.
** Telnet Options
We may set those options:
| transmit-binary | output | depending on the encoding US-ASCII or non-US-ASCII. |
| echo | input | echo the character received. |
| suppress-go-ahead | I/O | half-duplex ; enable this option to go full-duplex. |
| end-of-record | output | we may ask this option to send eor on flush. |
| end-of-record | input | ignore it? |
| echo | suppress-go-ahead | meaning |
|----------+-------------------+------------------|
| enabled | enabled | character mode |
| enabled | disabled | kludge line mode |
| disabled | enabled | kludge line mode |
| disabled | disabled | |
Note: The line mode option (RFC 1116, RFC 1184) is not implemented yet.
(defparameter *default-classes* '((:transmit-binary . option)
(:echo . option)
(:suppress-go-ahead . option)
(:end-of-record . option)
;; (:timing-mark . option)
(:status . status))
;; NOTE: when the class is OPTION, it means the option has no
;; specific behavior besides being enabled or disabled (but
;; the NVT may alter its behavior according to the setting of
;; the option).
"An a-list of (option-name . class-name).")
** Threads
The client needs two threads:
- a client input loop thread that waits and read the bytes from the
socket. as soon as some are received, they're transmitted to the
NVT, and queued into the Input Buffer of the gray stream.
- a client repl thread reads the data from the Input Buffer, and
evaluates it. Eventually, it may write some data to the thread.
Some buffering (if asked) may occur until it's flushed
(finish-output) or (terpri). The data is sent down to the NVT. The
NVT sends the data to the down-sender, which calls write-sequence on
the socket. Since this may block, it will set send-wait-p to false
first, so that if send down needs to be called from the other
thread, data will be queued instead in the send-buffer.
SEND-WAIT-P is never set (yet). It may be used for half-duplex and/or
flow control options (RFC 1372).
The DISPATCH-MESSAGE method calls (SEND down bytes) to send responses
and other control messages, in addition to data messages.
Therefore the serialization must be implemented in the NVT-DOWN-SENDER.
*** Gray Streams
Gray Streams don't specify anything about threading and mutex on the
stream operations.
For example, ccl has a :sharing option on streams, but only for
BASIC-STREAMS, not for Gray Streams. I/O function fork to Gray Stream
messages without doing any locking.
So Gray Streams must implement their own mutexing.
** Encodings
When using US-ASCII, we can use SEND-TEXT, but when using any other
encoding, we need to negociate binary and an encoding, and use
SEND-BINARY. The user will select the stream-external-format encoding
himself, so we don't need to negociate it (but we could once RFC 2066
is implemented, at least for the initial external-format).
** Buffering
Note: both for the input buffer and the output buffer, we will use
octet vectors both for binary and text modes. The encoding/decoding
of the text is therefore always performed by the telnet-stream itself.
The Telnet NVT has been modified to allow either the transmission of
vector of ascii code octets or strings for the text mode API. We use
only the vector of ascii codes. The let us avoid copying buffers as
much as possible.
Note: we may ask for the EOR option, and send an EOR when flushing
(automatic or explicit).
We may offer buffering options on the telnet-stream (up:GSTREAM):
| Setting | Description |
|--------------------------------------------------------+-----------------------------------------------------------------|
| (stream-output-buffering stream) | the current output-buffering: :CHARACTER :LINE or buffer-size |
| | |
| (setf (stream-output-buffering stream) nil) | no Output Buffer we send directly to the NVT |
| (setf (stream-output-buffering stream) :character) | and (send down bytes); |
| | we still may have to buffer when (send-wait-p nvt) |
| | |
| (setf (stream-output-buffering stream) :line) | We write into the Output Buffer until a newline. |
| | Then we automatically flush when a newline is written |
| | |
| (setf (stream-output-buffering stream) buffer-size) | We write into the Output Buffer up to a buffer-size full |
| | and then flush automatically when we the buffer is full. |
| | We need to call flush-output explicitely. |
|--------------------------------------------------------+-----------------------------------------------------------------|
| (stream-input-buffering stream) | the current input-buffering: :CHARACTER or :LINE |
| | |
| (setf (stream-input-buffering stream) nil) | Data is still stored in the Input Buffer, but is available |
| (setf (stream-input-buffering stream) :character) | (LISTEN stream) and can be READ/READ-CHAR/READ-SEQUENCE |
| | as soon as received. |
| | |
| (setf (stream-input-buffering stream) :line) | Data is stored in the Input Buffer, but is available |
| | only when a newline (or EOR) is received. |
| | -> the only difference really is for LISTEN and READ-SEQUENCE |
|--------------------------------------------------------+-----------------------------------------------------------------|
| (stream-echo stream) | he current echo mode: T or NIL |
| (setf (stream-echo stream) t) | Sets the telnet option. Default behavior. |
| (setf (stream-echo stream) nil) | Sets the telnet option. We could set this to read passwords. |
|--------------------------------------------------------+-----------------------------------------------------------------|
| (stream-external-format stream) | the current external-format. :default is us-ascii |
| | Note: we use the native external-format values. |
| | |
| (setf (stream-external-format stream) encoding) | sets the external-format. |
| | This also set the binary mode <=> the encoding is not us-ascii. |
|--------------------------------------------------------+-----------------------------------------------------------------|
| (stream-element-type stream) | the current element-type of the stream |
| | |
| (setf (stream-element-type stream) 'character) | set the text mode stream-external-format is used. |
| | |
| (setf (stream-element-type stream) '(unsigned-byte n)) | set the binary mode, and decode unsigned-byte to octets. |
| | This could be useful to transfer and process binary data. |
|--------------------------------------------------------+-----------------------------------------------------------------|
** TODOs
*** TODO We need to check thread safety of the NVT and the TELNET-STREAM.
#+BEGIN_CODE
-*- mode:text;mode:picture -*-
+------------+
| REPL |
+------------+
^ |
| (write stream)
(listen stream) |
| |
(read stream) |
client repl thread | |
..........................................|.... |
client input loop thread | . |
| . v
+------------------+ +------------+ +-------------------+
| Input Buffer |<---------| up:GSTREAM |---->| Output Buffer |
+------------------+ +------------+ +-------------------+
^ . |
| . |
| . |
| . |
| . |
+---------------+ . (send-binary nvt bytes)
| NVT-UP-SENDER | . |
+---------------+ . (send-text nvt text)
^ . |
| . (send-control nvt control)
| . |
(receive-binary up bytes) . |
| . |
(reveive-text up text) . |
| . |
(reveive-control up control) . |
| . |
(want-option-p up option-name). |
(receive-option up option value). |
| . |
| . |
| . v
+--------------------------+
options --------------->| NETWORK-VIRTUAL-TERMINAL |
+--------------------------+ (send-wait-p nvt)/
| ^ . |---------------> (send-buffer nvt)
| | . (send down bytes)
| | . |
| | . |
v | . v
+------------+ | . +-----------------+
| OPTION-MGR |* | . | NVT-DOWN-SENDER |
+------------+ | . +-----------------+
| . | | client repl thread
(receive nvt bytes) . |mutex->| until buffer is empty.
| . | | +----------------------+
| . v | | |
+--------------+ +---->buffer |
| down:GSTREAM | | |
client input loop thread +--------------+ | |
+-----------+ ^ . | v |
| | | . (write-sequence buffer socket) |
| v | . | | |
| (read-sequence buffer socket) .....|.......... | |
| | | v . +----------------------+
+-----------+ +---------------+ .
| socket-stream | .
+---------------+ .
.
#+END_CODE
|#
;; -*- mode:lisp -*-
;;;
;;; Telnet Streams
;;;
(defgeneric start-down-thread (layer))
(defun call-with-telnet-on-stream (low-stream client function)
(let* ((stream (make-instance 'telnet-stream
:element-type 'character))
(down (make-instance 'down-layer
:stream low-stream
:client client))
(nvt (make-instance 'network-virtual-terminal
:name "TELNET SERVER"
:client nil ; we're server.
:up-sender stream
:down-sender down)))
(setf (slot-value stream 'nvt) nvt
(slot-value down 'nvt) nvt)
(start-down-thread down)
(funcall function stream)))
(defmacro with-telnet-on-stream ((stream-var stream-expr client) &body body)
"Connects a telnet network-virtual-terminal to the remote stream
resulting from the STREAM-EXPR, and evaluates the BODY in a lexical
context where the STREAM-VAR is bound to a local bidirectional stream
conected to the NVt."
`(call-with-telnet-on-stream ,stream-expr ,client (lambda (,stream-var) ,@body)))
(deftype octet () `(unsigned-byte 8))
(defun make-binary-buffer (size)
(make-array size :element-type 'octet :adjustable t :fill-pointer 0))
(defun make-string-buffer (size)
;; base-char is enough for :us-ascii
(make-array size :element-type 'base-char :adjustable t :fill-pointer 0))
(defun buffer-append (buffer sequence start end)
(let* ((old-size (length buffer))
(new-size (+ old-size (- end start))))
(loop
:while (< (array-dimension buffer 0) new-size)
:do (setf buffer (adjust-array buffer
(* 2 (array-dimension buffer 0))
:element-type (array-element-type buffer)
:fill-pointer (fill-pointer buffer))))
(setf (fill-pointer buffer) new-size)
(replace buffer sequence :start1 old-size :start2 start :end2 end)
buffer))
;;
;; down:GSTREAM, NVT-DOWN-SENDER
;;
(defconstant +down-layer-buffer-size+ 1024)
(defclass down-layer ()
((nvt :reader nvt :initarg :nvt)
(stream :reader down-stream :initarg :stream)
(client :reader client :initarg :client)
(lock :reader down-lock)
(writingp :accessor %writingp :initform nil)
(down-buffer :reader down-buffer :initform (make-binary-buffer +down-layer-buffer-size+))
(thread :reader down-thread :initform nil)))
(defgeneric input-loop (down-layer))
(defgeneric stop-closure (client)) ;; TODO must be imported from telnet.repl
(defmethod initialize-instance :after ((layer down-layer) &key &allow-other-keys)
(setf (slot-value layer 'lock) (make-lock "down-layer")))
(defmethod start-down-thread ((layer down-layer))
(setf (slot-value layer 'thread)
(make-thread (lambda () (input-loop layer))
:name (format nil "~A DOWN LAYER" (name (client layer))))))
(defmethod input-loop ((self down-layer))
;; The input-loop runs in the client input loop thread
(loop
:with stream := (down-stream self)
:with buffer := (make-binary-buffer +down-layer-buffer-size+)
:until (funcall (stop-closure (client self)))
:initially (setf (fill-pointer buffer) 1)
:do (handler-case (setf (aref buffer 0) (read-byte stream))
(end-of-file ()
(receive (nvt self) :end-of-file)
(return-from input-loop)))
(format-log "~&down-layer received from remote: ~S~%"
buffer)
(force-output *log-output*)
(receive (nvt self) buffer)
(format-log "~&down-layer: nvt received: ~S~%"
buffer)
(force-output *log-output*)))
(defmethod send ((self down-layer) bytes &key (start 0) end)
;; The send method is called in the client repl thread
;; Down interface (to down):
;; Send the bytes to the remote NVT.
;; BYTE: a VECTOR of (UNSIGNED-BYTE 8).
(let ((buffer (down-buffer self))
(stream (down-stream self)))
(with-lock-held ((down-lock self))
(if (%writingp self)
(progn
(format-log "~&down-layer buffers to remote: ~S~%"
(subseq bytes start end))
(buffer-append buffer bytes start end)
(return-from send))
(setf (%writingp self) t)))
(format-log "~&down-layer sends to remote: ~S~%"
(subseq bytes start end))
(write-sequence bytes stream :start start :end end)
(force-output stream)
;; Either we write sequence with lock held, or we need a
;; double-buffering to be able to write a buffer while we append
;; to the other. The double-buffer would be better in case of
;; symetrical writers, But it is expected that one writer will
;; send bigger data and more often than the other.
;; So this should do better:
(with-lock-held ((down-lock self))
(when (plusp (length buffer))
(format-log "~&down-layer sends buffer: ~S~%"
buffer)
(write-sequence buffer stream)
(setf (fill-pointer buffer) 0))
(setf (%writingp self) nil))))
;;
;; up:GSTREAM, NVT-UP-SENDER
;;
(defgeneric stream-output-buffering (stream)) ; *
(defgeneric stream-input-buffering (stream)) ; *
(defgeneric stream-echo-mode (stream)) ; *
(defgeneric stream-external-format (stream)) ; *
(defgeneric stream-element-type (stream)) ; *
(defgeneric (setf stream-output-buffering) (new-buffering stream))
(defgeneric (setf stream-input-buffering) (new-buffering stream))
(defgeneric (setf stream-echo-mode) (new-echo stream))
(defgeneric (setf stream-external-format) (new-external-format stream))
(defgeneric (setf stream-element-type) (new-element-type stream))
(defclass telnet-stream (fundamental-character-input-stream
fundamental-character-output-stream
fundamental-binary-input-stream
fundamental-binary-output-stream)
((element-type :reader stream-element-type :initform 'character
:initarg :element-type)
(external-format :reader stream-external-format :initform :us-ascii)
(input-buffering :reader stream-input-buffering :initform :character)
(output-buffering :reader stream-output-buffering :initform :line)
(echo-mode :reader stream-echo-mode :initform t)
(nvt :reader nvt
:initarg :nvt)
(thread :accessor telnet-stream-thread
:initarg :thread
:initform nil
:documentation "The target thread for SIGNAL-INTERRUPT (INTERRUPT-PROCESS and BREAK telnet controls).")
(open :reader open-stream-p :initform t)
(lock :reader stream-lock)
(input-data-present :reader for-input-data-present
:documentation "A condition variable indicating that the input-buffer is not empty.")
(input-free-space :reader for-input-free-space
:documentation "A condition variable indicating that the input-buffer has more free space.")
(input-buffer :reader input-buffer)
(output-buffer :reader output-buffer)
(column :accessor column :initform 0)
(partial-character-octets :reader partial-character-octets :initform (make-binary-buffer 4))
(unread-character :accessor unread-character :initform nil)
(peeked-character :accessor peeked-character :initform nil)))
;; input-buffer is a vector of octet
;; listen peeks for a character
;; unread-char puts back a character
;; Depending on the encoding, a character may require several octets.
;; Therefore we use a small byte buffer and a character buffer in telnet-stream.
#|
# -*- mode:org -*-
The input characters are stored in a virtual buffer composed of the
following slots:
| unread-character | nil, or the character that has been unread-char'ed, until read |
| peeked-character | nil, or the character that has been peek-char'ed, until read |
| partial-character-octets | the octets read so far from input buffer that don't make a character |
| input-buffer | the octets received so far |
When reading characters, we take first the unread-character, next the
peeked-character, then we complete the partial-character-octets, then
we may decode them from the input-buffer.
| unread-character | peeked-character | read-char, peek-char |
|------------------+------------------+----------------------|
| t | t | unread-character |
| t | nil | unread-character |
| nil | t | peeked-character |
| nil | nil | go to partial |
# |#
;; -*- mode:lisp -*-
(defmethod print-object ((stream telnet-stream) output)
(declare (stepper disable))
(print-unreadable-object (stream output :type t :identity t)
(format output "(~@{~<~% ~1:;~S ~S~>~^ ~})"
:open (open-stream-p stream)
:element-type (stream-element-type stream)
:external-format (stream-external-format stream)
:input-buffering (stream-input-buffering stream)
:output-buffering (stream-output-buffering stream)
:echo-mode (stream-echo-mode stream)
:length-input-buffer (%input-buffer-length (input-buffer stream))
:length-output-buffer (length (output-buffer stream))))
stream)
(defconstant +input-buffer-size+ 4096)
(defconstant +output-buffer-size+ 4096)
(defmethod initialize-instance :after ((stream telnet-stream) &key &allow-other-keys)
(setf (slot-value stream 'lock) (make-lock "telnet-stream")
(slot-value stream 'input-data-present) (make-condition-variable :name "input-data-present")
(slot-value stream 'input-free-space) (make-condition-variable :name "input-free-space")
(slot-value stream 'input-buffer) (make-input-buffer (stream-input-buffering stream))
(slot-value stream 'output-buffer) (make-binary-buffer +output-buffer-size+)))
(defmethod (setf stream-output-buffering) (new-buffering (stream telnet-stream))
(let ((new-buffering (or new-buffering :character)))
(check-type new-buffering (member :character :line))
(setf (slot-value stream 'output-buffering) new-buffering)))
(defmethod (setf stream-input-buffering) (new-buffering (stream telnet-stream))
(let ((new-buffering (or new-buffering :character))
(buffer (slot-value stream 'input-buffer)))
(check-type new-buffering (or (integer 1) (member :character :line)))
(with-lock-held ((stream-lock stream))
(setf (slot-value stream 'input-buffering) new-buffering)
(when (integerp new-buffering)
;; TODO: check if the new buffer size is enough for the buffer content, and keep the old buffered input.
(adjust-array (input-buffer-data buffer)
new-buffering :fill-pointer new-buffering)
(setf (input-buffer-head buffer) 0
(input-buffer-tail buffer) 0)))
new-buffering))
(defmethod (setf stream-echo-mode) (new-echo (stream telnet-stream))
(check-type new-echo boolean)
(setf (slot-value stream 'echo-mode) new-echo)
(setf (option-enabled-p (nvt stream) :echo :us) t)
new-echo)
(defun type-equal-p (a b)
(and (subtypep a b) (subtypep b a)))
(defmethod configure-mode ((stream telnet-stream))
(setf (option-enabled-p (nvt stream) :transmit-binary :us)
(not (and (eq (stream-external-format stream) :us-ascii)
(type-equal-p (stream-element-type stream) 'character)))))
(defmethod (setf stream-external-format) (new-external-format (stream telnet-stream))
(let* ((cs (typecase new-external-format
((member :default) (find-character-set :us-ascii))
((or string symbol) (find-character-set new-external-format))
(t ;; Assume implementation dependent external-format
(character-set-for-lisp-encoding new-external-format))))
(le (first (cs-lisp-encoding cs))))
(unless le
(error "Invalid external-format ~S, got character-set ~S and no lisp-encoding."
new-external-format cs))
(with-lock-held ((stream-lock stream))
(let* ((old-external-format (stream-external-format stream))
(new-external-format (intern le "KEYWORD"))
(change (or (and (eq :us-ascii old-external-format)
(not (eq :us-ascii new-external-format)))
(and (not (eq :us-ascii old-external-format))
(eq :us-ascii new-external-format)))))
;; TODO: negociate with remote for a new encoding.
;; TODO: check element-type first:
(setf (slot-value stream 'external-format) new-external-format)
(when change
;; before configure-mode:
(flush-output-buffer stream)))
(configure-mode stream))
new-external-format))
(defmethod (setf stream-element-type) (new-element-type (stream telnet-stream))
;; TODO: negociate with remote for a text or binary.
(with-lock-held ((stream-lock stream))
(setf (slot-value stream 'element-type)
(cond
((or (type-equal-p new-element-type 'character)
(type-equal-p new-element-type 'base-char))
'character)
((type-equal-p new-element-type '(unsigned-byte 8))
'(unsigned-byte 8))
(t (error "Unsupported element-type ~S" new-element-type))))
(configure-mode stream))
new-element-type)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
;;; stream methods
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-condition simple-stream-error (stream-error simple-error)
())
(defun check-stream-open (stream where)
(unless (open-stream-p stream)
(error 'simple-stream-error
:stream stream
:format-control "~S cannot deal with closed stream ~S"
:format-arguments (list where stream))))
(defun check-sequence-arguments (direction stream sequence start end)
(assert (<= 0 start end (length sequence))
(sequence start end)
"START = ~D or END = ~D are not sequence bounding indexes for a ~S of length ~D"
start end (type-of sequence) (length sequence))
(ecase direction
(:read
(assert (or (listp sequence)
(and (vectorp sequence)
(subtypep (stream-element-type stream) (array-element-type sequence))))
(sequence)
"For reading, the sequence element type ~S should be a supertype of the stream element type ~S"
(array-element-type sequence) (stream-element-type stream)))
(:write
(assert (or (listp sequence)
(and (vectorp sequence)
(subtypep (array-element-type sequence) (stream-element-type stream))))
(sequence)
"For writing, the sequence element type ~S should be a subtype of the stream element type ~S"
(array-element-type sequence) (stream-element-type stream)))))
;;;
;;; Input
;;;
(defstruct (input-buffer
(:constructor %make-input-buffer))
data
(head 0)
(tail 0))
(defmethod print-object ((buffer input-buffer) stream)
(print-unreadable-object (buffer stream :identity t :type t)
(format stream ":LENGTH ~A :CONTENTS ~S"
(%input-buffer-length buffer)
(if (<= (input-buffer-head buffer)
(input-buffer-tail buffer))
(subseq (input-buffer-data buffer)
(input-buffer-head buffer)
(input-buffer-tail buffer))
(concatenate '(vector octet)
(subseq (input-buffer-data buffer)
(input-buffer-tail buffer))
(subseq (input-buffer-data buffer)
0
(input-buffer-head buffer)))))))
(defun make-input-buffer (buffering)
(let* ((size (if (integerp buffering)
buffering
+input-buffer-size+))
(buffer (make-binary-buffer size)))
(setf (fill-pointer buffer) size)
(%make-input-buffer :data buffer)))
(defun %input-buffer-free-space (buffer)
(let ((size (length (input-buffer-data buffer))))
(- size 1 (mod (- (input-buffer-tail buffer)
(input-buffer-head buffer))
size))))
(declaim (inline %input-buffer-free-space))
(defun %input-buffer-length (buffer)
(let ((size (length (input-buffer-data buffer))))
(mod (- (input-buffer-tail buffer)
(input-buffer-head buffer))
size)))
(declaim (inline %input-buffer-length))
(defun %input-buffer-ranges (buffer len)
"Return the ranges of free bytes in the buffer s1 e1 s2 e2 and the new tail position if len bytes are added."
(let* ((size (length (input-buffer-data buffer)))
(tail (input-buffer-tail buffer))
(max1 (- size tail)))
(if (<= len max1)
(values tail (+ tail len) nil nil (+ tail len))
(values tail (+ tail max1) 0 (- len max1) (mod (+ tail len) size)))))
(declaim (inline %input-buffer-ranges))
(defun %wait-for-input-free-space (stream required)
(loop
:while (< (%input-buffer-free-space (input-buffer stream)) required)
:do (condition-wait (for-input-free-space stream) (stream-lock stream))))
(declaim (inline %wait-for-input-free-space))
(defun %wait-for-input-data-present (stream required)
(loop
:while (< (%input-buffer-length (input-buffer stream)) required)
:do (condition-wait (for-input-data-present stream) (stream-lock stream))))
(declaim (inline %wait-for-input-data-present))
(defun %%input-buffer-fetch-octet (stream)
(%wait-for-input-data-present stream 1)
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer))
(head (input-buffer-head buffer))
(octet (aref data head)))
(setf (input-buffer-head buffer) (mod (+ head 1) (length data)))
(condition-notify (for-input-free-space stream))
octet))
(defmethod %input-buffer-fetch-octet ((stream telnet-stream) nohang)
;; Assume (stream-lock stream) is already held.
;; then read the octet and convert it to character
;; else (%wait-for-input-data-present)
(if (and nohang (zerop (%input-buffer-length (input-buffer stream))))
nil
(%%input-buffer-fetch-octet stream)))
(defmethod input-buffer-fetch-octet ((stream telnet-stream) nohang)
;; then read the octet and convert it to character
;; else (%wait-for-input-data-present)
(if (and nohang (zerop (%input-buffer-length (input-buffer stream))))
nil
(with-lock-held ((stream-lock stream))
(%%input-buffer-fetch-octet stream))))
(defmethod input-buffer-append-octet ((stream telnet-stream) octet)
(with-lock-held ((stream-lock stream))
(%wait-for-input-free-space stream 1)
;; copy one octet
(let ((buffer (input-buffer stream)))
(multiple-value-bind (s1 e1 s2 e2 nt) (%input-buffer-ranges buffer 1)
(declare (ignore e1 s2 e2))
(setf (aref (input-buffer-data buffer) s1) octet)
(setf (input-buffer-tail buffer) nt)))
(condition-notify (for-input-data-present stream))))
(defmethod input-buffer-append-text ((stream telnet-stream) text)
(let* ((end (length text))
(len (+ end (count #\newline text))))
(when (plusp len)
(with-lock-held ((stream-lock stream))
(%wait-for-input-free-space stream len)
;; copy the text octets.
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer)))
(multiple-value-bind (s1 e1 s2 e2 nt) (%input-buffer-ranges buffer len)
(let ((start2 (nth-value 1 (replace-ascii-bytes data text :newline :crlf :start1 s1 :end1 e1 :start2 0 :end2 end))))
(when s2
(replace-ascii-bytes data text :newline :crlf :start1 s2 :end1 e2 :start2 start2 :end2 end)))
(setf (input-buffer-tail buffer) nt))))
(condition-notify (for-input-data-present stream)))))
(defmethod input-buffer-append-octets ((stream telnet-stream) octets start end)
(let* ((end (or end (length octets)))
(len (- end start)))
(when (plusp len)
(with-lock-held ((stream-lock stream))
(%wait-for-input-free-space stream len)
;; copy the binary octets.
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer)))
(multiple-value-bind (s1 e1 s2 e2 nt) (%input-buffer-ranges buffer len)
(replace data octets :start1 s1 :end1 e1 :start2 start :end2 (+ start (- e1 s1)))
(when s2
(replace data octets :start1 s2 :end1 e2 :start2 (+ start (- e1 s1)) :end2 end))
(setf (input-buffer-tail buffer) nt))))
(condition-notify (for-input-data-present stream)))))
(defmethod input-buffer-erase-character ((stream telnet-stream))
(with-lock-held ((stream-lock stream))
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer))
(tail (input-buffer-tail buffer)))
(when (plusp (%input-buffer-length buffer))
(let ((last (mod (- tail 1) (length data))))
(unless (or (= (aref data last) lf)
(= (aref data last) cr))
(setf (input-buffer-tail buffer) last)
(condition-notify (for-input-free-space stream))))))))
(defmethod input-buffer-erase-line ((stream telnet-stream))
(with-lock-held ((stream-lock stream))
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer))
(head (input-buffer-head buffer))
(tail (input-buffer-tail buffer))
(size (length data)))
(when (plusp (%input-buffer-length buffer))
(loop
:with last := (mod (- tail 1) size)
:while (and (/= (aref data last) lf)
(/= (aref data last) cr))
:do (setf last (mod (- last 1) size))
:until (= last head)
:finally (setf (input-buffer-tail buffer) last)
(condition-notify (for-input-free-space stream)))))))
(defmethod input-buffer-peek-octet ((stream telnet-stream))
(with-lock-held ((stream-lock stream))
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer))
(head (input-buffer-head buffer)))
(when (plusp (%input-buffer-length buffer))
(aref data head)))))
(defmethod input-buffer-read-octet ((stream telnet-stream))
(with-lock-held ((stream-lock stream))
(%wait-for-input-data-present stream 1)
(let* ((buffer (input-buffer stream))
(data (input-buffer-data buffer))
(head (input-buffer-head buffer))
(size (length data)))
(prog1 (aref data head)
(setf (input-buffer-head buffer) (mod (1+ head) size))))))
;; (defmethod input-buffer-read-octets ((stream telnet-stream) octets &key (start 0) end)
;; (with-lock-held ((stream-lock stream))
;; (let ((len (- (or end (length octets)) start)))
;; (if (< (length (input-buffer-data))))
;; (%wait-for-input-data-present stream len)
;; (let* ((buffer (input-buffer stream))
;; (data (input-buffer-data buffer))
;; (head (input-buffer-head buffer))
;; (size (length data)))
;; (prog1 (aref data head)
;; (setf (input-buffer-data buffer) (mod (+ data 1) size)))))))
;; Up interface (to up):
(defmethod want-option-p ((up-sender telnet-stream) option-code)
(declare (ignore option-code))
;; Asks the upper layer whether the option is wanted.
;; OPTION-NAME: a keyword denoting the option.
(warn "~S not implemented yet" 'want-option-p))
(defmethod receive-option ((up-sender telnet-stream) option value)
;; Receive a result from an option request.
;; OPTION: the option instance.
;; VALUE: a value the option sends back.
(declare (ignore option value))
(warn "~S not implemented yet" 'receive-option))
(defmethod receive-binary ((up-sender telnet-stream) bytes &key (start 0) end)
;; Receive some binary text.
;; BYTE: a VECTOR of (UNSIGNED-BYTE 8).
;; START, END: bounding index designators of sequence.
;; The defaults are for START 0 and for END nil.
(format-log "~&up-layer receive binary: ~S~%" (subseq bytes start end))
(input-buffer-append-octets up-sender bytes start (or end (length bytes))))
(defmethod receive-text ((up-sender telnet-stream) (text string) &key (start 0) end)
;; Receive some ASCII text
;; TEXT: a string containing only printable ASCII characters and #\newline.
(assert (zerop start))
(assert (null end))
(format-log "~&up-layer receive text: ~S~%" (subseq text start end))
(input-buffer-append-text up-sender text))
(defmethod receive-text ((up-sender telnet-stream) (text vector) &key (start 0) end)
;; Receive some ASCII text
;; TEXT: a string containing only printable ASCII characters and #\newline.
(format-log "~&up-layer receive text: ~S~%" (subseq text start end))
(input-buffer-append-octets up-sender text start end))
(defmethod receive-control ((up-sender telnet-stream) control)
;; Receive a function code.
;; CONTROL: (member :are-you-there :abort-output :interrupt-process :go-ahead
;; :erase-line :erase-character
;; :break :cr :ff :vt :lf :ht :bs :bel :nul
;; :end-of-record).
(format-log "~&up-layer receive control: ~S~%" control)
(case control
;; | Controls | I/O | Description |
;; |-------------------+------------+--------------------------------------------------|
;; | are-you-there | output | should send an answer |
;; | | | at the REPL we could send the prompt |
;; | | | when reading, could issue a message or a prompt? |
;; | | | when processing, could issue a message about the |
;; | | | current function (short backtrace?) |
;; | | | |
;; | abort-output | output | clear output buffer (send-buffer, output buffer) |
;; | | | |
;; | interrupt-process | interrupt | enter the debugger, or resume REPL |
;; | | | |
;; | go-ahead | output | for half-duplex, resume sending. |
;; | | | |
;; | erase-line | input | erase the input buffer |
;; | | | |
;; | erase-character | input | erase the previous character in the input buffer |
;; | | | |
;; | break | interrupt? | enter the debugger, or resume REPL |
;; | | | at the REPL prompt, break could reissue |
;; | | | the prompt without entering the debugger. |
;; | | | |
;; | end-of-record | input | EOF? |
;;
;; Note: the input buffer may contain multiple lines. ERASE-LINE erase
;; back up to the previous newline, but cannot erase the previous line.
;; ERASE-CHARACTER cannot erase a newline in the buffer either.
(:are-you-there
;; if output-buffer contains something,
;; then flush it
;; else send a nul or a message?
(finish-output up-sender)
(format up-sender "~&I am here.~%")
(force-output up-sender))
(:abort-output
;; clear-output-buffer
)
(:interrupt-process
;; signal keyboard-interrupt in the repl thread
(when (telnet-stream-thread up-sender)
(signal-interrupt (telnet-stream-thread up-sender)
:action :resume
:source "keyword interrupt-process")))
(:break
;; signal keyboard-interrupt in the repl thread
(when (telnet-stream-thread up-sender)
(signal-interrupt (telnet-stream-thread up-sender)
:action :debug
:source "keyword break")))
(:go-ahead
;; we don't do half-duplex.
;; flush-output
)
(:erase-line
;; find last line in input-buffer and erase it
(input-buffer-erase-line up-sender))
(:erase-character
;; find last (non-newline) character in input-buffer and erase it
(input-buffer-erase-character up-sender))
(:end-of-record
;; mark an end-of-file?
)
((:cr :ff :vt :lf :ht :bs :bel :nul)
(input-buffer-append-octet up-sender (case control
(:cr CR)
(:ff FF)
(:vt VT)
(:lf LF)
(:ht HT)
(:bs BS)
(:bel BEL)
(:nul NUL))))
(otherwise
;; log an unknown control
)))
;;; character input
(declaim (inline update-column))
(defun update-column (stream ch)
(when (characterp ch)
(if (char= ch #\newline)
(setf (column stream) 0)
(incf (column stream))))
ch)
(defun %stream-read-char (stream no-hang)
(with-lock-held ((stream-lock stream))
(let ((char nil))
(rotatef char (unread-character stream))
(unless char
(rotatef char (peeked-character stream)))
(update-column
stream
(or char
(let ((encoding (stream-external-format stream)))
(if (= 1 (babel::enc-max-units-per-char
(babel::get-character-encoding
encoding)))
;; 1-octet encoding:
(let ((code (%input-buffer-fetch-octet stream no-hang)))
(when code
(let* ((octets (make-array 1 :element-type '(unsigned-byte 8) :initial-element code))
(char (decode-character octets :encoding encoding)))
(unless char
(error "Decoding error code ~A encoding ~S, no such character code" code encoding))
char)))
;; n-octets encoding:
(loop
:named read
:with partial := (partial-character-octets stream)
:for code := (%input-buffer-fetch-octet stream no-hang)
:while code
:do (vector-push-extend code partial (length partial))
(multiple-value-bind (char validp size)
(decode-character partial :encoding encoding)
(when (and validp (<= size (length partial)))
(if char
(progn
(replace partial partial :start2 size)
(setf (fill-pointer partial) (- (length partial) size))
(return-from read char))
(error "Decoding error code ~A encoding ~S, no such character code" partial encoding))))
:finally (return-from read nil)))))))))
(defmethod stream-read-char ((stream telnet-stream))
(check-stream-open stream 'stream-read-char)
(%stream-read-char stream nil))
(defmethod stream-read-char-no-hang ((stream telnet-stream))
(check-stream-open stream 'stream-read-char-no-hang)
(%stream-read-char stream t))
(defmethod stream-peek-char ((stream telnet-stream))
(check-stream-open stream 'stream-peek-char)
(with-lock-held ((stream-lock stream))
(or (unread-character stream)
(peeked-character stream)
(setf (peeked-character stream) (stream-read-char stream)))))
(defmethod stream-read-line ((stream telnet-stream))
(check-stream-open stream 'stream-read-line)
(let ((line (make-array 80 :element-type 'character :fill-pointer 0)))
(flet ((append-char (ch)
(when (char= ch #\newline)
(setf (column stream) 0)
(return-from stream-read-line (values line nil #|TODO: EOF is always NIL?|#)))
(vector-push-extend ch line (length line))))
(with-lock-held ((stream-lock stream))
(let ((char nil))
(rotatef char (unread-character stream))
(append-char (unread-character stream)))
(let ((char nil))
(rotatef char (peeked-character stream))
(append-char (peeked-character stream)))
(loop
(append-char (stream-read-char stream)))))))
(defmethod stream-listen ((stream telnet-stream))
(check-stream-open stream 'stream-listen)
(with-lock-held ((stream-lock stream))
(or (unread-character stream)
(peeked-character stream)
(setf (peeked-character stream) (stream-read-char-no-hang stream)))))
(defmethod stream-unread-char ((stream telnet-stream) char)
(check-stream-open stream 'stream-unread-char)
(with-lock-held ((stream-lock stream))
(when (unread-character stream)
(error "Two unread-char"))
(setf (unread-character stream) char)
(setf (column stream) (max 0 (1- (column stream)))))
char)
;; binary input
(defmethod stream-read-byte ((stream telnet-stream))
(check-stream-open stream 'stream-read-byte)
(with-lock-held ((stream-lock stream))
(error "~S Not Implemented Yet" 'stream-read-byte)))
;;; Sequence Input
(defmethod stream-read-sequence ((stream telnet-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-read-sequence)
(check-sequence-arguments :read stream sequence start end)
(with-lock-held ((stream-lock stream))
(error "~S Not Implemented Yet" 'stream-read-sequence)))
;;;
;;; Output
;;;
;; ;; Up interface (from up):
;;
;; (defgeneric send-binary (nvt bytes)
;; (:documentation "Send the binary text.
;; NVT: a NETWORK-VIRTUAL-TERMINAL instance.
;; BYTE: a VECTOR of (UNSIGNED-BYTE 8)."))
;;
;; (defgeneric send-text (nvt text)
;; (:documentation "Send the ASCII text.
;; NVT: a NETWORK-VIRTUAL-TERMINAL instance.
;; TEXT: a string containing only printable ASCII characters and #\newline."))
;;
;; (defgeneric send-control (nvt control)
;; (:documentation "Send a function control code.
;; NVT: a NETWORK-VIRTUAL-TERMINAL instance.
;; CONTROL: (member :synch :are-you-there :abort-output :interrupt-process :go-ahead
;; :erase-line :erase-character
;; :break :cr :ff :vt :lf :ht :bs :bel :nul
;; :end-of-record)."))
(defmethod send-binary :before (nvt bytes)
(declare (ignorable nvt))
(format-log "~&up-layer sends binary: ~S~%" bytes))
(defmethod send-text :before (nvt bytes)
(declare (ignorable nvt))
(format-log "~&up-layer sends text: ~S~%" bytes))
(defmethod send-control :before (nvt bytes)
(declare (ignorable nvt))
(format-log "~&up-layer sends control: ~S~%" bytes))
;;; character output
(defun flush-output-buffer (stream)
(let ((buffer (output-buffer stream)))
(when (plusp (length buffer))
(if (eq :us-ascii (stream-external-format stream))
(send-text (nvt stream) buffer)
(send-binary (nvt stream) buffer))
(setf (fill-pointer buffer) 0))))
(defmethod stream-write-char ((stream telnet-stream) char)
(check-stream-open stream 'stream-write-char)
(unless (char= #\newline char)
(let ((code (char-code char)))
(when (or (<= 0 code 31) (<= 127 code))
(stream-write-string stream (format nil "^~C" (code-char (mod (+ code 64) 128))))
(return-from stream-write-char))))
(with-lock-held ((stream-lock stream)) ;; <<<<<<<<< WE'RE SAFE !
(let ((encoding (stream-external-format stream))
(buffering (stream-output-buffering stream)))
(case buffering
(:character ; no buffering
(cond
((char= #\newline char)
(flush-output-buffer stream)
(send-control (nvt stream) :cr)
(send-control (nvt stream) :lf))
((eq encoding :us-ascii)
(vector-push (ascii-code char) (output-buffer stream))
(flush-output-buffer stream))
(t
(encode-string-to-output-buffer stream (string char))
(flush-output-buffer stream))))
(:line ; line buffering
(cond
((char= #\newline char) ; if newline, flush the buffer now.
;; flush only on newline
(flush-output-buffer stream)
;; TODO: check whether sending CR LF is equivalent to send-control :cr :lf
;; TODO: can we buffer the :cr :lf control with the line? Is it done in the NVT?
(send-control (nvt stream) :cr)
(send-control (nvt stream) :lf))
((eq encoding :us-ascii)
(let ((buffer (output-buffer stream)))
(vector-push-extend (ascii-code char) buffer (length buffer))))
(t
(encode-string-to-output-buffer stream (string char)))))
(otherwise
(assert (integerp buffering))
(cond
((eq encoding :us-ascii)
(let ((buffer (output-buffer stream)))
(if (char= #\newline char)
(progn
;; TODO: check whether sending CR LF is equivalent to send-control :cr :lf
(vector-push-extend CR buffer (length buffer))
(vector-push-extend LF buffer (length buffer)))
(vector-push-extend (ascii-code char) buffer (length buffer)))))
(t
(encode-string-to-output-buffer stream (string char))))
(when (<= buffering (length (output-buffer stream)))
;; flush only on buffer full
(flush-output-buffer stream))))
(if (char= #\newline char)
(setf (column stream) 0)
(incf (column stream)))))
char)
(defmethod stream-terpri ((stream telnet-stream))
(check-stream-open stream 'stream-terpri)
(stream-write-char stream #\newline)
nil)
(defgeneric encode-string-to-output-buffer (stream string &key start end))
(defmethod encode-string-to-output-buffer ((stream telnet-stream) string &key (start 0) end)
(let* ((encoding (stream-external-format stream))
(buffer (output-buffer stream))
(start1 (fill-pointer buffer)))
(setf (fill-pointer buffer) (array-dimension buffer 0))
(loop
(multiple-value-bind (filledp end1)
(replace-octets-by-string buffer string
:start1 start1
:start2 start
:end2 end
:encoding encoding
:use-bom nil
:errorp nil ; use replacement character
:error-on-out-of-space-p nil)
(when filledp
(setf (fill-pointer buffer) end1)
(return-from encode-string-to-output-buffer))
(let ((size (* (ceiling end1 1024) 1024)))
(setf (slot-value stream 'output-buffer)
(setf buffer (adjust-array buffer size :fill-pointer size))))))))
(defmacro for-each-line (((line-var start-var end-var)
(string-expression start-expr end-expr))
line-expression
&body newline-body)
(let ((vstring (gensym))
(vnewlines (gensym))
(process-line (gensym))
(vstart (gensym))
(vend (gensym))
(vsstart (gensym))
(vsend (gensym)))
`(let* ((,vstring ,string-expression)
(,vsstart ,start-expr)
(,vsend ,end-expr)
(,vnewlines (positions #\newline ,vstring :start ,vsstart :end ,vsend)))
(flet ((,process-line (start end)
(let ((,line-var ,vstring)
(,start-var start)
(,end-var end))
,line-expression)))
(loop
:for ,vstart := ,vsstart :then (1+ ,vend)
:for ,vend :in ,vnewlines
:do (progn
(when (< ,vstart ,vend)
(,process-line ,vstart ,vend))
,@newline-body)
:finally (when (< ,vstart (length ,vstring))
(,process-line ,vstart ,vsend)))))))
(defmethod stream-write-string ((stream telnet-stream) string &optional (start 0) end)
(check-stream-open stream 'stream-write-string)
(with-lock-held ((stream-lock stream))
(let ((end (or end (length string))))
;; If we have something in the buffer flush it now.
(flush-output-buffer stream)
(for-each-line ((line lstart lend) (string start end))
(encode-string-to-output-buffer stream line :start lstart :end lend)
(flush-output-buffer stream)
(send-control (nvt stream) :cr)
(send-control (nvt stream) :lf))
(setf (column stream) (fill-pointer (output-buffer stream)))))
string)
(defmethod stream-line-column ((stream telnet-stream))
(column stream))
(defmethod stream-start-line-p ((stream telnet-stream))
(zerop (column stream)))
(defmethod stream-advance-to-column ((stream telnet-stream) column)
(check-stream-open stream 'stream-advance-to-column)
(with-lock-held ((stream-lock stream))
(let ((delta (- column (column stream))))
(when (plusp delta)
(stream-write-string stream (make-string delta :initial-element #\space))
delta))))
(defmethod close ((stream telnet-stream) &key abort)
(declare (ignore abort))
(with-lock-held ((stream-lock stream))
;; TODO: close a telnet-stream
;; (with-lock-held ((lock stream))
;; (setf (slot-value (stream-output-stream stream) 'open) nil))
;; (gate-signal (not-empty stream))
;; (sink-stream (telnet-stream stream))
))
;; binary output
(defmethod stream-write-byte ((stream telnet-stream) byte)
(check-stream-open stream 'stream-write-byte)
(with-lock-held ((stream-lock stream))
;; TODO implement stream-write-byte
(vector-push byte (output-buffer stream)))
byte)
;;; Sequence Output
(defmethod stream-write-sequence ((stream telnet-stream) sequence start end &key &allow-other-keys)
(check-stream-open stream 'stream-write-sequence)
(check-sequence-arguments :write stream sequence start end)
(with-lock-held ((stream-lock stream))
;; TODO implement stream-write-sequence
)
sequence)
(defmethod stream-finish-output ((stream telnet-stream))
;; Attempts to ensure that all output sent to the stream has reached its
;; destination, and only then returns false. Implements
;; cl:finish-output. The default method does nothing.
(with-lock-held ((stream-lock stream))
(flush-output-buffer stream)
;; TODO: how to wait for write-sequence completed?
))
;; We assign the semantics of waiting for the reader process to
;; have read all the data written so far.
;;
;; NO: This could be done with a empty condition, and the writer waiting
;; on the empty condition. The reader would notify it when reaching
;; an empty telnet.
;; This assumes a single writer stream. While waiting for the
;; condition another writer stream could further write data.
;; Therefore we need instead to be able to enqueue tokens into the telnet,
;; that could be used to message back to the exact writing thread.
;;
;; (defmethod stream-finish-output ((stream telnet-stream))
;; (with-lock-held ((lock stream
;; (loop :until (%telnet-emptyp stream)
;; :do (condition-wait (empty stream) (lock stream)))))
;; telnet-warning
;; telnet-error
#|
;; option control:
(defgeneric option-enabled-p (nvt option-name &optional who)
(:documentation "Whether the option is currently enabled,
if WHO is nil, then for either end, otherwise for the indicated end.
OPTION-NAME: a keyword or fixnum denoting the option.
WHO: (member nil :us :him)."))
(defgeneric option-negotiating-p (nvt option-name &optional who)
(:documentation "Whether the option is currently being negotiated,
if WHO is nil, then for either end, otherwise for the indicated end.
OPTION-NAME: a keyword or fixnum denoting the option.
WHO: (member nil :us :him)."))
(defgeneric enable-option (nvt option-name &optional who)
(:documentation "Initiate the negotiation to enable the option.
OPTION-NAME: a keyword or fixnum denoting the option.
WHO: (member nil :us :him)."))
(defgeneric disable-option (nvt option-name &optional who)
(:documentation "Initiate the negotiation to disable the option.
OPTION-NAME: a keyword or fixnum denoting the option.
WHO: (member nil :us :him)."))
(defun (setf option-enabled-p) (flag nvt option-name &optional who)
"Enable or disable the option according to the boolean FLAG.
OPTION-NAME: a keyword or fixnum denoting an option."
(if flag
(enable-option nvt option-name who)
(disable-option nvt option-name who)))
(defgeneric option-register-class (nvt option-name option-class)
(:documentation "Register OPTION-CLASS as the class for a given OPTION-NAME.
NOTE: If the option is already initialized with a different
class, then CHANGE-CLASS is called on the instance.
OPTION-NAME: a keyword or fixnum denoting an option.
OPTION-CLASS: a class designator, should be a subclass of OPTION."))
(defgeneric option-register-default-classes (nvt option-names)
(:documentation "Register the default option-classes for the option given in OPTION-NAMES.
NOTE: If the option is already initialized with a different
class, then CHANGE-CLASS is called on the instance.
OPTION-NAMES: a list of keyword or fixnum denoting options.
RETURN: The subset of OPTION-NAMES (codes are converted into
option-names) for which a specific default class
exists."))
;; Implemented by subclasses of OPTION:
(defgeneric receive-subnegotiation (option nvt bytes &key start end)
(:documentation "Processes the subnegotiation packet (subseq bytes start end)
starting with IAC SB and ending with IAC SE."))
|#
;;;; THE END ;;;;
| 65,484 | Common Lisp | .lisp | 1,213 | 45.540808 | 132 | 0.5399 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 6d9cfa6448661d61068d297dc1502f6269da35a1829e57bae4ade1095b35b9d2 | 4,900 | [
-1
] |
4,901 | babel-extension.lisp | informatimago_lisp/clext/telnet/babel-extension.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: babel-extension.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; A function to test for code sequences.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-14 <PJB> Created
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION")
#|
We would want to know when we have accumulated in a buffer enough bytes to decode a character, depending on the current encodng…
babel doesn't provide a convenient (efficient) API to test that, but I hoped to be able to use OCTETS-TO-STRING for that.
Unfortunately, handling of incomplete code sequences by the different encoding is not consistent.
```
cl-user> (babel:OCTETS-TO-STRING (coerce #(194 182) '(vector (unsigned-byte 8))) :start 0 :end 2 :errorp nil :encoding :utf-8)
"¶"
cl-user> (babel:OCTETS-TO-STRING (coerce #(194 182) '(vector (unsigned-byte 8))) :start 0 :end 1 :errorp nil :encoding :utf-8)
"�"
cl-user> (babel:OCTETS-TO-STRING (coerce #(194 182) '(vector (unsigned-byte 8))) :start 0 :end 2 :errorp nil :encoding :utf-16)
"슶"
cl-user> (babel:OCTETS-TO-STRING (coerce #(194 182) '(vector (unsigned-byte 8))) :start 0 :end 1 :errorp nil :encoding :utf-16)
> Debug: Failed assertion: (= babel-encodings::i babel-encodings::end)
> While executing: (:internal swank::invoke-default-debugger), in process new-repl-thread(1481).
> Type cmd-/ to continue, cmd-. to abort, cmd-\ for a list of available restarts.
> If continued: test the assertion again.
> Type :? for other options.
1 > :q
; Evaluation aborted on #<simple-error #x302006CBABDD>.
cl-user> (babel:octets-to-string (babel:string-to-octets "こんにちは 世界" :encoding :eucjp) :start 0 :end 2 :encoding :eucjp)
"こ"
cl-user> (babel:octets-to-string (babel:string-to-octets "こんにちは 世界" :encoding :eucjp) :start 0 :end 1 :encoding :eucjp)
> Debug: Illegal :eucjp character starting at position 0.
> While executing: (:internal swank::invoke-default-debugger), in process repl-thread(3921).
> Type cmd-. to abort, cmd-\ for a list of available restarts.
> Type :? for other options.
1 > :q
; Evaluation aborted on #<babel-encodings:end-of-input-in-character #x302006CA4EAD>.
cl-user>
```
I would suggest to add a keyword parameter to specify what to do in such a case:
| :on-invalid-code substitution-character | would insert the given substitution-character in place of the code. |
| :on-invalid-code :ignore | would ignore the code and go on. |
| :on-invalid-code :error | would signal a babel-encodings:character-decoding-error condition. |
I would propose also, to provide an efficient function to query the length of a code sequence for the next character:
```
(babel:decode-character bytes &key start end encoding)
--> character ;
sequence-valid-p ;
length
```
- If a character can be decoded, then it is returned as primary value, otherwise NIL.
- If the code sequence is definitely invalid then NIL, else T. Notably if it is just too short, but could be a valid code sequence if completed, T should be returned.
- If the character is decoded and returned, then the length of the decoded code sequence is returned; if sequence-valid-p then a minimal code sequence length with the given prefix is returned; otherwise a minimum code sequence length.
| character | sequence-valid-p | length |
|-----------+------------------+----------------------------------------------------------------|
| ch | T | length of the decoded sequence |
| ch | NIL | --impossible-- |
| NIL | T | minimal length of a valid code sequence with the given prefix. |
| NIL | NIL | minimal length of a valid code sequence. |
For example, in the case NIL T len, if len <= (- end start), then it means the given code sequence is valid, but the decoded code is not the code of a character. eg. ```#(#xED #xA0 #x80)``` is UTF-8 for 55296, but ```(code-char 55296) --> nil```.
```
(babel:decode-character (coerce #(65 32 66) '(vector (unsigned-byte 8)))
:start 0 :end 3 :encoding :utf-8)
--> #\A
T
1
(babel:decode-character (coerce #(195 128 32 80 97 114 105 115) '(vector (unsigned-byte 8)))
:start 0 :end 3 :encoding :utf-8)
--> #\À
T
2
(babel:decode-character (coerce #(195 128 32 80 97 114 105 115) '(vector (unsigned-byte 8)))
:start 0 :end 1 :encoding :utf-8)
--> NIL
T
2
(babel:decode-character (coerce #(195 195 32 80 97 114 105 115) '(vector (unsigned-byte 8)))
:start 0 :end 1 :encoding :utf-8)
--> NIL
T
2
(babel:decode-character (coerce #(195 195 32 80 97 114 105 115) '(vector (unsigned-byte 8)))
:start 0 :end 2 :encoding :utf-8)
--> NIL
NIL
1
(babel:decode-character (coerce #(#xED #xA0 #x80) '(vector (unsigned-byte 8)))
:start 0 :end 3 :encoding :utf-8)
--> NIL
T
3
```
|#
;; (defparameter *replacement-character*
;; (if (<= 65535 char-code-limit) ; does it really mean that the
;; ; implementation uses unicode?
;;
;; (code-char 65533) ; #\Replacement_Character
;;
;; ;; Let's assume ASCII:
;; (code-char 26) ; #\Sub
;; ;; SUB is #x3f in EBCDIC
;; )
;;
;; "A replacement character.")
(defparameter *replacement-character* (code-char 65533)
;; TODO: Is it always the same for all encodings?
"The replacement character used by babel.")
(defun decode-character (octets &key (start 0) end (encoding :utf-8))
;; we'll optimize :us-ascii, :iso-8895-1 and :utf-8 cases.
(let ((end (or end (length octets))))
(case encoding
((:us-ascii :csascii :cp637 :ibm637 :us :iso646-us :ascii :iso-ir-6)
(if (<= end start)
(values nil t 1)
(let ((code (aref octets start)))
(if (<= 0 code 127)
(values (code-char code) t 1)
(values nil nil 1)))))
((:iso-8859-1 :iso_8859-1 :latin1 :l1 :ibm819 :cp819 :csisolatin1)
(if (<= end start)
(values nil t 1)
(let ((code (aref octets start)))
(if (<= 0 code 255)
(values (code-char code) t 1)
(values nil nil 1)))))
((:utf-8)
(if (<= end start)
(values nil t 1)
(let ((byte (aref octets start))
(code 0))
(cond
((<= 0 byte 127) ; 1 byte
(values (code-char byte) t 1))
((<= #b11000000 byte #b11011111) ; 2 bytes
(setf code (ash (ldb (byte 5 0) byte) 6))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 0) code))
(values (code-char code) t 2))
(values nil nil 2)))
(values nil t 2)))
((<= #b11100000 byte #b11101111) ; 3 bytes
(setf code (ash (ldb (byte 4 0) byte) 12))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 6) code))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 0) code))
(values (code-char code) t 3))
(values nil nil 3)))
(values nil t 3)))
(values nil nil 3)))
(values nil t 3)))
((<= #b11110000 byte #b11110111) ; 4 bytes
(setf code (ash (ldb (byte 3 0) byte) 18))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 12) code))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 6) code))
(incf start)
(if (< start end)
(let ((byte (aref octets start)))
(if (<= #b10000000 byte #b10111111)
(progn
(setf code (dpb (ldb (byte 6 0) byte) (byte 6 0) code))
(values (code-char code) t 4))
(values nil nil 4)))
(values nil t 4)))
(values nil nil 4)))
(values nil t 4)))
(values nil nil 4)))
(values nil t 4)))
(t
(values nil nil 1))))))
(otherwise
(handler-case
(octets-to-string octets :start start :end end :errorp nil :encoding encoding)
(:no-error (string)
(if (= 1 (length string))
(if (char= (aref string 0) *replacement-character*)
(values nil t 1) ; ???
(values (aref string 0) t (length (string-to-octets string :encoding encoding))))
(values (aref string 0) t (length (string-to-octets string :end 1 :encoding encoding)))))
(end-of-input-in-character ()
(values nil t 1)) ; ???
(character-out-of-range ()
(values nil t 1)) ; ???
(character-decoding-error ()
(values nil nil 1) #|???|#))))))
(defparameter babel::*string-vector-mappings*
(babel::instantiate-concrete-mappings
;; :optimize ((speed 3) (safety 0) (debug 0) (compilation-speed 0))
:octet-seq-setter babel::ub-set
:octet-seq-getter babel::ub-get
:octet-seq-type (vector (unsigned-byte 8) *)
:code-point-seq-setter babel::string-set
:code-point-seq-getter babel::string-get
:code-point-seq-type babel::unicode-string))
(defun replace-octets-by-string (octets string &key (encoding *default-character-encoding*)
(use-bom :default)
(start1 0) end1 ; for octets
(start2 0) end2 ; for string
(errorp (not babel::*suppress-character-coding-errors*))
(error-on-out-of-space-p t))
(declare (optimize (speed 3) (safety 2)))
(let* ((babel::*suppress-character-coding-errors* (not errorp))
(end1 (or end1 (length octets)))
(end2 (or end2 (length string)))
(mapping (babel::lookup-mapping babel::*string-vector-mappings* encoding))
(bom (babel::bom-vector encoding use-bom))
(bom-length (length bom))
(octet-count (funcall (the function (babel::octet-counter mapping))
string start2 end2 -1)))
(if (< (- end1 start1) (+ bom-length octet-count))
(if error-on-out-of-space-p
(error "Not enough space in destination octets vector; needed ~D bytes, available ~D bytes."
(+ bom-length octet-count)
(- end1 start1))
(values nil (+ start1 bom-length octet-count)))
(progn
(replace octets bom :start1 start1)
(funcall (the function (babel::encoder mapping))
string start2 end2 octets (+ start1 bom-length))
(values octets (+ start1 bom-length octet-count))))))
;;;; THE END ;;;;
| 13,987 | Common Lisp | .lisp | 269 | 40.29368 | 247 | 0.521108 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 50627fca3d408b545b60fd221fc0eff70cf4bc896c27316ff284ac4de9153465 | 4,901 | [
-1
] |
4,902 | test-stub-nvt.lisp | informatimago_lisp/clext/telnet/test-stub-nvt.lisp | (defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.TEST.STUB-NVT"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.TELNET")
(:export "STUB-NVT"))
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.TEST.STUB-NVT")
(defclass stub-nvt ()
((urgent-mode-p :initform nil
:accessor urgent-mode-p
:reader nvt-urgent-mode-p
:documentation "Urgent mode: we've received an urgent notification
and are discarding text bytes till the next IAC DM.")
(ascii-decoder-enabled-p :initform t
:accessor ascii-decoder-enabled-p
:documentation "Whether received text messages are decoded from ASCII.")))
(defmethod initialize-instance :before ((nvt stub-nvt) &key &allow-other-keys))
(defmethod send-binary ((nvt stub-nvt) bytes)
(format *trace-output* "~&~S ~S ~S~%"
'stub-nvt 'send-binary bytes))
(defmethod send-text ((nvt stub-nvt) text)
(format *trace-output* "~&~S ~S ~S~%"
'stub-nvt 'send-text text))
(defmethod send-control ((nvt stub-nvt) control)
(format *trace-output* "~&~S ~S ~S~%"
'stub-nvt 'send-control control))
(defmethod ascii-decoder-enabled-p :before ((nvt stub-nvt))
(format *trace-output* "~&~S ~S -> ~S~%"
'stub-nvt 'ascii-decoder-enabled-p (slot-value nvt 'ascii-decoder-enable-p)))
(defmethod (setf ascii-decoder-enabled-p) :before (flag (nvt stub-nvt))
(format *trace-output* "~&~S ~S ~S~%"
'stub-nvt '(setf ascii-decoder-enabled-p) flag))
(defmethod receive ((nvt stub-nvt) bytes &key start end)
(format *trace-output* "~&~S ~S ~S :start ~S :end ~S~%"
'stub-nvt 'receive bytes start end))
;; ;; option control:
;;
;; (defmethod option-enabled-p ((nvt stub-nvt) option-name &optional who)
;; (:documentation "Whether the option is currently enabled,
;; if WHO is nil, then for either end, otherwise for the indicated end.
;; OPTION-NAME: a keyword or fixnum denoting the option.
;; WHO: (member nil :us :him)."))
;;
;; (defmethod option-negotiating-p ((nvt stub-nvt) option-name &optional who)
;; (:documentation "Whether the option is currently being negotiated,
;; if WHO is nil, then for either end, otherwise for the indicated end.
;; OPTION-NAME: a keyword or fixnum denoting the option.
;; WHO: (member nil :us :him)."))
;;
;; (defmethod enable-option ((nvt stub-nvt) option-name &optional who)
;; (:documentation "Initiate the negotiation to enable the option.
;; OPTION-NAME: a keyword or fixnum denoting the option.
;; WHO: (member nil :us :him)."))
;;
;; (defmethod disable-option ((nvt stub-nvt) option-name &optional who)
;; (:documentation "Initiate the negotiation to disable the option.
;; OPTION-NAME: a keyword or fixnum denoting the option.
;; WHO: (member nil :us :him)."))
;;
;;
;; (defun (setf option-enabled-p) (flag (nvt stub-nvt) option-name &optional who)
;; "Enable or disable the option according to the boolean FLAG.
;; OPTION-NAME: a keyword or fixnum denoting an option."
;; (if flag
;; (enable-option (nvt stub-nvt) option-name who)
;; (disable-option (nvt stub-nvt) option-name who)))
;;
;;
;;
;; (defmethod option-register-class ((nvt stub-nvt) option-name option-class)
;; (:documentation "Register OPTION-CLASS as the class for a given OPTION-NAME.
;; NOTE: If the option is already initialized with a different
;; class, then CHANGE-CLASS is called on the instance.
;; OPTION-NAME: a keyword or fixnum denoting an option.
;; OPTION-CLASS: a class designator, should be a subclass of OPTION."))
;;
;;
;; (defmethod option-register-default-classes ((nvt stub-nvt) option-names)
;; (:documentation "Register the default option-classes for the option given in OPTION-NAMES.
;; NOTE: If the option is already initialized with a different
;; class, then CHANGE-CLASS is called on the instance.
;; OPTION-NAMES: a list of keyword or fixnum denoting options.
;; RETURN: The subset of OPTION-NAMES (codes are converted into
;; option-names) for which a specific default class
;; exists."))
;;
;;
;; ;; Implemented by subclasses of OPTION:
;;
;; (defmethod receive-subnegotiation (option (nvt stub-nvt) bytes &key start end)
;; (:documentation "Processes the subnegotiation packet (subseq bytes start end)
;; starting with IAC SB and ending with IAC SE."))
| 4,445 | Common Lisp | .lisp | 90 | 46.022222 | 102 | 0.674263 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 6d0bb36506819bd6588d42a7e923b52a8e29df8850001f8980f291979c259201 | 4,902 | [
-1
] |
4,903 | babel-extension-test.lisp | informatimago_lisp/clext/telnet/babel-extension-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: babel-extension-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Tests decode-character.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-15 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST")
(:export "TEST/ALL"))
(in-package "COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION.TEST")
(define-test test/decode-character/us-ascii ()
(let ((encoding :us-ascii)
(octets (make-array 10 :element-type '(unsigned-byte 8) :initial-element 32)))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 0 :encoding encoding))
'(nil t 1))
(loop :for code :from 0 :to 127
:do (setf (aref octets 0) code)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 1 :encoding encoding))
(list (code-char code) t 1)
(encoding code octets)))
(loop :for code :from 128 :to 255
:do (setf (aref octets 0) code)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 1 :encoding encoding))
'(nil nil 1)
(encoding code octets)))
(loop :for code :from 0 :to 127
:do (setf (aref octets 0) code)
(setf (aref octets 1) 65)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 2 :encoding encoding))
(list (code-char code) t 1)
(encoding code octets)))
(loop :for code :from 128 :to 255
:do (setf (aref octets 0) code)
(setf (aref octets 1) 65)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 2 :encoding encoding))
'(nil nil 1)
(encoding code octets)))))
(define-test test/decode-character/iso-8859-1 ()
(let ((encoding :iso-8859-1)
(octets (make-array 10 :element-type '(unsigned-byte 8) :initial-element 32)))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 0 :encoding encoding))
'(nil t 1))
(loop :for code :from 0 :to 255
:do (setf (aref octets 0) code)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 1 :encoding encoding))
(list (code-char code) t 1)
(encoding code octets)))
(loop :for code :from 0 :to 255
:do (setf (aref octets 0) code)
(setf (aref octets 1) 65)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 2 :encoding encoding))
(list (code-char code) t 1)
(encoding code octets)))))
(defun utf-8-to-octets (code octets &key (start 0) end)
(assert (<= code char-code-limit) (code)
"Code ~D should be a unicode code point between 0 and ~A"
code char-code-limit)
(cond
((<= code #x7f)
(assert (<= (+ start 1) (or end (length octets))))
(setf (aref octets start) code)
(incf start))
((<= code #x7ff)
(assert (<= (+ start 2) (or end (length octets))))
(setf (aref octets start) (dpb (ldb (byte 5 6) code) (byte 5 0) #b11000000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 0) code) (byte 6 0) #b10000000))
(incf start))
((<= code #xffff)
(assert (<= (+ start 3) (or end (length octets))))
(setf (aref octets start) (dpb (ldb (byte 4 12) code) (byte 4 0) #b11100000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 6) code) (byte 6 0) #b10000000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 0) code) (byte 6 0) #b10000000))
(incf start))
((<= code #x10ffff)
(assert (<= (+ start 4) (or end (length octets))))
(setf (aref octets start) (dpb (ldb (byte 3 18) code) (byte 3 0) #b11110000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 12) code) (byte 6 0) #b10000000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 6) code) (byte 6 0) #b10000000))
(incf start)
(setf (aref octets start) (dpb (ldb (byte 6 0) code) (byte 6 0) #b10000000))
(incf start))
(t
(error "Invalid unicode code-point for utf-8 encoding ~D (#x~:*~X)" code)))
(values start octets))
(define-test test/utf-8-to-octets ()
(let ((octets (make-array 10 :element-type '(unsigned-byte 8) :initial-element 32)))
(assert-true (= 1 (utf-8-to-octets #x45 octets)))
(assert-true (= 2 (utf-8-to-octets #x745 octets)))
(assert-true (= 3 (utf-8-to-octets #x7045 octets)))
(assert-true (= 4 (utf-8-to-octets #x100045 octets)))))
(define-test test/decode-character/utf-8 ()
(let ((encoding :utf-8)
(octets (make-array 10 :element-type '(unsigned-byte 8) :initial-element 32)))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 0 :encoding encoding))
'(nil t 1))
;; Note: this includes the cases where code-char returns NIL:
(loop :for code :from 0 :below char-code-limit
:for next := (utf-8-to-octets code octets :start 0 :end (length octets))
:do (utf-8-to-octets 65 octets :start next :end (length octets))
(if (<= code #x7f)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 1 :encoding encoding))
(list (code-char code) t next)
(encoding code octets))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 1 :encoding encoding))
(list nil t next)
(encoding code octets)))
(if (<= code #x7ff)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 2 :encoding encoding))
(list (code-char code) t next)
(encoding code octets))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 2 :encoding encoding))
(list nil t next)
(encoding code octets)))
(if (<= code #xffff)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 3 :encoding encoding))
(list (code-char code) t next)
(encoding code octets))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 3 :encoding encoding))
(list nil t next)
(encoding code octets)))
(if (<= code #x10ffff)
(check equal
(multiple-value-list (decode-character octets :start 0 :end 4 :encoding encoding))
(list (code-char code) t next)
(encoding code octets))
(check equal
(multiple-value-list (decode-character octets :start 0 :end 4 :encoding encoding))
(list nil t next)
(encoding code octets))))
;; Testing invalid utf-8 code sequences:
(check equal (multiple-value-list (decode-character (replace octets #(130)) :encoding encoding))
'(nil nil 1)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11000000 #b00100001)) :encoding encoding))
'(nil nil 2)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11000000 #b11100001)) :encoding encoding))
'(nil nil 2)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11100000 #b10110011 #b00100001)) :encoding encoding))
'(nil nil 3)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11100000 #b10110011 #b11100001)) :encoding encoding))
'(nil nil 3)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b00100001 #b10110011 #b10110011)) :encoding encoding))
'(nil nil 4)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b10110011 #b00100001 #b10110011)) :encoding encoding))
'(nil nil 4)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b10110011 #b10110011 #b00100001)) :encoding encoding))
'(nil nil 4)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b11100001 #b10110011 #b10110011)) :encoding encoding))
'(nil nil 4)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b10110011 #b11100001 #b10110011)) :encoding encoding))
'(nil nil 4)
(encoding octets))
(check equal (multiple-value-list (decode-character (replace octets #(#b11110000 #b10110011 #b10110011 #b11100001)) :encoding encoding))
'(nil nil 4)
(encoding octets))))
(define-test test/decode-character/eucjp ()
(let* ((encoding :eucjp)
(string "こんにちは / コンニチハ")
(octets (babel:string-to-octets string :encoding :eucjp)))
(loop
:for expected :across string
:for start := 0 :then (+ start size)
:for (character validp size) := (multiple-value-list (decode-character octets :start start :encoding encoding))
:do (assert-true character (character) "decode-character should have decoded a ~S character from ~A" encoding start)
(assert-true validp (validp) "decode-character should have decoded a valid ~S code sequence from ~A" encoding start)
(check char= character expected (encoding start octets character expected))
:finally (incf start size)
(check = start (length octets) (encoding start octets)))))
(define-test test/all ()
(test/decode-character/us-ascii)
(test/decode-character/iso-8859-1)
(test/utf-8-to-octets)
(test/decode-character/utf-8)
(test/decode-character/eucjp))
;; (test/all)
;;;; THE END ;;;;
| 11,887 | Common Lisp | .lisp | 233 | 40.703863 | 140 | 0.580734 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 47482d2b33e76cbb61335ec619671fee5487ca36b01b5f3089f4312b72202120 | 4,903 | [
-1
] |
4,904 | packages.lisp | informatimago_lisp/clext/telnet/packages.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: packages.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; The package definitions of the telnet REPL server.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2021-05-13 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2021 - 2021
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION"
(:use "COMMON-LISP"
"BABEL")
(:export "DECODE-CHARACTER"
"REPLACE-OCTETS-BY-STRING"))
;; (push :debug-condition-variables *features*)
;; (member :debug-condition-variables *features*)
#+(and ccl debug-condition-variables)
(defpackage "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
(:use "COMMON-LISP" "BORDEAUX-THREADS")
(:shadow "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:documentation "Implements bt:make-condition-variable on ccl to print the name."))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
(:use "COMMON-LISP"
"BORDEAUX-THREADS"
"TRIVIAL-GRAY-STREAMS"
"COM.INFORMATIMAGO.COMMON-LISP.TELNET"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ASCII"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS"
"COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION"
"COM.INFORMATIMAGO.CLEXT.INTERRUPT")
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "WITH-TELNET-ON-STREAM"
"TELNET-STREAM"
"TELNET-STREAM-THREAD"
"NAME" "CLIENT" "STOP-CLOSURE"
"*LOG-OUTPUT*"
"STREAM-ECHO-MODE"))
(defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.REPL"
(:use "COMMON-LISP"
"BABEL"
"USOCKET"
"BORDEAUX-THREADS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STREAM"
"COM.INFORMATIMAGO.COMMON-LISP.TELNET"
;; "com.informatimago.common-lisp.cesarum"
"COM.INFORMATIMAGO.COMMON-LISP.INTERACTIVE.INTERACTIVE"
"COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
"COM.INFORMATIMAGO.CLEXT.INTERRUPT")
#+(and ccl debug-condition-variables)
(:shadowing-import-from "COM.INFORMATIMAGO.BORDEAUX-THREAD.PATCH"
"MAKE-CONDITION-VARIABLE" "WITH-LOCK-HELD")
(:export "REPL-SERVER"
"REPL-SERVER-THREAD"
"REPL-SERVER-PORT"
"REPL-SERVER-INTERFACE"
"REPL-SERVER-MAX-CLIENTS"
"REPL-SERVER-CLIENT-THREADS"
"START-REPL-SERVER" "STOP-REPL-SERVER"))
;;;; THE END ;;;;
| 3,774 | Common Lisp | .lisp | 89 | 37.089888 | 85 | 0.637354 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 9f7a12396f0ba2b5d8b884c8276e4dfcd023d840f15468eea0f7cf56bfeadba7 | 4,904 | [
-1
] |
4,905 | telnet-stream-test.lisp | informatimago_lisp/clext/telnet/telnet-stream-test.lisp | (defpackage "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM.TEST"
(:use "COMMON-LISP"
"BORDEAUX-THREADS"
"TRIVIAL-GRAY-STREAMS"
"COM.INFORMATIMAGO.COMMON-LISP.TELNET"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ASCII"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.CHARACTER-SETS"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.ARRAY"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.STRING"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.LIST"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.CLEXT.CHARACTER-SETS"
"COM.INFORMATIMAGO.CLEXT.BABEL-EXTENSION"
"COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
"COM.INFORMATIMAGO.CLEXT.TELNET.TEST.STUB-NVT")
(:import-from "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM"
"OCTET"
"MAKE-BINARY-BUFFER" "NVT"
"OUTPUT-BUFFER" "ENCODE-STRING-TO-OUTPUT-BUFFER"
"INPUT-BUFFER" "INPUT-BUFFER-APPEND-OCTETS"
"INPUT-BUFFER-READ-OCTET"
"+INPUT-BUFFER-SIZE+"
"INPUT-BUFFER-DATA"
"INPUT-BUFFER-HEAD"
"INPUT-BUFFER-TAIL")
(:export "TEST/ALL"))
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM.TEST")
(define-test test/replace-octets-by-string ()
(let ((buffer (make-binary-buffer 100)))
(let* ((string "Hello World")
(bytes (map 'vector 'ascii-code string)))
(setf (fill-pointer buffer) (array-dimension buffer 0))
(multiple-value-bind (filledp size)
(replace-octets-by-string buffer string
:start1 0
:encoding :us-ascii)
(assert-true filledp (buffer string :us-ascii)
"~S could not fill the buffer."
'replace-octets-by-string)
(assert-true (= (length string) size)
(buffer string :us-ascii)
"~S didn't filled only ~D bytes instead of expected ~D bytes."
'replace-octets-by-string
size
(length string))
(assert-true (= size (mismatch buffer bytes :end1 size)))
(setf (fill-pointer buffer) size)
(check equalp buffer bytes)))))
(define-test test/encode-string-to-output-buffer ()
(let* ((stream (make-instance 'telnet-stream
:element-type 'character))
(nvt (make-instance 'stub-nvt
:name "STUB NVT"
:client nil
:up-sender stream
:down-sender nil)))
(setf (slot-value stream 'nvt) nvt)
(let* ((buffer (output-buffer stream))
(s1 "Hello ")
(s2 "World!")
(s1+s2 (concatenate 'string s1 s2))
(bytes (map 'vector 'ascii-code s1+s2)))
(check = (fill-pointer buffer) 0 (buffer))
(encode-string-to-output-buffer stream s1)
(check = (fill-pointer buffer) (length s1) (buffer))
(encode-string-to-output-buffer stream s2)
(check = (fill-pointer buffer) (length s1+s2) (buffer))
(check equalp buffer bytes (buffer bytes)))))
(define-test test/input-buffer-append-octets ()
(let* ((stream (make-instance 'telnet-stream
:element-type 'character))
(nvt (make-instance 'stub-nvt
:name "STUB NVT"
:client nil
:up-sender stream
:down-sender nil)))
(setf (slot-value stream 'nvt) nvt)
(let* ((smallest 32)
(bytes (coerce (iota 95 smallest) '(vector octet))))
(assert-true (= +input-buffer-size+
(length (input-buffer-data (input-buffer stream)))))
(assert-true (plusp (rem +input-buffer-size+ (length bytes))) ()
"We expected (plusp (rem +input-buffer-size+ ~A)) but it's zero."
(length bytes))
(loop ; fill the buffer (truncate 4096 95) -> 43 times, remains 11 free.
:repeat (truncate (length (input-buffer-data (input-buffer stream)))
(length bytes))
:for head := (input-buffer-head (input-buffer stream))
:for tail := (input-buffer-tail (input-buffer stream))
:do (input-buffer-append-octets stream bytes 0 (length bytes))
(let* ((buffer (input-buffer stream)))
(check = (input-buffer-head buffer) 0 (buffer bytes))
(check = (input-buffer-head buffer) head (buffer bytes))
(check = (input-buffer-tail buffer) (+ tail (length bytes)) (buffer bytes))
(check equalp
(subseq (input-buffer-data buffer) tail (input-buffer-tail buffer))
bytes (buffer bytes))))
(let ((size 1000))
(loop
:repeat size
:with head := (input-buffer-head (input-buffer stream))
:with tail := (input-buffer-tail (input-buffer stream))
:for i :from 0
:for expected := (+ smallest (mod i (length bytes)))
:for byte := (input-buffer-read-octet stream)
:do (let* ((buffer (input-buffer stream)))
(assert-true (= byte expected) (byte expected))
(check = (input-buffer-head buffer) (+ head i 1) (buffer bytes))
(check = (input-buffer-tail buffer) tail (buffer bytes))))
(let* ((remains (rem (length (input-buffer-data (input-buffer stream)))
(length bytes)))
(head (input-buffer-head (input-buffer stream)))
(tail (input-buffer-tail (input-buffer stream))))
(input-buffer-append-octets stream bytes 0 (length bytes))
(let* ((buffer (input-buffer stream)))
(check = (input-buffer-head buffer) size (buffer bytes))
(check = (input-buffer-head buffer) head (buffer bytes))
(check = (input-buffer-tail buffer)
(mod (+ tail (length bytes)) (length (input-buffer-data buffer)))
(buffer bytes))
(check < (input-buffer-tail buffer) (input-buffer-head buffer)
(buffer bytes))
(check equalp
(subseq (input-buffer-data buffer) tail (length (input-buffer-data buffer)))
(subseq bytes 0 remains)
(buffer bytes))
(check equalp
(subseq (input-buffer-data buffer) 0 (- (length bytes) remains))
(subseq bytes remains)
(buffer bytes))))))))
(define-test test/all ()
(test/replace-octets-by-string)
(test/encode-string-to-output-buffer)
(test/input-buffer-append-octets))
;; (setf *DEBUG-ON-FAILURE* t)
(test/all)
| 7,014 | Common Lisp | .lisp | 136 | 37.477941 | 95 | 0.544315 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 4f264614e14d374d75c217606b546d7cd4a66ab762a777b76198da90e36fe1db | 4,905 | [
-1
] |
4,906 | start.lisp | informatimago_lisp/clext/telnet/start.lisp | (push :debug-condition-variables *features*)
;; (push :debug-trace-telnet *features*)
(ql:quickload :com.informatimago.clext.telnet.repl.test)
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.STREAM")
#+debug-trace-telnet
(trace %input-buffer-free-space
%input-buffer-length
%input-buffer-ranges
%stream-read-char
%wait-for-input-data-present
%wait-for-input-free-space
(setf stream-echo-mode)
(setf stream-element-type)
(setf stream-external-format)
(setf stream-input-buffering)
(setf stream-output-buffering)
buffer-append
call-with-telnet-on-stream
check-sequence-arguments
check-stream-open
configure-mode
encode-string-to-output-buffer
flush-output-buffer
input-buffer-append-octet
input-buffer-append-octets
input-buffer-append-text
input-buffer-erase-character
input-buffer-erase-line
input-buffer-fetch-octet
input-buffer-peek-octet
input-buffer-read-octet
input-loop
make-binary-buffer
make-input-buffer
make-string-buffer
receive-binary
receive-control
receive-option
receive-text
send
send-binary
send-control
send-text
type-equal-p
update-column
want-option-p)
#+debug-trace-telnet
(trace (stream-read-char :if (typep (first ccl::args) 'telnet-stream))
(stream-read-char-no-hang :if (typep (first ccl::args) 'telnet-stream))
(stream-peek-char :if (typep (first ccl::args) 'telnet-stream))
(stream-read-line :if (typep (first ccl::args) 'telnet-stream))
(stream-listen :if (typep (first ccl::args) 'telnet-stream))
(stream-unread-char :if (typep (first ccl::args) 'telnet-stream))
(stream-read-byte :if (typep (first ccl::args) 'telnet-stream))
(stream-read-sequence :if (typep (first ccl::args) 'telnet-stream))
(stream-advance-to-column :if (typep (first ccl::args) 'telnet-stream))
(stream-finish-output :if (typep (first ccl::args) 'telnet-stream))
(stream-line-column :if (typep (first ccl::args) 'telnet-stream))
(stream-start-line-p :if (typep (first ccl::args) 'telnet-stream))
(stream-terpri :if (typep (first ccl::args) 'telnet-stream))
(stream-write-byte :if (typep (first ccl::args) 'telnet-stream))
(stream-write-char :if (typep (first ccl::args) 'telnet-stream))
(stream-write-sequence :if (typep (first ccl::args) 'telnet-stream))
(stream-write-string :if (typep (first ccl::args) 'telnet-stream)))
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.REPL")
#+debug-trace-telnet
(trace make-repl-readtable
make-repl-package
telnet-repl
run-client-loop
%clean-up
%add-client
remove-client
wait-for-free-client-slot
run-server-loop
start-repl-server
stop-repl-server)
(in-package "COM.INFORMATIMAGO.CLEXT.TELNET.REPL")
(defparameter *repl-server* (com.informatimago.clext.telnet.repl:start-repl-server
:banner-function (lambda (stream cn name)
(format stream "~&REPL SERVER #~A ~A~%" cn name)
(force-output stream))
:login-function nil))
(com.informatimago.tools.thread:list-threads)
| 3,552 | Common Lisp | .lisp | 84 | 33.488095 | 102 | 0.618303 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d453d12a3b922c6d5f618897249ff1b3d64f2f21130f3a134fed3e75ae869ed8 | 4,906 | [
-1
] |
4,907 | debug.lisp | informatimago_lisp/clext/pkcs11/debug.lisp | (in-package "COM.INFORMATIMAGO.CLEXT.PKCS11")
(defvar *dump-prefix* "")
(defun dump-vector (vector &key print-characters)
(let ((*print-circle* nil)
(size (length vector)))
(loop
:for i :from 0 :by 16
:while (< i size)
:do (format t "~&~A~16,'0X: " *dump-prefix* i)
(loop
:repeat 16
:for j :from i
:if (< j size)
:do (format t "~2,'0X " (aref vector j))
:else
:do (write-string " "))
(when print-characters
(loop
:repeat 16
:for j :from i
:if (< j size)
:do (format t "~C" (let ((code (aref vector j)))
(if (<= 32 code 126)
(code-char code)
#\.)))
:else
:do (write-string " "))))
:finally (terpri)))
;; (print (list :ok) *trace-output*) (finish-output *trace-output*)
;; (let ((*template* template))
;; (declare (special *template*))
;; (proclaim '(special *template*))
;; (com.informatimago.common-lisp.interactive.interactive:repl))
;; (print '(:attribute-sensitive :attribute-type-invalid :buffer-too-small) *trace-output*)
;; (print (list 'get-attribute-value (list 'template-decode template)) *trace-output*)
;; (finish-output *trace-output*)
;; (let ((*template* template)
;; (*error* err))
;; (declare (special *template* *error*))
;; (proclaim '(special *template* *error*))
;; (com.informatimago.common-lisp.interactive.interactive:repl))
(defun resume ()
(com.informatimago.common-lisp.interactive.interactive:repl-exit))
(defun pause (bindings message &rest arguments)
(format t "~&~?~%" message arguments)
(format t "Type (resume) to resume.~%")
(progv
(mapcar (function first) bindings)
(mapcar (function second) bindings)
(com.informatimago.common-lisp.interactive.interactive:repl)))
;;;; THE END ;;;;
| 2,198 | Common Lisp | .lisp | 51 | 31.156863 | 108 | 0.510042 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | ca140ffdfcb49702e5ef4c0fc0aa80c5460725b6c0620ef4bd912093b9319aba | 4,907 | [
-1
] |
4,908 | tests.lisp | informatimago_lisp/clext/pkcs11/tests.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: tests.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Some tests of the pkcs11 package.
;;;;
;;;; Note they're not (YET) actual unit tests (automatic tests,
;;;; resulting in success / failure status), but more debugging
;;;; tools and exercises of the pkcs11 functions that need manual
;;;; validation. (And definitely manual intervention: insert the
;;;; Smartcard in the Smartcard reader, key-in PIN codes, etc).
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2018-04-25 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2018 - 2018
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(in-package "COM.INFORMATIMAGO.CLEXT.PKCS11")
(defcfun (mtrace "mtrace") :void)
(defcfun (muntrace "muntrace") :void)
(defun call-with-mtrace (log-pathname thunk)
#+darwin (declare (ignore log-pathname))
;; TODO: darwin: use libgmalloc.
#+linux
(let* ((mtrace-envvar "MALLOC_TRACE")
(old-mtrace (ccl:getenv mtrace-envvar)))
(ccl:setenv mtrace-envvar (namestring log-pathname))
(mtrace)
(unwind-protect
(funcall thunk)
(muntrace)
(if old-mtrace
(ccl:setenv mtrace-envvar old-mtrace)
(ccl:unsetenv mtrace-envvar))))
#+darwin
(funcall thunk))
(defmacro with-mtrace ((log-pathname) &body body)
`(call-with-mtrace ,log-pathname (lambda () ,@body)))
(defun print-error (condition)
(format t "~&~A~%" condition)
(force-output))
(defun safe-get-list-of-slots-with-token ()
(or (get-slot-list t)
(progn
(format t "No smartcart~%")
(finish-output)
'())))
(defun test/string-to-utf-8 ()
(assert (equalp (string-to-utf-8 "Ça roule en été!" :size 18 :padchar #\space)
#(195 135 97 32 114 111 117 108 101 32 101 110 32 195 169 116 195 169)))
(assert (nth-value 1 (ignore-errors (progn (string-to-utf-8 "Ça roule en été!" :size 17 :padchar #\space) t))))
(assert (equalp (string-to-utf-8 "Ça roule en été!" :size 16 :padchar #\space)
#(195 135 97 32 114 111 117 108 101 32 101 110 32 195 169 116)))
(assert (equalp (string-to-utf-8 "Ça roule en été!" :size 24 :padchar #\space)
#(195 135 97 32 114 111 117 108 101 32 101 110 32 195 169 116 195 169 33 32 32 32 32 32)))
(assert (nth-value 1 (ignore-errors (progn (string-to-utf-8 "Ça roule en été!" :size 24 :padchar (character "∞")) t))))
(assert (equalp (string-to-utf-8 "Ça roule en été!" :size 25 :padchar (character "∞"))
#(195 135 97 32 114 111 117 108 101 32 101 110 32 195 169 116 195 169 33 226 136 158 226 136 158)))
:success)
(defun test/session ()
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(with-open-session (session slot-id :if-open-session-fails nil)
(print (when session (get-session-info session))))))
:success)
(defun test/operation-state ()
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(handler-case
(with-open-session (session slot-id :if-open-session-fails nil)
(let ((state (get-operation-state session)))
(print state)
(set-operation-state session state)))
(pkcs11-error (err) (print-error err)))))
:success)
(defun test/login ()
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(with-open-session (session slot-id)
(let ((*verbose* t))
(do-logged-in (session slot-id)
(write-line "Inside logged session.")
(finish-output))))))
(finish-output)
:success)
(defun test/slots-and-mechanisms ()
(test/string-to-utf-8)
(with-pkcs11
(format t "Info: ~S~%" (get-info))
(format t "All Slot IDs: ~S~%" (get-slot-list nil))
(format t "~:{- Slot ID: ~A~% Slot Info: ~S~%~%~}"
(mapcar (lambda (slot-id)
(list slot-id
(handler-case (get-slot-info slot-id)
(error (err) (princ-to-string err)))))
(get-slot-list nil)))
(format t "Slot IDs with a token: ~S~%" (get-slot-list t))
(format t "~:{- Slot ID: ~A~% Slot Info: ~S~% Token Info: ~S~
~% Mechanism list: ~{~A~^~% ~}~%~}"
(mapcar (lambda (slot-id)
(list slot-id
(handler-case (get-slot-info slot-id)
(error (err) (princ-to-string err)))
(handler-case (get-token-info slot-id)
(error (err) (princ-to-string err)))
(handler-case (mapcar (lambda (mechanism-type)
(list mechanism-type
(get-mechanism-info slot-id mechanism-type)))
(get-mechanism-list slot-id))
(error (err) (list (princ-to-string err))))))
(get-slot-list t))))
:success)
(defun test/template-encode ()
(let ((template (template-encode
'((:class . :data)
(:application . "My Test Application")
(:token . t)
(:label . "Test Data")
(:value . "Some data object containing some test data. This is it!")))))
(template-dump template)
(template-free template))
:success)
(defun test/create-object ()
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(with-open-session (session slot-id)
(handler-case
(print (create-object session '((:class . :data)
(:application . "My Test Application")
(:token . t)
(:label . "Test Data")
(:value . "Some data object containing some test data. This is it!"))))
(pkcs11-error (err) (print-error err))))))
:success)
;; (test/create-object) -> attribute value invalid. would that be the application?
(defun test/random ()
(write-line ";; seed-random is not supported by ECC-MI.")
(write-line ";; generate-random works only on length=0 on ECC-MI (useless).")
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(with-open-session (session slot-id)
(handler-case
(seed-random session (vector (random 256)
(random 256)
(random 256)
(random 256)))
(pkcs11-error (err)
(print-error err)
(unless (eql :function-not-supported (pkcs11-error-label err))
(signal err))))
(handler-case
(generate-random session 4)
(pkcs11-error (err)
(print-error err)
(unless (eql :data-len-range (pkcs11-error-label err))
(signal err)))))))
:success)
;; ; seed-random not supported
;; (untrace foreign-vector)
;; (test/random)
;; get-function-status and cancel-function are useless legacy functions. Not implemented.
;; (test/session)
;; (test)
;; (load-library)
;; (with-pkcs11 (wait-for-slot-event nil)) ;; not supported by "/usr/local/lib/libiaspkcs11.so"
(defmacro possibly-logged-in ((session slot-id log-in) &body body)
(let ((vsession (gensym "session"))
(vslot-id (gensym "slot-id"))
(vlog-in (gensym "log-in"))
(fbody (gensym "body")))
`(let ((,vsession ,session)
(,vslot-id ,slot-id)
(,vlog-in ,log-in))
(flet ((,fbody () ,@body))
(if ,vlog-in
(call-logged-in ,vsession ,vslot-id (function ,fbody))
(,fbody))))))
(defun test/find-objects (&optional log-in)
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(format t "~2%Slot ~3D~%--------~2%" slot-id)
(with-open-session (session slot-id)
(possibly-logged-in (session slot-id log-in)
(let ((all-objects (find-all-objects session nil)))
(pprint all-objects)
(dolist (object all-objects)
(format t "~&Object Handle: ~A~%~{ ~S~%~}~%" object (object-get-all-attributes session object))))))))
:success)
;; (test/find-objects t)
(defun select/encrypt-key ())
(defun test/encrypt ()
(with-pkcs11
(format t "Info: ~S~%" (get-info))
(format t "All Slot IDs: ~S~%" (get-slot-list nil))
(format t "~:{- Slot ID: ~A~% Slot Info: ~S~%~%~}"
(mapcar (lambda (slot-id)
(list slot-id
(handler-case (get-slot-info slot-id)
(error (err) (princ-to-string err)))))
(get-slot-list nil)))
(format t "Slot IDs with a token: ~S~%" (get-slot-list t))
(format t "~:{- Slot ID: ~A~% Slot Info: ~S~% Token Info: ~S~
~% Mechanism list: ~{~A~^~% ~}~%~}"
(mapcar (lambda (slot-id)
(list slot-id
(handler-case (get-slot-info slot-id)
(error (err) (princ-to-string err)))
(handler-case (get-token-info slot-id)
(error (err) (princ-to-string err)))
(handler-case (mapcar (lambda (mechanism-type)
(list mechanism-type
(get-mechanism-info slot-id mechanism-type)))
(get-mechanism-list slot-id))
(error (err) (list (princ-to-string err))))))
(get-slot-list t)))))
(defun aget (k a) (cdr (assoc k a)))
(defun object-handle (session &key class id token key-type label)
(first (find-all-objects session (append (when class (list (cons :class class)))
(when id (list (cons :id id)))
(when token (list (cons :token token)))
(when key-type (list (cons :key-type key-type)))
(when label (list (cons :label label)))))))
(defgeneric key-id (object)
(:documentation "KEY-ID specifiers are integers or octet vectors.")
(:method ((object vector)) object)
(:method ((object list)) (coerce object '(vector octet)))
(:method ((object integer))
(loop :with id := (make-array 18 :element-type 'octet)
:for j :from 0
:for p :from (* 8 (1- (length id))) :downto 0 :by 8
:do (setf (aref id j) (ldb (byte 8 p) object))
:finally (return id))))
(defparameter *authentication-key-path* '(:slot-id 0 :token "ECC MI" :id #xe828bd080fd2500000104d494f4300010101))
(defparameter *signature-key-path* '(:slot-id 1 :token "ECC MI" :id #xe828bd080fd2500000104d494f4300010103))
;; pub-key value <- authentication (no login)
;; priv-key signature -> sign (login)
(defun get-public-key-value (path)
(break)
(with-open-session (session (getf path :slot-id))
(break)
(let* ((pub-key (object-handle session :class :public-key :token (getf path :token) :id (key-id (getf path :id))))
(pub-key-value (let ((attributes (object-get-all-attributes session pub-key)))
(aget :value attributes))))
pub-key-value)))
(defun /sign (data signature-key-path)
(let ((slot-id (getf signature-key-path :slot-id)))
(with-open-session (session slot-id)
(do-logged-in (session slot-id "signing the authentication public-key")
(let ((sign-private-key (object-handle session :class :private-key
:token (getf signature-key-path :token)
:id (key-id (getf signature-key-path :id)))))
(sign-init session :sha1-rsa-pkcs sign-private-key)
(sign session data :output-end 256))))))
(defun /verify (data signature signature-key-path)
(let ((slot-id (getf signature-key-path :slot-id)))
(with-open-session (session slot-id)
(let ((sign-public-key (object-handle session :class :public-key
:token (getf signature-key-path :token)
:id (key-id (getf signature-key-path :id)))))
(verify-init session :sha1-rsa-pkcs sign-public-key)
(verify session data signature)))))
(defun test/sign&verify (&key
(authentication-key-path *authentication-key-path*)
(signature-key-path *signature-key-path*))
(with-pkcs11
(handler-case
(let* ((pub-key-value (get-public-key-value authentication-key-path))
(signature (/sign pub-key-value signature-key-path)))
(format t "~&Authentication public-key: ~S~%" pub-key-value)
(format t "~&Signature: ~S~%" signature)
(format t "~&Verifying signature.~%")
(/verify pub-key-value signature signature-key-path)
(format t "~&Verifying bad signature.~%")
(setf (aref pub-key-value 0) (mod (1+ (aref pub-key-value 0)) 256))
(unwind-protect
(princ (nth-value 1 (ignore-errors (/verify pub-key-value signature signature-key-path))))
(setf (aref pub-key-value 0) (mod (1- (aref pub-key-value 0)) 256))))
(pkcs11-error (err)
(if (eql :token-not-present (pkcs11-error-label err))
(progn
(format t "No smartcart~%")
(finish-output))
(signal err)))))
:success)
(defvar *session* nil)
(defvar *slot-id* nil)
(defparameter *pjb-auth-key-id* #xe828bd080fd2500000104d494f4300010101)
(defparameter *pjb-sign-key-id* #xe828bd080fd2500000104d494f4300010103)
(defun done ()
(com.informatimago.common-lisp.interactive.interactive:repl-exit))
(defun test/repl (&key ((:slot-id *slot-id*) 0))
(with-pkcs11
(handler-case
(with-open-session (*session* *slot-id*)
(do-logged-in (*session* *slot-id*)
(format t "~&Evaluate (done) to log out from the smartcard.~%")
(com.informatimago.common-lisp.interactive.interactive:repl :reset-history nil)))
(error (err) (princ err) (terpri)))))
(defun test/all ()
(test/string-to-utf-8)
(test/session)
(test/operation-state)
(test/template-encode)
(test/slots-and-mechanisms)
(test/create-object)
(test/random)
(test/find-objects)
(test/login)
(test/sign&verify))
(defun iaspkcs11-library-p ()
(search "iaspkcs11" %ck::*loaded-library-pathname*))
(defun init-for-iaspkcs11 ()
(when (iaspkcs11-library-p)
(setf *authentication-key-path* '(:slot-id 1 :token "ECC MI" :id #xe828bd080fd2500000104d494f4300010101)
*signature-key-path* '(:slot-id 1 :token "ECC MI" :id #xe828bd080fd2500000104d494f4300010103))))
(defun print-object-attributes (session object-handle)
(format t "~&Object Handle: ~A~%~{ ~S~%~}~%"
object-handle
(object-get-all-attributes session object-handle)))
(defun test/find-object-signature ()
(with-pkcs11
(dolist (slot-id (safe-get-list-of-slots-with-token))
(format t "~&Slot ID = ~A~%" slot-id)
(with-open-session (*session* slot-id)
(handler-case
(do-logged-in (*session* slot-id)
(dolist (object (find-all-objects *session* '((:class . :private-key)
(:sign . 1))))
(print-object-attributes *session* object)))
(error (err) (princ err) (terpri)))))))
(defun opensc-pkcs11-library ()
(find "OPENSC-PKCS11" (cffi:list-foreign-libraries)
:key (function cffi:foreign-library-name)
:test (lambda (substr name) (search substr (string name)))))
(defun ias-pkcs11-library ()
(find "LIBIASPKCS11" (cffi:list-foreign-libraries)
:key (function cffi:foreign-library-name)
:test (lambda (substr name) (search substr (string name)))))
#-(and) (
(list (opensc-pkcs11-library) (ias-pkcs11-library))
;; (nil #<foreign-library libiaspkcs11.so-7496 "libiaspkcs11.so">)
(load-library #P"/usr/local/lib/opensc-pkcs11.so")
(test/find-object-signature)
(cffi:close-foreign-library (opensc-pkcs11-library))
(cffi:list-foreign-libraries)
(load-library #P"/usr/local/lib/libiaspkcs11.so")
(test/find-object-signature)
(cffi:close-foreign-library (ias-pkcs11-library))
(cffi:list-foreign-libraries)
(values (load-library #P"/usr/local/lib/opensc-pkcs11.so")
%ck::*loaded-library-pathname*)
(test/find-object-signature)
(ql:quickload :com.informatimago.clext.pkcs11)
(load #P"~/src/public/lisp/clext/pkcs11/tests.lisp")
)
;; (load-library #P"/usr/local/lib/libiaspkcs11.so")
;; Slot ID = 0
;; Please, enter pin on pin-pad (4 digits).
;; Logged in.
;; Object Handle: 139726896189904
;; (:class . :private-key)
;; (:token . 1)
;; (:private . 1)
;; (:label . "Clé d'authentification1")
;; (:key-type . :rsa)
;; (:subject . #())
;; (:id . #(232 40 189 8 15 210 80 0 0 16 77 73 79 67 0 1 1 1))
;; (:sensitive . 1)
;; (:decrypt . 1)
;; (:unwrap . 1)
;; (:sign . 1)
;; (:sign-recover . 0)
;; (:derive . 0)
;; (:start-date . "")
;; (:end-date . "")
;; (:modulus . #(193 88 149 82 25 31 19 49 204 111 230 49 213 136 64 113 59 31 124 129 100 70 209 119 77 233 1 142 145 186 242 58 88 146 44 150 67 62 19 179 50 58 185 41 204 58 194 159 171 80 152 254 104 248 146 158 177 216 245 190 222 103 160 151 233 127 182 112 33 11 47 71 83 75 115 10 173 31 16 178 158 155 91 150 245 139 23 203 248 67 41 121 16 203 120 37 126 187 33 71 151 138 221 193 126 167 236 91 183 104 200 51 102 222 247 180 54 3 3 45 215 32 44 246 53 120 150 154 158 27 18 169 150 154 164 231 196 138 120 224 186 237 193 246 59 179 39 99 50 183 116 177 86 119 223 193 143 3 55 140 65 149 75 192 80 192 184 245 111 113 107 236 225 0 224 213 121 106 126 5 27 220 240 115 149 126 37 157 228 10 141 41 95 63 62 51 147 190 70 157 117 186 127 159 145 19 253 91 146 60 17 249 48 212 73 106 52 254 177 115 77 75 73 220 29 132 86 108 198 106 176 73 39 125 113 47 26 109 79 174 45 184 251 214 125 23 240 144 160 75 222 137 172 116 221 143))
;; (:modulus-bits . 2048)
;; (:public-exponent . #(1 0 1))
;; (:extractable . 0)
;; (:local . 0)
;; (:never-extractable . 1)
;; (:always-sensitive . 1)
;; (:key-gen-mechanism . 18446744073709551615)
;; (:modifiable . 0)
;; (:always-authenticate . 0)
;;
;; Logged out.
;; Slot ID = 1
;; Please, enter pin on pin-pad (6 digits).
;; Logged in.
;; Object Handle: 139726896495648
;; (:class . :private-key)
;; (:token . 1)
;; (:private . 1)
;; (:label . "Clé de signature1")
;; (:key-type . :rsa)
;; (:subject . #())
;; (:id . #(232 40 189 8 15 210 80 0 0 16 77 73 79 67 0 1 1 3))
;; (:sensitive . 1)
;; (:decrypt . 0)
;; (:unwrap . 0)
;; (:sign . 1)
;; (:sign-recover . 0)
;; (:derive . 0)
;; (:start-date . "")
;; (:end-date . "")
;; (:modulus . #(193 10 1 244 230 222 241 199 246 105 42 213 38 253 252 77 85 173 161 56 3 117 114 170 218 239 121 195 77 163 116 52 29 99 45 75 209 66 177 189 130 199 20 109 66 253 49 226 67 43 1 210 175 199 223 139 200 66 147 28 27 72 1 179 177 212 160 155 208 166 246 228 244 112 20 148 216 20 255 184 0 92 154 7 25 98 242 1 12 69 30 27 192 190 68 120 141 23 21 201 198 100 73 175 1 92 64 78 236 143 25 176 79 122 233 191 8 211 154 17 101 128 214 175 187 169 106 44 234 144 168 30 26 132 7 165 188 120 239 247 32 50 152 245 105 207 78 38 223 101 111 228 238 162 209 190 12 98 38 51 35 140 86 96 29 100 185 207 33 80 8 135 39 102 33 158 79 167 102 101 68 126 95 45 34 58 204 80 241 211 14 212 244 200 217 131 124 157 249 53 21 5 29 21 145 44 77 27 31 96 159 84 186 158 62 215 171 144 155 103 159 19 252 7 144 121 184 44 64 174 139 195 80 255 209 11 83 157 23 166 154 159 176 124 84 67 199 12 215 63 228 181 35 54 30 249))
;; (:modulus-bits . 2048)
;; (:public-exponent . #(1 0 1))
;; (:extractable . 0)
;; (:local . 0)
;; (:never-extractable . 1)
;; (:always-sensitive . 1)
;; (:key-gen-mechanism . 18446744073709551615)
;; (:modifiable . 0)
;; (:always-authenticate . 1)
;;
;; Logged out.
;; nil
;;;; THE END ;;;;
| 21,905 | Common Lisp | .lisp | 442 | 40.384615 | 947 | 0.56951 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bbb110d725d6086772d73330b5e6c026eccf10d7aff5dd7025ce110f5507f309 | 4,908 | [
-1
] |
4,909 | pkcs11-cffi.lisp | informatimago_lisp/clext/pkcs11/pkcs11-cffi.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: pkcs11-cffi.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; XXX
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2018-04-18 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2018 - 2018
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.PKCS11.LOW"
(:use "COMMON-LISP" "CFFI")
(:nicknames "%CK")
(:export "LOAD-LIBRARY")
(:export "INITIALIZE" "FINALIZE" "GET-INFO" "GET-SLOT-LIST"
"GET-SLOT-INFO" "GET-TOKEN-INFO" "WAIT-FOR-SLOT-EVENT"
"GET-MECHANISM-LIST" "GET-MECHANISM-INFO" "INIT-TOKEN" "INIT-PIN"
"SET-PIN" "OPEN-SESSION" "CLOSE-SESSION" "CLOSE-ALL-SESSIONS"
"GET-SESSION-INFO" "GET-OPERATION-STATE" "SET-OPERATION-STATE"
"LOGIN" "LOGOUT" "CREATE-OBJECT" "COPY-OBJECT" "DESTROY-OBJECT"
"GET-OBJECT-SIZE" "GET-ATTRIBUTE-VALUE" "SET-ATTRIBUTE-VALUE"
"FIND-OBJECTS-INIT" "FIND-OBJECTS" "FIND-OBJECTS-FINAL"
"ENCRYPT-INIT" "ENCRYPT" "ENCRYPT-UPDATE" "ENCRYPT-FINAL"
"DECRYPT-INIT" "DECRYPT" "DECRYPT-UPDATE" "DECRYPT-FINAL"
"DIGEST-INIT" "DIGEST" "DIGEST-UPDATE" "DIGEST-KEY" "DIGEST-FINAL"
"SIGN-INIT" "SIGN" "SIGN-UPDATE" "SIGN-FINAL" "SIGN-RECOVER-INIT"
"SIGN-RECOVER" "VERIFY-INIT" "VERIFY" "VERIFY-UPDATE" "VERIFY-FINAL"
"VERIFY-RECOVER-INIT" "VERIFY-RECOVER" "DIGEST-ENCRYPT-UPDATE"
"DECRYPT-DIGEST-UPDATE" "SIGN-ENCRYPT-UPDATE"
"DECRYPT-VERIFY-UPDATE" "GENERATE-KEY" "GENERATE-KEY-PAIR"
"WRAP-KEY" "UNWRAP-KEY" "DERIVE-KEY" "SEED-RANDOM" "GENERATE-RANDOM"
"GET-FUNCTION-STATUS" "CANCEL-FUNCTION")
(:export "+TRUE+" "+FALSE+"
"+SURRENDER+" "+TOKEN-PRESENT+" "+REMOVABLE-DEVICE+"
"+HW-SLOT+" "+ARRAY-ATTRIBUTE+" "+RNG+" "+WRITE-PROTECTED+"
"+LOGIN-REQUIRED+" "+USER-PIN-INITIALIZED+" "+RESTORE-KEY-NOT-NEEDED+"
"+CLOCK-ON-TOKEN+" "+PROTECTED-AUTHENTICATION-PATH+"
"+DUAL-CRYPTO-OPERATIONS+" "+TOKEN-INITIALIZED+"
"+SECONDARY-AUTHENTICATION+" "+USER-PIN-COUNT-LOW+"
"+USER-PIN-FINAL-TRY+" "+USER-PIN-LOCKED+" "+USER-PIN-TO-BE-CHANGED+"
"+SO-PIN-COUNT-LOW+" "+SO-PIN-FINAL-TRY+" "+SO-PIN-LOCKED+"
"+SO-PIN-TO-BE-CHANGED+" "+UNAVAILABLE-INFORMATION+"
"+EFFECTIVELY-INFINITE+" "+INVALID-HANDLE+" "+SO+" "+USER+"
"+CONTEXT-SPECIFIC+" "+RO-PUBLIC-SESSION+" "+RO-USER-FUNCTIONS+"
"+RW-PUBLIC-SESSION+" "+RW-USER-FUNCTIONS+" "+RW-SO-FUNCTIONS+"
"+RW-SESSION+" "+SERIAL-SESSION+" "+O-DATA+" "+O-CERTIFICATE+"
"+O-PUBLIC-KEY+" "+O-PRIVATE-KEY+" "+O-SECRET-KEY+" "+O-HW-FEATURE+"
"+O-DOMAIN-PARAMETERS+" "+O-MECHANISM+" "+VENDOR-DEFINED+"
"+H-MONOTONIC-COUNTER+" "+H-CLOCK+" "+H-USER-INTERFACE+" "+K-RSA+"
"+K-DSA+" "+K-DH+" "+K-ECDSA+" "+K-EC+" "+K-X9-42-DH+" "+K-KEA+"
"+K-GENERIC-SECRET+" "+K-RC2+" "+K-RC4+" "+K-DES+" "+K-DES2+"
"+K-DES3+" "+K-CAST+" "+K-CAST3+" "+K-CAST128+" "+K-RC5+" "+K-IDEA+"
"+K-SKIPJACK+" "+K-BATON+" "+K-JUNIPER+" "+K-CDMF+" "+K-AES+"
"+K-BLOWFISH+" "+K-TWOFISH+" "+C-X-509+" "+C-X-509-ATTR-CERT+"
"+C-WTLS+" "+A-CLASS+" "+A-TOKEN+" "+A-PRIVATE+" "+A-LABEL+"
"+A-APPLICATION+" "+A-VALUE+" "+A-OBJECT-ID+" "+A-CERTIFICATE-TYPE+"
"+A-ISSUER+" "+A-SERIAL-NUMBER+" "+A-AC-ISSUER+" "+A-OWNER+"
"+A-ATTR-TYPES+" "+A-TRUSTED+" "+A-CERTIFICATE-CATEGORY+"
"+A-JAVA-MIDP-SECURITY-DOMAIN+" "+A-URL+"
"+A-HASH-OF-SUBJECT-PUBLIC-KEY+" "+A-HASH-OF-ISSUER-PUBLIC-KEY+"
"+A-CHECK-VALUE+" "+A-KEY-TYPE+" "+A-SUBJECT+" "+A-ID+"
"+A-SENSITIVE+" "+A-ENCRYPT+" "+A-DECRYPT+" "+A-WRAP+" "+A-UNWRAP+"
"+A-SIGN+" "+A-SIGN-RECOVER+" "+A-VERIFY+" "+A-VERIFY-RECOVER+"
"+A-DERIVE+" "+A-START-DATE+" "+A-END-DATE+" "+A-MODULUS+"
"+A-MODULUS-BITS+" "+A-PUBLIC-EXPONENT+" "+A-PRIVATE-EXPONENT+"
"+A-PRIME-1+" "+A-PRIME-2+" "+A-EXPONENT-1+" "+A-EXPONENT-2+"
"+A-COEFFICIENT+" "+A-PRIME+" "+A-SUBPRIME+" "+A-BASE+"
"+A-PRIME-BITS+" "+A-SUB-PRIME-BITS+" "+A-VALUE-BITS+" "+A-VALUE-LEN+"
"+A-EXTRACTABLE+" "+A-LOCAL+" "+A-NEVER-EXTRACTABLE+"
"+A-ALWAYS-SENSITIVE+" "+A-KEY-GEN-MECHANISM+" "+A-MODIFIABLE+"
"+A-ECDSA-PARAMS+" "+A-EC-PARAMS+" "+A-EC-POINT+" "+A-SECONDARY-AUTH+"
"+A-AUTH-PIN-FLAGS+" "+A-ALWAYS-AUTHENTICATE+" "+A-WRAP-WITH-TRUSTED+"
"+A-HW-FEATURE-TYPE+" "+A-RESET-ON-INIT+" "+A-HAS-RESET+"
"+A-PIXEL-X+" "+A-PIXEL-Y+" "+A-RESOLUTION+" "+A-CHAR-ROWS+"
"+A-CHAR-COLUMNS+" "+A-COLOR+" "+A-BITS-PER-PIXEL+" "+A-CHAR-SETS+"
"+A-ENCODING-METHODS+" "+A-MIME-TYPES+" "+A-MECHANISM-TYPE+"
"+A-REQUIRED-CMS-ATTRIBUTES+" "+A-DEFAULT-CMS-ATTRIBUTES+"
"+A-SUPPORTED-CMS-ATTRIBUTES+" "+A-WRAP-TEMPLATE+"
"+A-UNWRAP-TEMPLATE+" "+A-ALLOWED-MECHANISMS+"
"+M-RSA-PKCS-KEY-PAIR-GEN+" "+M-RSA-PKCS+" "+M-RSA-9796+"
"+M-RSA-X-509+" "+M-MD2-RSA-PKCS+" "+M-MD5-RSA-PKCS+"
"+M-SHA1-RSA-PKCS+" "+M-RIPEMD128-RSA-PKCS+" "+M-RIPEMD160-RSA-PKCS+"
"+M-RSA-PKCS-OAEP+" "+M-RSA-X9-31-KEY-PAIR-GEN+" "+M-RSA-X9-31+"
"+M-SHA1-RSA-X9-31+" "+M-RSA-PKCS-PSS+" "+M-SHA1-RSA-PKCS-PSS+"
"+M-DSA-KEY-PAIR-GEN+" "+M-DSA+" "+M-DSA-SHA1+"
"+M-DH-PKCS-KEY-PAIR-GEN+" "+M-DH-PKCS-DERIVE+"
"+M-X9-42-DH-KEY-PAIR-GEN+" "+M-X9-42-DH-DERIVE+"
"+M-X9-42-DH-HYBRID-DERIVE+" "+M-X9-42-MQV-DERIVE+"
"+M-SHA256-RSA-PKCS+" "+M-SHA384-RSA-PKCS+" "+M-SHA512-RSA-PKCS+"
"+M-SHA256-RSA-PKCS-PSS+" "+M-SHA384-RSA-PKCS-PSS+"
"+M-SHA512-RSA-PKCS-PSS+" "+M-RC2-KEY-GEN+" "+M-RC2-ECB+"
"+M-RC2-CBC+" "+M-RC2-MAC+" "+M-RC2-MAC-GENERAL+" "+M-RC2-CBC-PAD+"
"+M-RC4-KEY-GEN+" "+M-RC4+" "+M-DES-KEY-GEN+" "+M-DES-ECB+"
"+M-DES-CBC+" "+M-DES-MAC+" "+M-DES-MAC-GENERAL+" "+M-DES-CBC-PAD+"
"+M-DES2-KEY-GEN+" "+M-DES3-KEY-GEN+" "+M-DES3-ECB+" "+M-DES3-CBC+"
"+M-DES3-MAC+" "+M-DES3-MAC-GENERAL+" "+M-DES3-CBC-PAD+"
"+M-CDMF-KEY-GEN+" "+M-CDMF-ECB+" "+M-CDMF-CBC+" "+M-CDMF-MAC+"
"+M-CDMF-MAC-GENERAL+" "+M-CDMF-CBC-PAD+" "+M-MD2+" "+M-MD2-HMAC+"
"+M-MD2-HMAC-GENERAL+" "+M-MD5+" "+M-MD5-HMAC+" "+M-MD5-HMAC-GENERAL+"
"+M-SHA-1+" "+M-SHA-1-HMAC+" "+M-SHA-1-HMAC-GENERAL+" "+M-RIPEMD128+"
"+M-RIPEMD128-HMAC+" "+M-RIPEMD128-HMAC-GENERAL+" "+M-RIPEMD160+"
"+M-RIPEMD160-HMAC+" "+M-RIPEMD160-HMAC-GENERAL+" "+M-SHA256+"
"+M-SHA256-HMAC+" "+M-SHA256-HMAC-GENERAL+" "+M-SHA384+"
"+M-SHA384-HMAC+" "+M-SHA384-HMAC-GENERAL+" "+M-SHA512+"
"+M-SHA512-HMAC+" "+M-SHA512-HMAC-GENERAL+" "+M-CAST-KEY-GEN+"
"+M-CAST-ECB+" "+M-CAST-CBC+" "+M-CAST-MAC+" "+M-CAST-MAC-GENERAL+"
"+M-CAST-CBC-PAD+" "+M-CAST3-KEY-GEN+" "+M-CAST3-ECB+" "+M-CAST3-CBC+"
"+M-CAST3-MAC+" "+M-CAST3-MAC-GENERAL+" "+M-CAST3-CBC-PAD+"
"+M-CAST5-KEY-GEN+" "+M-CAST128-KEY-GEN+" "+M-CAST5-ECB+"
"+M-CAST128-ECB+" "+M-CAST5-CBC+" "+M-CAST128-CBC+" "+M-CAST5-MAC+"
"+M-CAST128-MAC+" "+M-CAST5-MAC-GENERAL+" "+M-CAST128-MAC-GENERAL+"
"+M-CAST5-CBC-PAD+" "+M-CAST128-CBC-PAD+" "+M-RC5-KEY-GEN+"
"+M-RC5-ECB+" "+M-RC5-CBC+" "+M-RC5-MAC+" "+M-RC5-MAC-GENERAL+"
"+M-RC5-CBC-PAD+" "+M-IDEA-KEY-GEN+" "+M-IDEA-ECB+" "+M-IDEA-CBC+"
"+M-IDEA-MAC+" "+M-IDEA-MAC-GENERAL+" "+M-IDEA-CBC-PAD+"
"+M-GENERIC-SECRET-KEY-GEN+" "+M-CONCATENATE-BASE-AND-KEY+"
"+M-CONCATENATE-BASE-AND-DATA+" "+M-CONCATENATE-DATA-AND-BASE+"
"+M-XOR-BASE-AND-DATA+" "+M-EXTRACT-KEY-FROM-KEY+"
"+M-SSL3-PRE-MASTER-KEY-GEN+" "+M-SSL3-MASTER-KEY-DERIVE+"
"+M-SSL3-KEY-AND-MAC-DERIVE+" "+M-SSL3-MASTER-KEY-DERIVE-DH+"
"+M-TLS-PRE-MASTER-KEY-GEN+" "+M-TLS-MASTER-KEY-DERIVE+"
"+M-TLS-KEY-AND-MAC-DERIVE+" "+M-TLS-MASTER-KEY-DERIVE-DH+"
"+M-SSL3-MD5-MAC+" "+M-SSL3-SHA1-MAC+" "+M-MD5-KEY-DERIVATION+"
"+M-MD2-KEY-DERIVATION+" "+M-SHA1-KEY-DERIVATION+"
"+M-PBE-MD2-DES-CBC+" "+M-PBE-MD5-DES-CBC+" "+M-PBE-MD5-CAST-CBC+"
"+M-PBE-MD5-CAST3-CBC+" "+M-PBE-MD5-CAST5-CBC+"
"+M-PBE-MD5-CAST128-CBC+" "+M-PBE-SHA1-CAST5-CBC+"
"+M-PBE-SHA1-CAST128-CBC+" "+M-PBE-SHA1-RC4-128+"
"+M-PBE-SHA1-RC4-40+" "+M-PBE-SHA1-DES3-EDE-CBC+"
"+M-PBE-SHA1-DES2-EDE-CBC+" "+M-PBE-SHA1-RC2-128-CBC+"
"+M-PBE-SHA1-RC2-40-CBC+" "+M-PKCS5-PBKD2+"
"+M-PBA-SHA1-WITH-SHA1-HMAC+" "+M-KEY-WRAP-LYNKS+"
"+M-KEY-WRAP-SET-OAEP+" "+M-SKIPJACK-KEY-GEN+" "+M-SKIPJACK-ECB64+"
"+M-SKIPJACK-CBC64+" "+M-SKIPJACK-OFB64+" "+M-SKIPJACK-CFB64+"
"+M-SKIPJACK-CFB32+" "+M-SKIPJACK-CFB16+" "+M-SKIPJACK-CFB8+"
"+M-SKIPJACK-WRAP+" "+M-SKIPJACK-PRIVATE-WRAP+" "+M-SKIPJACK-RELAYX+"
"+M-KEA-KEY-PAIR-GEN+" "+M-KEA-KEY-DERIVE+" "+M-FORTEZZA-TIMESTAMP+"
"+M-BATON-KEY-GEN+" "+M-BATON-ECB128+" "+M-BATON-ECB96+"
"+M-BATON-CBC128+" "+M-BATON-COUNTER+" "+M-BATON-SHUFFLE+"
"+M-BATON-WRAP+" "+M-ECDSA-KEY-PAIR-GEN+" "+M-EC-KEY-PAIR-GEN+"
"+M-ECDSA+" "+M-ECDSA-SHA1+" "+M-ECDH1-DERIVE+"
"+M-ECDH1-COFACTOR-DERIVE+" "+M-ECMQV-DERIVE+" "+M-JUNIPER-KEY-GEN+"
"+M-JUNIPER-ECB128+" "+M-JUNIPER-CBC128+" "+M-JUNIPER-COUNTER+"
"+M-JUNIPER-SHUFFLE+" "+M-JUNIPER-WRAP+" "+M-FASTHASH+"
"+M-AES-KEY-GEN+" "+M-AES-ECB+" "+M-AES-CBC+" "+M-AES-MAC+"
"+M-AES-MAC-GENERAL+" "+M-AES-CBC-PAD+" "+M-DSA-PARAMETER-GEN+"
"+M-DH-PKCS-PARAMETER-GEN+" "+M-X9-42-DH-PARAMETER-GEN+" "+F-HW+"
"+F-ENCRYPT+" "+F-DECRYPT+" "+F-DIGEST+" "+F-SIGN+" "+F-SIGN-RECOVER+"
"+F-VERIFY+" "+F-VERIFY-RECOVER+" "+F-GENERATE+"
"+F-GENERATE-KEY-PAIR+" "+F-WRAP+" "+F-UNWRAP+" "+F-DERIVE+"
"+F-EXTENSION+" "+DONT-BLOCK+")
(:export "+OK+" "+CANCEL+" "+HOST-MEMORY+" "+SLOT-ID-INVALID+"
"+GENERAL-ERROR+" "+FUNCTION-FAILED+" "+ARGUMENTS-BAD+" "+NO-EVENT+"
"+NEED-TO-CREATE-THREADS+" "+CANT-LOCK+" "+ATTRIBUTE-READ-ONLY+"
"+ATTRIBUTE-SENSITIVE+" "+ATTRIBUTE-TYPE-INVALID+"
"+ATTRIBUTE-VALUE-INVALID+" "+DATA-INVALID+" "+DATA-LEN-RANGE+"
"+DEVICE-ERROR+" "+DEVICE-MEMORY+" "+DEVICE-REMOVED+"
"+ENCRYPTED-DATA-INVALID+" "+ENCRYPTED-DATA-LEN-RANGE+"
"+FUNCTION-CANCELED+" "+FUNCTION-NOT-PARALLEL+"
"+FUNCTION-NOT-SUPPORTED+" "+KEY-HANDLE-INVALID+" "+KEY-SIZE-RANGE+"
"+KEY-TYPE-INCONSISTENT+" "+KEY-NOT-NEEDED+" "+KEY-CHANGED+"
"+KEY-NEEDED+" "+KEY-INDIGESTIBLE+" "+KEY-FUNCTION-NOT-PERMITTED+"
"+KEY-NOT-WRAPPABLE+" "+KEY-UNEXTRACTABLE+" "+MECHANISM-INVALID+"
"+MECHANISM-PARAM-INVALID+" "+OBJECT-HANDLE-INVALID+"
"+OPERATION-ACTIVE+" "+OPERATION-NOT-INITIALIZED+" "+PIN-INCORRECT+"
"+PIN-INVALID+" "+PIN-LEN-RANGE+" "+PIN-EXPIRED+" "+PIN-LOCKED+"
"+SESSION-CLOSED+" "+SESSION-COUNT+" "+SESSION-HANDLE-INVALID+"
"+SESSION-PARALLEL-NOT-SUPPORTED+" "+SESSION-READ-ONLY+"
"+SESSION-EXISTS+" "+SESSION-READ-ONLY-EXISTS+"
"+SESSION-READ-WRITE-SO-EXISTS+" "+SIGNATURE-INVALID+"
"+SIGNATURE-LEN-RANGE+" "+TEMPLATE-INCOMPLETE+"
"+TEMPLATE-INCONSISTENT+" "+TOKEN-NOT-PRESENT+"
"+TOKEN-NOT-RECOGNIZED+" "+TOKEN-WRITE-PROTECTED+"
"+UNWRAPPING-KEY-HANDLE-INVALID+" "+UNWRAPPING-KEY-SIZE-RANGE+"
"+UNWRAPPING-KEY-TYPE-INCONSISTENT+" "+USER-ALREADY-LOGGED-IN+"
"+USER-NOT-LOGGED-IN+" "+USER-PIN-NOT-INITIALIZED+"
"+USER-TYPE-INVALID+" "+USER-ANOTHER-ALREADY-LOGGED-IN+"
"+USER-TOO-MANY-TYPES+" "+WRAPPED-KEY-INVALID+"
"+WRAPPED-KEY-LEN-RANGE+" "+WRAPPING-KEY-HANDLE-INVALID+"
"+WRAPPING-KEY-SIZE-RANGE+" "+WRAPPING-KEY-TYPE-INCONSISTENT+"
"+RANDOM-SEED-NOT-SUPPORTED+" "+RANDOM-NO-RNG+"
"+DOMAIN-PARAMS-INVALID+" "+BUFFER-TOO-SMALL+" "+SAVED-STATE-INVALID+"
"+INFORMATION-SENSITIVE+" "+STATE-UNSAVEABLE+"
"+CRYPTOKI-NOT-INITIALIZED+" "+CRYPTOKI-ALREADY-INITIALIZED+"
"+MUTEX-BAD+" "+MUTEX-NOT-LOCKED+" "+FUNCTION-REJECTED+")
(:export "FLAGS" "RV" "NOTIFICATION" "SLOT-ID" "NOTIFY" "SESSION-HANDLE"
"USER-TYPE" "STATE" "OBJECT-HANDLE" "OBJECT-CLASS" "HW-FEATURE-TYPE"
"KEY-TYPE" "CERTIFICATE-TYPE" "ATTRIBUTE-TYPE" "MECHANISM-TYPE")
(:export "ATTRIBUTE" "CRYPTOKI-VERSION" "DATE" "DAY" "DEVICE-ERROR"
"FIRMWARE-VERSION" "FLAGS" "FREE-PRIVATE-MEMORY" "FREE-PUBLIC-MEMORY"
"HARDWARE-VERSION" "INFO" "LABEL" "LIBRARY-DESCRIPTION"
"LIBRARY-VERSION" "MAJOR" "MANUFACTURER-ID" "MAX-KEY-SIZE"
"MAX-PIN-LEN" "MAX-RW-SESSION-COUNT" "MAX-SESSION-COUNT" "MECHANISM"
"MECHANISM-INFO" "MIN-KEY-SIZE" "MIN-PIN-LEN" "MINOR" "MODEL" "MONTH"
"PARAMETER" "PARAMETER-LEN" "RW-SESSION-COUNT" "SERIAL-NUMBER"
"SESSION-COUNT" "SESSION-INFO" "SLOT-DESCRIPTION" "SLOT-ID"
"SLOT-INFO" "STATE" "TOKEN-INFO" "TOTAL-PRIVATE-MMEORY"
"TOTAL-PUBLIC-MEMORY" "TYPE" "UTC-TIME" "VALUE" "VALUE-LEN" "VERSION"
"YEAR")
(:documentation "CFFI interface over Cryptoki pkcs11 version 2.02"))
(in-package "COM.INFORMATIMAGO.CLEXT.PKCS11.LOW")
(defvar *loaded-library-pathname* nil)
(defun load-library (&optional library-pathname)
"Load the Cryptoki pkcs11 library found at LIBRARY-PATHNAME, or some default path if not given."
(if library-pathname
(progn (load-foreign-library library-pathname)
(setf *loaded-library-pathname* library-pathname))
(or (find-if (lambda (pathname)
(ignore-errors (load-foreign-library pathname))
(setf *loaded-library-pathname* pathname))
#+darwin '("/opt/local/lib/opensc-pkcs11.bundle/Contents/MacOS/opensc-pkcs11"
"/opt/local/lib/libopensc.dylib"
"/opt/local/lib/libpkcs11-helper.dylib")
#+linux '("/usr/local/lib/opensc-pkcs11.so"
"/usr/local/lib/libiaspkcs11.so"
"/usr/lib/x86_64-linux-gnu/opensc-pkcs11.so" #|an old version without C_Initialize et al.|#)
#-(or darwin linux) (error "What Cryptoki pkcs11 library shall I load?"))
(error "Cannot find a Cryptoki pkcs11 library."))))
(defconstant +true+ 1)
(defconstant +false+ 0)
(defcstruct version
(major :uchar)
(minor :uchar))
(defctype flags :ulong)
(defctype rv :ulong)
(defconstant +OK+ #x000)
(defconstant +CANCEL+ #x001)
(defconstant +HOST-MEMORY+ #x002)
(defconstant +SLOT-ID-INVALID+ #x003)
(defconstant +GENERAL-ERROR+ #x005)
(defconstant +FUNCTION-FAILED+ #x006)
(defconstant +ARGUMENTS-BAD+ #x007)
(defconstant +NO-EVENT+ #x008)
(defconstant +NEED-TO-CREATE-THREADS+ #x009)
(defconstant +CANT-LOCK+ #x00a)
(defconstant +ATTRIBUTE-READ-ONLY+ #x010)
(defconstant +ATTRIBUTE-SENSITIVE+ #x011)
(defconstant +ATTRIBUTE-TYPE-INVALID+ #x012)
(defconstant +ATTRIBUTE-VALUE-INVALID+ #x013)
(defconstant +DATA-INVALID+ #x020)
(defconstant +DATA-LEN-RANGE+ #x021)
(defconstant +DEVICE-ERROR+ #x030)
(defconstant +DEVICE-MEMORY+ #x031)
(defconstant +DEVICE-REMOVED+ #x032)
(defconstant +ENCRYPTED-DATA-INVALID+ #x040)
(defconstant +ENCRYPTED-DATA-LEN-RANGE+ #x041)
(defconstant +FUNCTION-CANCELED+ #x050)
(defconstant +FUNCTION-NOT-PARALLEL+ #x051)
(defconstant +FUNCTION-NOT-SUPPORTED+ #x054)
(defconstant +KEY-HANDLE-INVALID+ #x060)
(defconstant +KEY-SIZE-RANGE+ #x062)
(defconstant +KEY-TYPE-INCONSISTENT+ #x063)
(defconstant +KEY-NOT-NEEDED+ #x064)
(defconstant +KEY-CHANGED+ #x065)
(defconstant +KEY-NEEDED+ #x066)
(defconstant +KEY-INDIGESTIBLE+ #x067)
(defconstant +KEY-FUNCTION-NOT-PERMITTED+ #x068)
(defconstant +KEY-NOT-WRAPPABLE+ #x069)
(defconstant +KEY-UNEXTRACTABLE+ #x06a)
(defconstant +MECHANISM-INVALID+ #x070)
(defconstant +MECHANISM-PARAM-INVALID+ #x071)
(defconstant +OBJECT-HANDLE-INVALID+ #x082)
(defconstant +OPERATION-ACTIVE+ #x090)
(defconstant +OPERATION-NOT-INITIALIZED+ #x091)
(defconstant +PIN-INCORRECT+ #x0a0)
(defconstant +PIN-INVALID+ #x0a1)
(defconstant +PIN-LEN-RANGE+ #x0a2)
(defconstant +PIN-EXPIRED+ #x0a3)
(defconstant +PIN-LOCKED+ #x0a4)
(defconstant +SESSION-CLOSED+ #x0b0)
(defconstant +SESSION-COUNT+ #x0b1)
(defconstant +SESSION-HANDLE-INVALID+ #x0b3)
(defconstant +SESSION-PARALLEL-NOT-SUPPORTED+ #x0b4)
(defconstant +SESSION-READ-ONLY+ #x0b5)
(defconstant +SESSION-EXISTS+ #x0b6)
(defconstant +SESSION-READ-ONLY-EXISTS+ #x0b7)
(defconstant +SESSION-READ-WRITE-SO-EXISTS+ #x0b8)
(defconstant +SIGNATURE-INVALID+ #x0c0)
(defconstant +SIGNATURE-LEN-RANGE+ #x0c1)
(defconstant +TEMPLATE-INCOMPLETE+ #x0d0)
(defconstant +TEMPLATE-INCONSISTENT+ #x0d1)
(defconstant +TOKEN-NOT-PRESENT+ #x0e0)
(defconstant +TOKEN-NOT-RECOGNIZED+ #x0e1)
(defconstant +TOKEN-WRITE-PROTECTED+ #x0e2)
(defconstant +UNWRAPPING-KEY-HANDLE-INVALID+ #x0f0)
(defconstant +UNWRAPPING-KEY-SIZE-RANGE+ #x0f1)
(defconstant +UNWRAPPING-KEY-TYPE-INCONSISTENT+ #x0f2)
(defconstant +USER-ALREADY-LOGGED-IN+ #x100)
(defconstant +USER-NOT-LOGGED-IN+ #x101)
(defconstant +USER-PIN-NOT-INITIALIZED+ #x102)
(defconstant +USER-TYPE-INVALID+ #x103)
(defconstant +USER-ANOTHER-ALREADY-LOGGED-IN+ #x104)
(defconstant +USER-TOO-MANY-TYPES+ #x105)
(defconstant +WRAPPED-KEY-INVALID+ #x110)
(defconstant +WRAPPED-KEY-LEN-RANGE+ #x112)
(defconstant +WRAPPING-KEY-HANDLE-INVALID+ #x113)
(defconstant +WRAPPING-KEY-SIZE-RANGE+ #x114)
(defconstant +WRAPPING-KEY-TYPE-INCONSISTENT+ #x115)
(defconstant +RANDOM-SEED-NOT-SUPPORTED+ #x120)
(defconstant +RANDOM-NO-RNG+ #x121)
(defconstant +DOMAIN-PARAMS-INVALID+ #x130)
(defconstant +BUFFER-TOO-SMALL+ #x150)
(defconstant +SAVED-STATE-INVALID+ #x160)
(defconstant +INFORMATION-SENSITIVE+ #x170)
(defconstant +STATE-UNSAVEABLE+ #x180)
(defconstant +CRYPTOKI-NOT-INITIALIZED+ #x190)
(defconstant +CRYPTOKI-ALREADY-INITIALIZED+ #x191)
(defconstant +MUTEX-BAD+ #x1a0)
(defconstant +MUTEX-NOT-LOCKED+ #x1a1)
(defconstant +FUNCTION-REJECTED+ #x200)
;; +VENDOR-DEFINED+
(defctype notification :ulong)
(defctype slot-id :ulong)
(defconstant +surrender+ 0)
(defctype notify :pointer)
;; typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session, ck_notification_t event, void *application);
(defcstruct info
(cryptoki-version (:struct version))
(manufacturer-id :uchar :count 32)
(flags flags)
(library-description :uchar :count 32)
(library-version (:struct version)))
(defcstruct slot-info
(slot-description :uchar :count 64)
(manufacturer-id :uchar :count 32)
(flags flags)
(hardware-version (:struct version))
(firmware-version (:struct version)))
(defconstant +token-present+ (ash 1 0))
(defconstant +removable-device+ (ash 1 1))
(defconstant +hw-slot+ (ash 1 2))
(defconstant +array-attribute+ (ash 1 30))
(defcstruct token-info
(label :uchar :count 32)
(manufacturer-id :uchar :count 32)
(model :uchar :count 16)
(serial-number :uchar :count 16)
(flags flags)
(max-session-count :ulong)
(session-count :ulong)
(max-rw-session-count :ulong)
(rw-session-count :ulong)
(max-pin-len :ulong)
(min-pin-len :ulong)
(total-public-memory :ulong)
(free-public-memory :ulong)
(total-private-mmeory :ulong)
(free-private-memory :ulong)
(hardware-version (:struct version))
(firmware-version (:struct version))
(utc-time :uchar :count 16))
(defconstant +RNG+ (ash 1 0))
(defconstant +WRITE-PROTECTED+ (ash 1 1))
(defconstant +LOGIN-REQUIRED+ (ash 1 2))
(defconstant +USER-PIN-INITIALIZED+ (ash 1 3))
(defconstant +RESTORE-KEY-NOT-NEEDED+ (ash 1 5))
(defconstant +CLOCK-ON-TOKEN+ (ash 1 6))
(defconstant +PROTECTED-AUTHENTICATION-PATH+ (ash 1 8))
(defconstant +DUAL-CRYPTO-OPERATIONS+ (ash 1 9))
(defconstant +TOKEN-INITIALIZED+ (ash 1 10))
(defconstant +SECONDARY-AUTHENTICATION+ (ash 1 11))
(defconstant +USER-PIN-COUNT-LOW+ (ash 1 16))
(defconstant +USER-PIN-FINAL-TRY+ (ash 1 17))
(defconstant +USER-PIN-LOCKED+ (ash 1 18))
(defconstant +USER-PIN-TO-BE-CHANGED+ (ash 1 19))
(defconstant +SO-PIN-COUNT-LOW+ (ash 1 20))
(defconstant +SO-PIN-FINAL-TRY+ (ash 1 21))
(defconstant +SO-PIN-LOCKED+ (ash 1 22))
(defconstant +SO-PIN-TO-BE-CHANGED+ (ash 1 23))
(defconstant +unavailable-information+
#+(or (and ccl 64-bit-host))
(- (expt 2 64) 1)
#+(or (and ccl 32-bit-host))
(- (expt 2 32) 1))
(defconstant +effectively-infinite+ 0)
(defctype session-handle :ulong)
(defconstant +invalid-handle+ 0)
(defctype user-type :ulong)
(defconstant +so+ 0)
(defconstant +user+ 1)
(defconstant +context-specific+ 2)
(defctype state :ulong)
(defconstant +RO-PUBLIC-SESSION+ 0)
(defconstant +RO-USER-FUNCTIONS+ 1)
(defconstant +RW-PUBLIC-SESSION+ 2)
(defconstant +RW-USER-FUNCTIONS+ 3)
(defconstant +RW-SO-FUNCTIONS+ 4)
(defcstruct session-info
(slot-id slot-id)
(state state)
(flags flags)
(device-error :ulong))
(defconstant +RW-SESSION+ (ash 1 1))
(defconstant +SERIAL-SESSION+ (ash 1 2))
(defctype object-handle :ulong)
(defctype object-class :ulong)
(defconstant +O-DATA+ 0)
(defconstant +O-CERTIFICATE+ 1)
(defconstant +O-PUBLIC-KEY+ 2)
(defconstant +O-PRIVATE-KEY+ 3)
(defconstant +O-SECRET-KEY+ 4)
(defconstant +O-HW-FEATURE+ 5)
(defconstant +O-DOMAIN-PARAMETERS+ 6)
(defconstant +O-MECHANISM+ 7)
(defconstant +VENDOR-DEFINED+ (ash 1 31))
(defctype hw-feature-type :ulong)
(defconstant +H-MONOTONIC-COUNTER+ 1)
(defconstant +H-CLOCK+ 2)
(defconstant +H-USER-INTERFACE+ 3)
;; +vendor-defined+
(defctype key-type :ulong)
(defconstant +K-RSA+ #x00)
(defconstant +K-DSA+ #x01)
(defconstant +K-DH+ #x02)
(defconstant +K-ECDSA+ #x03)
(defconstant +K-EC+ #x03)
(defconstant +K-X9-42-DH+ #x04)
(defconstant +K-KEA+ #x05)
(defconstant +K-GENERIC-SECRET+ #x10)
(defconstant +K-RC2+ #x11)
(defconstant +K-RC4+ #x12)
(defconstant +K-DES+ #x13)
(defconstant +K-DES2+ #x14)
(defconstant +K-DES3+ #x15)
(defconstant +K-CAST+ #x16)
(defconstant +K-CAST3+ #x17)
(defconstant +K-CAST128+ #x18)
(defconstant +K-RC5+ #x19)
(defconstant +K-IDEA+ #x1a)
(defconstant +K-SKIPJACK+ #x1b)
(defconstant +K-BATON+ #x1c)
(defconstant +K-JUNIPER+ #x1d)
(defconstant +K-CDMF+ #x1e)
(defconstant +K-AES+ #x1f)
(defconstant +K-BLOWFISH+ #x20)
(defconstant +K-TWOFISH+ #x21)
;; +vendor-defined+
(defctype certificate-type :ulong)
(defconstant +C-X-509+ 0)
(defconstant +C-X-509-ATTR-CERT+ 1)
(defconstant +C-WTLS+ 2)
;; +vendor-defined+
(defctype attribute-type :ulong)
(defconstant +A-CLASS+ #x000)
(defconstant +A-TOKEN+ #x001)
(defconstant +A-PRIVATE+ #x002)
(defconstant +A-LABEL+ #x003)
(defconstant +A-APPLICATION+ #x010)
(defconstant +A-VALUE+ #x011)
(defconstant +A-OBJECT-ID+ #x012)
(defconstant +A-CERTIFICATE-TYPE+ #x080)
(defconstant +A-ISSUER+ #x081)
(defconstant +A-SERIAL-NUMBER+ #x082)
(defconstant +A-AC-ISSUER+ #x083)
(defconstant +A-OWNER+ #x084)
(defconstant +A-ATTR-TYPES+ #x085)
(defconstant +A-TRUSTED+ #x086)
(defconstant +A-CERTIFICATE-CATEGORY+ #x087)
(defconstant +A-JAVA-MIDP-SECURITY-DOMAIN+ #x088)
(defconstant +A-URL+ #x089)
(defconstant +A-HASH-OF-SUBJECT-PUBLIC-KEY+ #x08a)
(defconstant +A-HASH-OF-ISSUER-PUBLIC-KEY+ #x08b)
(defconstant +A-CHECK-VALUE+ #x090)
(defconstant +A-KEY-TYPE+ #x100)
(defconstant +A-SUBJECT+ #x101)
(defconstant +A-ID+ #x102)
(defconstant +A-SENSITIVE+ #x103)
(defconstant +A-ENCRYPT+ #x104)
(defconstant +A-DECRYPT+ #x105)
(defconstant +A-WRAP+ #x106)
(defconstant +A-UNWRAP+ #x107)
(defconstant +A-SIGN+ #x108)
(defconstant +A-SIGN-RECOVER+ #x109)
(defconstant +A-VERIFY+ #x10a)
(defconstant +A-VERIFY-RECOVER+ #x10b)
(defconstant +A-DERIVE+ #x10c)
(defconstant +A-START-DATE+ #x110)
(defconstant +A-END-DATE+ #x111)
(defconstant +A-MODULUS+ #x120)
(defconstant +A-MODULUS-BITS+ #x121)
(defconstant +A-PUBLIC-EXPONENT+ #x122)
(defconstant +A-PRIVATE-EXPONENT+ #x123)
(defconstant +A-PRIME-1+ #x124)
(defconstant +A-PRIME-2+ #x125)
(defconstant +A-EXPONENT-1+ #x126)
(defconstant +A-EXPONENT-2+ #x127)
(defconstant +A-COEFFICIENT+ #x128)
(defconstant +A-PRIME+ #x130)
(defconstant +A-SUBPRIME+ #x131)
(defconstant +A-BASE+ #x132)
(defconstant +A-PRIME-BITS+ #x133)
(defconstant +A-SUB-PRIME-BITS+ #x134)
(defconstant +A-VALUE-BITS+ #x160)
(defconstant +A-VALUE-LEN+ #x161)
(defconstant +A-EXTRACTABLE+ #x162)
(defconstant +A-LOCAL+ #x163)
(defconstant +A-NEVER-EXTRACTABLE+ #x164)
(defconstant +A-ALWAYS-SENSITIVE+ #x165)
(defconstant +A-KEY-GEN-MECHANISM+ #x166)
(defconstant +A-MODIFIABLE+ #x170)
(defconstant +A-ECDSA-PARAMS+ #x180)
(defconstant +A-EC-PARAMS+ #x180)
(defconstant +A-EC-POINT+ #x181)
(defconstant +A-SECONDARY-AUTH+ #x200)
(defconstant +A-AUTH-PIN-FLAGS+ #x201)
(defconstant +A-ALWAYS-AUTHENTICATE+ #x202)
(defconstant +A-WRAP-WITH-TRUSTED+ #x210)
(defconstant +A-HW-FEATURE-TYPE+ #x300)
(defconstant +A-RESET-ON-INIT+ #x301)
(defconstant +A-HAS-RESET+ #x302)
(defconstant +A-PIXEL-X+ #x400)
(defconstant +A-PIXEL-Y+ #x401)
(defconstant +A-RESOLUTION+ #x402)
(defconstant +A-CHAR-ROWS+ #x403)
(defconstant +A-CHAR-COLUMNS+ #x404)
(defconstant +A-COLOR+ #x405)
(defconstant +A-BITS-PER-PIXEL+ #x406)
(defconstant +A-CHAR-SETS+ #x480)
(defconstant +A-ENCODING-METHODS+ #x481)
(defconstant +A-MIME-TYPES+ #x482)
(defconstant +A-MECHANISM-TYPE+ #x500)
(defconstant +A-REQUIRED-CMS-ATTRIBUTES+ #x501)
(defconstant +A-DEFAULT-CMS-ATTRIBUTES+ #x502)
(defconstant +A-SUPPORTED-CMS-ATTRIBUTES+ #x503)
(defconstant +A-WRAP-TEMPLATE+ (logior +ARRAY-ATTRIBUTE+ #x211))
(defconstant +A-UNWRAP-TEMPLATE+ (logior +ARRAY-ATTRIBUTE+ #x212))
(defconstant +A-ALLOWED-MECHANISMS+ (logior +ARRAY-ATTRIBUTE+ #x600))
;; +vendor-defined+
(defcstruct attribute
(type attribute-type)
(value :pointer)
(value-len :ulong))
(defcstruct date
(year :uchar :count 4)
(month :uchar :count 2)
(day :uchar :count 2))
(defctype mechanism-type :ulong)
(defconstant +M-RSA-PKCS-KEY-PAIR-GEN+ #x0000)
(defconstant +M-RSA-PKCS+ #x0001)
(defconstant +M-RSA-9796+ #x0002)
(defconstant +M-RSA-X-509+ #x0003)
(defconstant +M-MD2-RSA-PKCS+ #x0004)
(defconstant +M-MD5-RSA-PKCS+ #x0005)
(defconstant +M-SHA1-RSA-PKCS+ #x0006)
(defconstant +M-RIPEMD128-RSA-PKCS+ #x0007)
(defconstant +M-RIPEMD160-RSA-PKCS+ #x0008)
(defconstant +M-RSA-PKCS-OAEP+ #x0009)
(defconstant +M-RSA-X9-31-KEY-PAIR-GEN+ #x000a)
(defconstant +M-RSA-X9-31+ #x000b)
(defconstant +M-SHA1-RSA-X9-31+ #x000c)
(defconstant +M-RSA-PKCS-PSS+ #x000d)
(defconstant +M-SHA1-RSA-PKCS-PSS+ #x000e)
(defconstant +M-DSA-KEY-PAIR-GEN+ #x0010)
(defconstant +M-DSA+ #x0011)
(defconstant +M-DSA-SHA1+ #x0012)
(defconstant +M-DH-PKCS-KEY-PAIR-GEN+ #x0020)
(defconstant +M-DH-PKCS-DERIVE+ #x0021)
(defconstant +M-X9-42-DH-KEY-PAIR-GEN+ #x0030)
(defconstant +M-X9-42-DH-DERIVE+ #x0031)
(defconstant +M-X9-42-DH-HYBRID-DERIVE+ #x0032)
(defconstant +M-X9-42-MQV-DERIVE+ #x0033)
(defconstant +M-SHA256-RSA-PKCS+ #x0040)
(defconstant +M-SHA384-RSA-PKCS+ #x0041)
(defconstant +M-SHA512-RSA-PKCS+ #x0042)
(defconstant +M-SHA256-RSA-PKCS-PSS+ #x0043)
(defconstant +M-SHA384-RSA-PKCS-PSS+ #x0044)
(defconstant +M-SHA512-RSA-PKCS-PSS+ #x0045)
(defconstant +M-RC2-KEY-GEN+ #x0100)
(defconstant +M-RC2-ECB+ #x0101)
(defconstant +M-RC2-CBC+ #x0102)
(defconstant +M-RC2-MAC+ #x0103)
(defconstant +M-RC2-MAC-GENERAL+ #x0104)
(defconstant +M-RC2-CBC-PAD+ #x0105)
(defconstant +M-RC4-KEY-GEN+ #x0110)
(defconstant +M-RC4+ #x0111)
(defconstant +M-DES-KEY-GEN+ #x0120)
(defconstant +M-DES-ECB+ #x0121)
(defconstant +M-DES-CBC+ #x0122)
(defconstant +M-DES-MAC+ #x0123)
(defconstant +M-DES-MAC-GENERAL+ #x0124)
(defconstant +M-DES-CBC-PAD+ #x0125)
(defconstant +M-DES2-KEY-GEN+ #x0130)
(defconstant +M-DES3-KEY-GEN+ #x0131)
(defconstant +M-DES3-ECB+ #x0132)
(defconstant +M-DES3-CBC+ #x0133)
(defconstant +M-DES3-MAC+ #x0134)
(defconstant +M-DES3-MAC-GENERAL+ #x0135)
(defconstant +M-DES3-CBC-PAD+ #x0136)
(defconstant +M-CDMF-KEY-GEN+ #x0140)
(defconstant +M-CDMF-ECB+ #x0141)
(defconstant +M-CDMF-CBC+ #x0142)
(defconstant +M-CDMF-MAC+ #x0143)
(defconstant +M-CDMF-MAC-GENERAL+ #x0144)
(defconstant +M-CDMF-CBC-PAD+ #x0145)
(defconstant +M-MD2+ #x0200)
(defconstant +M-MD2-HMAC+ #x0201)
(defconstant +M-MD2-HMAC-GENERAL+ #x0202)
(defconstant +M-MD5+ #x0210)
(defconstant +M-MD5-HMAC+ #x0211)
(defconstant +M-MD5-HMAC-GENERAL+ #x0212)
(defconstant +M-SHA-1+ #x0220)
(defconstant +M-SHA-1-HMAC+ #x0221)
(defconstant +M-SHA-1-HMAC-GENERAL+ #x0222)
(defconstant +M-RIPEMD128+ #x0230)
(defconstant +M-RIPEMD128-HMAC+ #x0231)
(defconstant +M-RIPEMD128-HMAC-GENERAL+ #x0232)
(defconstant +M-RIPEMD160+ #x0240)
(defconstant +M-RIPEMD160-HMAC+ #x0241)
(defconstant +M-RIPEMD160-HMAC-GENERAL+ #x0242)
(defconstant +M-SHA256+ #x0250)
(defconstant +M-SHA256-HMAC+ #x0251)
(defconstant +M-SHA256-HMAC-GENERAL+ #x0252)
(defconstant +M-SHA384+ #x0260)
(defconstant +M-SHA384-HMAC+ #x0261)
(defconstant +M-SHA384-HMAC-GENERAL+ #x0262)
(defconstant +M-SHA512+ #x0270)
(defconstant +M-SHA512-HMAC+ #x0271)
(defconstant +M-SHA512-HMAC-GENERAL+ #x0272)
(defconstant +M-CAST-KEY-GEN+ #x0300)
(defconstant +M-CAST-ECB+ #x0301)
(defconstant +M-CAST-CBC+ #x0302)
(defconstant +M-CAST-MAC+ #x0303)
(defconstant +M-CAST-MAC-GENERAL+ #x0304)
(defconstant +M-CAST-CBC-PAD+ #x0305)
(defconstant +M-CAST3-KEY-GEN+ #x0310)
(defconstant +M-CAST3-ECB+ #x0311)
(defconstant +M-CAST3-CBC+ #x0312)
(defconstant +M-CAST3-MAC+ #x0313)
(defconstant +M-CAST3-MAC-GENERAL+ #x0314)
(defconstant +M-CAST3-CBC-PAD+ #x0315)
(defconstant +M-CAST5-KEY-GEN+ #x0320)
(defconstant +M-CAST128-KEY-GEN+ #x0320)
(defconstant +M-CAST5-ECB+ #x0321)
(defconstant +M-CAST128-ECB+ #x0321)
(defconstant +M-CAST5-CBC+ #x0322)
(defconstant +M-CAST128-CBC+ #x0322)
(defconstant +M-CAST5-MAC+ #x0323)
(defconstant +M-CAST128-MAC+ #x0323)
(defconstant +M-CAST5-MAC-GENERAL+ #x0324)
(defconstant +M-CAST128-MAC-GENERAL+ #x0324)
(defconstant +M-CAST5-CBC-PAD+ #x0325)
(defconstant +M-CAST128-CBC-PAD+ #x0325)
(defconstant +M-RC5-KEY-GEN+ #x0330)
(defconstant +M-RC5-ECB+ #x0331)
(defconstant +M-RC5-CBC+ #x0332)
(defconstant +M-RC5-MAC+ #x0333)
(defconstant +M-RC5-MAC-GENERAL+ #x0334)
(defconstant +M-RC5-CBC-PAD+ #x0335)
(defconstant +M-IDEA-KEY-GEN+ #x0340)
(defconstant +M-IDEA-ECB+ #x0341)
(defconstant +M-IDEA-CBC+ #x0342)
(defconstant +M-IDEA-MAC+ #x0343)
(defconstant +M-IDEA-MAC-GENERAL+ #x0344)
(defconstant +M-IDEA-CBC-PAD+ #x0345)
(defconstant +M-GENERIC-SECRET-KEY-GEN+ #x0350)
(defconstant +M-CONCATENATE-BASE-AND-KEY+ #x0360)
(defconstant +M-CONCATENATE-BASE-AND-DATA+ #x0362)
(defconstant +M-CONCATENATE-DATA-AND-BASE+ #x0363)
(defconstant +M-XOR-BASE-AND-DATA+ #x0364)
(defconstant +M-EXTRACT-KEY-FROM-KEY+ #x0365)
(defconstant +M-SSL3-PRE-MASTER-KEY-GEN+ #x0370)
(defconstant +M-SSL3-MASTER-KEY-DERIVE+ #x0371)
(defconstant +M-SSL3-KEY-AND-MAC-DERIVE+ #x0372)
(defconstant +M-SSL3-MASTER-KEY-DERIVE-DH+ #x0373)
(defconstant +M-TLS-PRE-MASTER-KEY-GEN+ #x0374)
(defconstant +M-TLS-MASTER-KEY-DERIVE+ #x0375)
(defconstant +M-TLS-KEY-AND-MAC-DERIVE+ #x0376)
(defconstant +M-TLS-MASTER-KEY-DERIVE-DH+ #x0377)
(defconstant +M-SSL3-MD5-MAC+ #x0380)
(defconstant +M-SSL3-SHA1-MAC+ #x0381)
(defconstant +M-MD5-KEY-DERIVATION+ #x0390)
(defconstant +M-MD2-KEY-DERIVATION+ #x0391)
(defconstant +M-SHA1-KEY-DERIVATION+ #x0392)
(defconstant +M-PBE-MD2-DES-CBC+ #x03a0)
(defconstant +M-PBE-MD5-DES-CBC+ #x03a1)
(defconstant +M-PBE-MD5-CAST-CBC+ #x03a2)
(defconstant +M-PBE-MD5-CAST3-CBC+ #x03a3)
(defconstant +M-PBE-MD5-CAST5-CBC+ #x03a4)
(defconstant +M-PBE-MD5-CAST128-CBC+ #x03a4)
(defconstant +M-PBE-SHA1-CAST5-CBC+ #x03a5)
(defconstant +M-PBE-SHA1-CAST128-CBC+ #x03a5)
(defconstant +M-PBE-SHA1-RC4-128+ #x03a6)
(defconstant +M-PBE-SHA1-RC4-40+ #x03a7)
(defconstant +M-PBE-SHA1-DES3-EDE-CBC+ #x03a8)
(defconstant +M-PBE-SHA1-DES2-EDE-CBC+ #x03a9)
(defconstant +M-PBE-SHA1-RC2-128-CBC+ #x03aa)
(defconstant +M-PBE-SHA1-RC2-40-CBC+ #x03ab)
(defconstant +M-PKCS5-PBKD2+ #x03b0)
(defconstant +M-PBA-SHA1-WITH-SHA1-HMAC+ #x03c0)
(defconstant +M-KEY-WRAP-LYNKS+ #x0400)
(defconstant +M-KEY-WRAP-SET-OAEP+ #x0401)
(defconstant +M-SKIPJACK-KEY-GEN+ #x1000)
(defconstant +M-SKIPJACK-ECB64+ #x1001)
(defconstant +M-SKIPJACK-CBC64+ #x1002)
(defconstant +M-SKIPJACK-OFB64+ #x1003)
(defconstant +M-SKIPJACK-CFB64+ #x1004)
(defconstant +M-SKIPJACK-CFB32+ #x1005)
(defconstant +M-SKIPJACK-CFB16+ #x1006)
(defconstant +M-SKIPJACK-CFB8+ #x1007)
(defconstant +M-SKIPJACK-WRAP+ #x1008)
(defconstant +M-SKIPJACK-PRIVATE-WRAP+ #x1009)
(defconstant +M-SKIPJACK-RELAYX+ #x100a)
(defconstant +M-KEA-KEY-PAIR-GEN+ #x1010)
(defconstant +M-KEA-KEY-DERIVE+ #x1011)
(defconstant +M-FORTEZZA-TIMESTAMP+ #x1020)
(defconstant +M-BATON-KEY-GEN+ #x1030)
(defconstant +M-BATON-ECB128+ #x1031)
(defconstant +M-BATON-ECB96+ #x1032)
(defconstant +M-BATON-CBC128+ #x1033)
(defconstant +M-BATON-COUNTER+ #x1034)
(defconstant +M-BATON-SHUFFLE+ #x1035)
(defconstant +M-BATON-WRAP+ #x1036)
(defconstant +M-ECDSA-KEY-PAIR-GEN+ #x1040)
(defconstant +M-EC-KEY-PAIR-GEN+ #x1040)
(defconstant +M-ECDSA+ #x1041)
(defconstant +M-ECDSA-SHA1+ #x1042)
(defconstant +M-ECDH1-DERIVE+ #x1050)
(defconstant +M-ECDH1-COFACTOR-DERIVE+ #x1051)
(defconstant +M-ECMQV-DERIVE+ #x1052)
(defconstant +M-JUNIPER-KEY-GEN+ #x1060)
(defconstant +M-JUNIPER-ECB128+ #x1061)
(defconstant +M-JUNIPER-CBC128+ #x1062)
(defconstant +M-JUNIPER-COUNTER+ #x1063)
(defconstant +M-JUNIPER-SHUFFLE+ #x1064)
(defconstant +M-JUNIPER-WRAP+ #x1065)
(defconstant +M-FASTHASH+ #x1070)
(defconstant +M-AES-KEY-GEN+ #x1080)
(defconstant +M-AES-ECB+ #x1081)
(defconstant +M-AES-CBC+ #x1082)
(defconstant +M-AES-MAC+ #x1083)
(defconstant +M-AES-MAC-GENERAL+ #x1084)
(defconstant +M-AES-CBC-PAD+ #x1085)
(defconstant +M-DSA-PARAMETER-GEN+ #x2000)
(defconstant +M-DH-PKCS-PARAMETER-GEN+ #x2001)
(defconstant +M-X9-42-DH-PARAMETER-GEN+ #x2002)
;; +VENDOR-DEFINED+
(defcstruct mechanism
(mechanism mechanism-type)
(parameter :pointer)
(parameter-len :ulong))
(defcstruct mechanism-info
(min-key-size :ulong)
(max-key-size :ulong)
(flags flags))
(defconstant +F-HW+ (ash 1 0))
(defconstant +F-ENCRYPT+ (ash 1 8))
(defconstant +F-DECRYPT+ (ash 1 9))
(defconstant +F-DIGEST+ (ash 1 10))
(defconstant +F-SIGN+ (ash 1 11))
(defconstant +F-SIGN-RECOVER+ (ash 1 12))
(defconstant +F-VERIFY+ (ash 1 13))
(defconstant +F-VERIFY-RECOVER+ (ash 1 14))
(defconstant +F-GENERATE+ (ash 1 15))
(defconstant +F-GENERATE-KEY-PAIR+ (ash 1 16))
(defconstant +F-WRAP+ (ash 1 17))
(defconstant +F-UNWRAP+ (ash 1 18))
(defconstant +F-DERIVE+ (ash 1 19))
(defconstant +F-EXTENSION+ (ash 1 31))
;; Flags for C-WaitForSlotEvent.
(defconstant +DONT-BLOCK+ 1)
(defcfun (initialize "C_Initialize") rv (init-args :pointer))
(defcfun (finalize "C_Finalize") rv (reserved :pointer))
(defcfun (get-info "C_GetInfo") rv (info (:pointer (:struct info))))
(defcfun (get-slot-list "C_GetSlotList") rv
(token-present :uchar)
(slot-list (:pointer slot-id))
(count (:pointer :ulong)))
(defcfun (get-slot-info "C_GetSlotInfo") rv
(slot-id slot-id)
(info (:pointer (:struct slot-info))))
(defcfun (get-token-info "C_GetTokenInfo") rv
(slot-id slot-id)
(info (:pointer (:struct token-info))))
(defcfun (wait-for-slot-event "C_WaitForSlotEvent") rv
(flags flags)
(slot (:pointer slot-id))
(reserved :pointer))
(defcfun (get-mechanism-list "C_GetMechanismList") rv
(slot-id slot-id)
(mechanism-list (:pointer mechanism-type)) (count (:pointer :ulong)))
(defcfun (get-mechanism-info "C_GetMechanismInfo") rv
(slot-id slot-id)
(type mechanism-type)
(info (:pointer (:struct mechanism-info))))
(defcfun (init-token "C_InitToken") rv
(slot-id slot-id)
(pin (:pointer :uchar))
(pin-len :ulong)
(label (:pointer :uchar)))
(defcfun (init-pin "C_InitPIN") rv
(session session-handle)
(pin (:pointer :uchar))
(pin-len :ulong))
(defcfun (set-pin "C_SetPIN") rv
(session session-handle)
(old-pin (:pointer :uchar))
(old-len :ulong)
(new-pin (:pointer :uchar))
(new-len :ulong))
(defcfun (open-session "C_OpenSession") rv
(slot-id slot-id)
(flags flags)
(application :pointer)
(notify notify)
(session (:pointer session-handle)))
(defcfun (close-session "C_CloseSession") rv
(session session-handle))
(defcfun (close-all-sessions "C_CloseAllSessions") rv
(slot-id slot-id))
(defcfun (get-session-info "C_GetSessionInfo") rv
(session session-handle)
(info (:pointer (:struct session-info))))
(defcfun (get-operation-state "C_GetOperationState") rv
(session session-handle)
(operation-state (:pointer :uchar))
(operation-state-len (:pointer :ulong)))
(defcfun (set-operation-state "C_SetOperationState") rv
(session session-handle)
(operation-state (:pointer :uchar))
(operation-state-len :ulong)
(encryption-key object-handle)
(authentication-key object-handle))
(defcfun (login "C_Login") rv
(session session-handle)
(user-type user-type)
(pin (:pointer :uchar))
(pin-len :ulong))
(defcfun (logout "C_Logout") rv
(session session-handle))
(defcfun (create-object "C_CreateObject") rv
(session session-handle)
(templ (:pointer (:struct attribute)))
(count :ulong)
(object (:pointer object-handle)))
(defcfun (copy-object "C_CopyObject") rv
(session session-handle)
(object object-handle)
(templ (:pointer (:struct attribute)))
(count :ulong)
(new-object (:pointer object-handle)))
(defcfun (destroy-object "C_DestroyObject") rv
(session session-handle)
(object object-handle))
(defcfun (get-object-size "C_GetObjectSize") rv
(session session-handle)
(object object-handle)
(size (:pointer :ulong)))
(defcfun (get-attribute-value "C_GetAttributeValue") rv
(session session-handle)
(object object-handle)
(templ (:pointer (:struct attribute)))
(count :ulong))
(defcfun (set-attribute-value "C_SetAttributeValue") rv
(session session-handle)
(object object-handle)
(templ (:pointer (:struct attribute)))
(count :ulong))
(defcfun (find-objects-init "C_FindObjectsInit") rv
(session session-handle)
(templ (:pointer (:struct attribute)))
(count :ulong))
(defcfun (find-objects "C_FindObjects") rv
(session session-handle)
(object (:pointer object-handle))
(max-object-count :ulong)
(object-count (:pointer :ulong)))
(defcfun (find-objects-final "C_FindObjectsFinal") rv (session session-handle))
(defcfun (encrypt-init "C_EncryptInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (encrypt "C_Encrypt") rv
(session session-handle)
(data (:pointer :uchar))
(data-len :ulong)
(encrypted-data (:pointer :uchar))
(encrypted-data-len (:pointer :ulong)))
(defcfun (encrypt-update "C_EncryptUpdate") rv
(session session-handle)
(part (:pointer :uchar))
(part-len :ulong)
(encrypted-part (:pointer :uchar))
(encrypted-part-len (:pointer :ulong)))
(defcfun (encrypt-final "C_EncryptFinal") rv
(session session-handle)
(last-encrypted-part (:pointer :uchar))
(last-encrypted-part-len (:pointer :ulong)))
(defcfun (decrypt-init "C_DecryptInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (decrypt "C_Decrypt") rv
(session session-handle)
(encrypted-data (:pointer :uchar))
(encrypted-data-len :ulong)
(data (:pointer :uchar))
(data-len (:pointer :ulong)))
(defcfun (decrypt-update "C_DecryptUpdate") rv
(session session-handle)
(encrypted-part (:pointer :uchar))
(encrypted-part-len :ulong)
(part (:pointer :uchar))
(part-len (:pointer :ulong)))
(defcfun (decrypt-final "C_DecryptFinal") rv
(session session-handle)
(last-part (:pointer :uchar))
(last-part-len (:pointer :ulong)))
(defcfun (digest-init "C_DigestInit") rv (session session-handle) (mechanism (:pointer (:struct mechanism))))
(defcfun (digest "C_Digest") rv
(session session-handle)
(data (:pointer :uchar))
(data-len :ulong)
(digest (:pointer :uchar))
(digest-len (:pointer :ulong)))
(defcfun (digest-update "C_DigestUpdate") rv (session session-handle) (part (:pointer :uchar)) (part-len :ulong))
(defcfun (digest-key "C_DigestKey") rv (session session-handle) (key object-handle))
(defcfun (digest-final "C_DigestFinal") rv
(session session-handle)
(digest (:pointer :uchar))
(digest-len (:pointer :ulong)))
(defcfun (sign-init "C_SignInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (sign "C_Sign") rv
(session session-handle)
(data (:pointer :uchar))
(data-len :ulong)
(signature (:pointer :uchar))
(signature-len (:pointer :ulong)))
(defcfun (sign-update "C_SignUpdate") rv
(session session-handle)
(part (:pointer :uchar))
(part-len :ulong))
(defcfun (sign-final "C_SignFinal") rv
(session session-handle)
(signature (:pointer :uchar))
(signature-len (:pointer :ulong)))
(defcfun (sign-recover-init "C_SignRecoverInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (sign-recover "C_SignRecover") rv
(session session-handle)
(data (:pointer :uchar))
(data-len :ulong)
(signature (:pointer :uchar))
(signature-len (:pointer :ulong)))
(defcfun (verify-init "C_VerifyInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (verify "C_Verify") rv
(session session-handle)
(data (:pointer :uchar))
(data-len :ulong)
(signature (:pointer :uchar))
(signature-len :ulong))
(defcfun (verify-update "C_VerifyUpdate") rv
(session session-handle)
(part (:pointer :uchar))
(part-len :ulong))
(defcfun (verify-final "C_VerifyFinal") rv
(session session-handle)
(signature (:pointer :uchar))
(signature-len :ulong))
(defcfun (verify-recover-init "C_VerifyRecoverInit") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(key object-handle))
(defcfun (verify-recover "C_VerifyRecover") rv
(session session-handle)
(signature (:pointer :uchar))
(signature-len :ulong)
(data (:pointer :uchar))
(data-len (:pointer :ulong)))
(defcfun (digest-encrypt-update "C_DigestEncryptUpdate") rv
(session session-handle)
(part (:pointer :uchar))
(part-len :ulong)
(encrypted-part (:pointer :uchar))
(encrypted-part-len (:pointer :ulong)))
(defcfun (decrypt-digest-update "C_DecryptDigestUpdate") rv
(session session-handle)
(encrypted-part (:pointer :uchar))
(encrypted-part-len :ulong)
(part (:pointer :uchar))
(part-len (:pointer :ulong)))
(defcfun (sign-encrypt-update "C_SignEncryptUpdate") rv
(session session-handle)
(part (:pointer :uchar))
(part-len :ulong)
(encrypted-part (:pointer :uchar))
(encrypted-part-len (:pointer :ulong)))
(defcfun (decrypt-verify-update "C_DecryptVerifyUpdate") rv
(session session-handle)
(encrypted-part (:pointer :uchar))
(encrypted-part-len :ulong)
(part (:pointer :uchar))
(part-len (:pointer :ulong)))
(defcfun (generate-key "C_GenerateKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(templ (:pointer (:struct attribute)))
(count :ulong)
(key (:pointer object-handle)))
(defcfun (generate-key-pair "C_GenerateKeyPair") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(public-key-template (:pointer (:struct attribute)))
(public-key-attribute-count :ulong)
(private-key-template (:pointer (:struct attribute)))
(private-key-attribute-count :ulong)
(public-key (:pointer object-handle))
(private-key (:pointer object-handle)))
(defcfun (wrap-key "C_WrapKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(wrapping-key object-handle)
(key object-handle)
(wrapped-key (:pointer :uchar))
(wrapped-key-len (:pointer :ulong)))
(defcfun (unwrap-key "C_UnwrapKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(unwrapping-key object-handle)
(wrapped-key (:pointer :uchar))
(wrapped-key-len :ulong)
(templ (:pointer (:struct attribute)))
(attribute-count :ulong)
(key (:pointer object-handle)))
(defcfun (derive-key "C_DeriveKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(base-key object-handle)
(templ (:pointer (:struct attribute)))
(attribute-count :ulong)
(key (:pointer object-handle)))
(defcfun (seed-random "C_SeedRandom") rv (session session-handle) (seed (:pointer :uchar)) (seed-len :ulong))
(defcfun (generate-random "C_GenerateRandom") rv (session session-handle) (random-data (:pointer :uchar)) (random-len :ulong))
(defcfun (get-function-status "C_GetFunctionStatus") rv (session session-handle))
(defcfun (cancel-function "C_CancelFunction") rv (session session-handle))
;;;; THE END ;;;;
| 53,103 | Common Lisp | .lisp | 1,066 | 46.094747 | 136 | 0.583248 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | eb5c108147a0b3d5259727e190d66251b27e2bda3b856d7cf1a31ca53da827a1 | 4,909 | [
-1
] |
4,910 | pkcs11.lisp | informatimago_lisp/clext/pkcs11/pkcs11.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: pkcs11.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Lispy interface over Cryptoki pkcs11 version 2.02.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2018-04-18 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2018 - 2018
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.PKCS11"
(:use "COMMON-LISP" "CFFI" "BABEL")
(:use "COM.INFORMATIMAGO.CLEXT.PKCS11.CFFI-UTILS")
(:import-from "COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SYMBOL" "SCAT")
(:import-from "COM.INFORMATIMAGO.CLEXT.PKCS11.LOW" "LOAD-LIBRARY")
(:shadowing-import-from "COM.INFORMATIMAGO.CLEXT.PKCS11.CFFI-DEBUG"
"FOREIGN-ALLOC" "FOREIGN-FREE")
(:export "PKCS11-ERROR"
"PKCS11-ERROR-CODE" "PKCS11-ERROR-LABEL" "PKCS11-ERROR-FUNCTION"
"CHECK-RV" "WITH-PKCS11"
"RETURN-VALUE" "CONVERT-SLOT-INFO-FLAGS" "CONVERT-TOKEN-INFO-FLAGS"
"USER-TYPE" "STATE" "CONVERT-SESSION-INFO-FLAGS"
"CONVERT-WAIT-FOR-SLOT-EVENT-FLAGS" "OBJECT-CLASS" "HARDWARE-FEATURE"
"KEY-TYPE" "CERTIFICATE-TYPE" "ATTRIBUTE-TYPE" "MECHANISM-TYPE"
"CONVERT-MECHANISM-INFO-FLAGS" "CKBOOL" "UNAVAILABLE-INFORMATION-P"
"INVALID-POINTER-P" "VERSION" "MAKE-VERSION" "VERSION-P"
"COPY-VERSION" "VERSION-MAJOR" "VERSION-MINOR" "VERSION" "INFO"
"MAKE-INFO" "INFO-P" "COPY-INFO" "INFO-CRYPTOKI-VERSION"
"INFO-MANUFACTURER-ID" "INFO-FLAGS" "INFO-LIBRARY-DESCRIPTION"
"INFO-LIBRARY-VERSION" "GET-INFO" "GET-SLOT-LIST" "SLOT-INFO"
"MAKE-SLOT-INFO" "SLOT-INFO-P" "COPY-SLOT-INFO"
"SLOT-INFO-SLOT-DESCRIPTION" "SLOT-INFO-MANUFACTURER-ID"
"SLOT-INFO-FLAGS" "SLOT-INFO-HARDWARE-VERSION"
"SLOT-INFO-FIRMWARE-VERSION" "GET-SLOT-INFO" "TOKEN-INFO"
"MAKE-TOKEN-INFO" "TOKEN-INFO-P" "COPY-TOKEN-INFO" "TOKEN-INFO-LABEL"
"TOKEN-INFO-MANUFACTURER-ID" "TOKEN-INFO-MODEL"
"TOKEN-INFO-SERIAL-NUMBER" "TOKEN-INFO-FLAGS"
"TOKEN-INFO-MAX-SESSION-COUNT" "TOKEN-INFO-SESSION-COUNT"
"TOKEN-INFO-MAX-RW-SESSION-COUNT" "TOKEN-INFO-RW-SESSION-COUNT"
"TOKEN-INFO-MAX-PIN-LEN" "TOKEN-INFO-MIN-PIN-LEN"
"TOKEN-INFO-TOTAL-PUBLIC-MEMORY" "TOKEN-INFO-FREE-PUBLIC-MEMORY"
"TOKEN-INFO-TOTAL-PRIVATE-MMEORY" "TOKEN-INFO-FREE-PRIVATE-MEMORY"
"TOKEN-INFO-HARDWARE-VERSION" "TOKEN-INFO-FIRMWARE-VERSION"
"TOKEN-INFO-UTC-TIME" "GET-TOKEN-INFO" "WAIT-FOR-SLOT-EVENT"
"GET-MECHANISM-LIST" "MECHANISM-INFO" "MAKE-MECHANISM-INFO"
"MECHANISM-INFO-P" "COPY-MECHANISM-INFO" "MECHANISM-INFO-MIN-KEY-SIZE"
"MECHANISM-INFO-MAX-KEY-SIZE" "MECHANISM-INFO-FLAGS"
"GET-MECHANISM-INFO" "STRING-FROM-UTF-8" "INIT-TOKEN" "OPEN-SESSION"
"CLOSE-SESSION" "CLOSE-ALL-SESSIONS" "WITH-OPEN-SESSION"
"SESSION-INFO" "MAKE-SESSION-INFO" "SESSION-INFO-P"
"COPY-SESSION-INFO" "SESSION-INFO-SLOT-ID" "SESSION-INFO-STATE"
"SESSION-INFO-FLAGS" "SESSION-INFO-DEVICE-ERROR" "GET-SESSION-INFO"
"GET-OPERATION-STATE" "SET-OPERATION-STATE" "LOGIN" "LOGOUT"
"INIT-PIN" "SET-PIN" "READ-PIN" "CREATE-OBJECT" "COPY-OBJECT"
"DESTROY-OBJECT" "GET-OBJECT-SIZE" "GET-ATTRIBUTE-VALUE"
"SET-ATTRIBUTE-VALUE" "FIND-OBJECTS-INIT" "FIND-OBJECTS"
"FIND-OBJECTS-FINAL" "FIND-ALL-OBJECTS" "OBJECT-GET-ALL-ATTRIBUTES"
"OBJECT-GET-ATTRIBUTES"
"SEED-RANDOM" "GENERATE-RANDOM" "LOAD-LIBRARY"
"CALL-LOGGED-IN" "DO-LOGGED-IN")
(:documentation "Lispy interface over Cryptoki pkcs11 version 2.02
License:
AGPL3
Copyright Pascal J. Bourguignon 2018 - 2018
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program.
If not, see <http://www.gnu.org/licenses/>
"))
(in-package "COM.INFORMATIMAGO.CLEXT.PKCS11")
(deftype octet () '(unsigned-byte 8))
(defconstant +ulong-bits+ (* 8 (foreign-type-size :ulong)))
(deftype session-handle () `(unsigned-byte ,+ulong-bits+))
(deftype slot-id () `(unsigned-byte ,+ulong-bits+))
(deftype mechanismi-type () `(unsigned-byte ,+ulong-bits+))
(deftype object-handle () `(unsigned-byte ,+ulong-bits+))
(defun flags (operation flags map)
(ecase operation
((:decode)
(loop :for (flag . keyword) :in map
:when (= flag (logand flags flag))
:collect keyword))
((:encode)
(loop :for (flag . keyword) :in map
:when (member keyword flags)
:sum flag))))
(defun enum (operation value map)
(ecase operation
((:decode) (or (cdr (assoc value map)) value))
((:encode) (or (car (rassoc value map))
(error "Unknown enum keyword ~S, expected one of `{~S~^ ~}."
value (mapcar (function cdr) map))))))
(defmacro define-flag-converter (name map)
`(defun ,name (operation value)
(flags operation value (load-time-value
(list ,@(mapcar (lambda (entry)
"(ck-constant keyword) -> (cons ck-constant keyword)"
`(cons ,@entry))
map))))))
(defmacro define-enum-converter (name map)
`(defun ,name (operation value)
(enum operation value (load-time-value
(list ,@(mapcar (lambda (entry)
"(ck-constant keyword) -> (cons ck-constant keyword)"
`(cons ,@entry))
map))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Converters
(define-enum-converter return-value
((%ck:+ok+ :ok)
(%ck:+cancel+ :cancel)
(%ck:+host-memory+ :host-memory)
(%ck:+slot-id-invalid+ :slot-id-invalid)
(%ck:+general-error+ :general-error)
(%ck:+function-failed+ :function-failed)
(%ck:+arguments-bad+ :arguments-bad)
(%ck:+no-event+ :no-event)
(%ck:+need-to-create-threads+ :need-to-create-threads)
(%ck:+cant-lock+ :cant-lock)
(%ck:+attribute-read-only+ :attribute-read-only)
(%ck:+attribute-sensitive+ :attribute-sensitive)
(%ck:+attribute-type-invalid+ :attribute-type-invalid)
(%ck:+attribute-value-invalid+ :attribute-value-invalid)
(%ck:+data-invalid+ :data-invalid)
(%ck:+data-len-range+ :data-len-range)
(%ck:+device-error+ :device-error)
(%ck:+device-memory+ :device-memory)
(%ck:+device-removed+ :device-removed)
(%ck:+encrypted-data-invalid+ :encrypted-data-invalid)
(%ck:+encrypted-data-len-range+ :encrypted-data-len-range)
(%ck:+function-canceled+ :function-canceled)
(%ck:+function-not-parallel+ :function-not-parallel)
(%ck:+function-not-supported+ :function-not-supported)
(%ck:+key-handle-invalid+ :key-handle-invalid)
(%ck:+key-size-range+ :key-size-range)
(%ck:+key-type-inconsistent+ :key-type-inconsistent)
(%ck:+key-not-needed+ :key-not-needed)
(%ck:+key-changed+ :key-changed)
(%ck:+key-needed+ :key-needed)
(%ck:+key-indigestible+ :key-indigestible)
(%ck:+key-function-not-permitted+ :key-function-not-permitted)
(%ck:+key-not-wrappable+ :key-not-wrappable)
(%ck:+key-unextractable+ :key-unextractable)
(%ck:+mechanism-invalid+ :mechanism-invalid)
(%ck:+mechanism-param-invalid+ :mechanism-param-invalid)
(%ck:+object-handle-invalid+ :object-handle-invalid)
(%ck:+operation-active+ :operation-active)
(%ck:+operation-not-initialized+ :operation-not-initialized)
(%ck:+pin-incorrect+ :pin-incorrect)
(%ck:+pin-invalid+ :pin-invalid)
(%ck:+pin-len-range+ :pin-len-range)
(%ck:+pin-expired+ :pin-expired)
(%ck:+pin-locked+ :pin-locked)
(%ck:+session-closed+ :session-closed)
(%ck:+session-count+ :session-count)
(%ck:+session-handle-invalid+ :session-handle-invalid)
(%ck:+session-parallel-not-supported+ :session-parallel-not-supported)
(%ck:+session-read-only+ :session-read-only)
(%ck:+session-exists+ :session-exists)
(%ck:+session-read-only-exists+ :session-read-only-exists)
(%ck:+session-read-write-so-exists+ :session-read-write-so-exists)
(%ck:+signature-invalid+ :signature-invalid)
(%ck:+signature-len-range+ :signature-len-range)
(%ck:+template-incomplete+ :template-incomplete)
(%ck:+template-inconsistent+ :template-inconsistent)
(%ck:+token-not-present+ :token-not-present)
(%ck:+token-not-recognized+ :token-not-recognized)
(%ck:+token-write-protected+ :token-write-protected)
(%ck:+unwrapping-key-handle-invalid+ :unwrapping-key-handle-invalid)
(%ck:+unwrapping-key-size-range+ :unwrapping-key-size-range)
(%ck:+unwrapping-key-type-inconsistent+ :unwrapping-key-type-inconsistent)
(%ck:+user-already-logged-in+ :user-already-logged-in)
(%ck:+user-not-logged-in+ :user-not-logged-in)
(%ck:+user-pin-not-initialized+ :user-pin-not-initialized)
(%ck:+user-type-invalid+ :user-type-invalid)
(%ck:+user-another-already-logged-in+ :user-another-already-logged-in)
(%ck:+user-too-many-types+ :user-too-many-types)
(%ck:+wrapped-key-invalid+ :wrapped-key-invalid)
(%ck:+wrapped-key-len-range+ :wrapped-key-len-range)
(%ck:+wrapping-key-handle-invalid+ :wrapping-key-handle-invalid)
(%ck:+wrapping-key-size-range+ :wrapping-key-size-range)
(%ck:+wrapping-key-type-inconsistent+ :wrapping-key-type-inconsistent)
(%ck:+random-seed-not-supported+ :random-seed-not-supported)
(%ck:+random-no-rng+ :random-no-rng)
(%ck:+domain-params-invalid+ :domain-params-invalid)
(%ck:+buffer-too-small+ :buffer-too-small)
(%ck:+saved-state-invalid+ :saved-state-invalid)
(%ck:+information-sensitive+ :information-sensitive)
(%ck:+state-unsaveable+ :state-unsaveable)
(%ck:+cryptoki-not-initialized+ :cryptoki-not-initialized)
(%ck:+cryptoki-already-initialized+ :cryptoki-already-initialized)
(%ck:+mutex-bad+ :mutex-bad)
(%ck:+mutex-not-locked+ :mutex-not-locked)
(%ck:+function-rejected+ :function-rejected)))
(define-flag-converter convert-slot-info-flags
((%ck:+token-present+ :token-present)
(%ck:+removable-device+ :removable-device)
(%ck:+hw-slot+ :hardware-slot)
(%ck:+array-attribute+ :array-attribute)))
(define-flag-converter convert-token-info-flags
((%ck:+rng+ :rng)
(%ck:+write-protected+ :write-protected)
(%ck:+login-required+ :login-required)
(%ck:+user-pin-initialized+ :user-pin-initialized)
(%ck:+restore-key-not-needed+ :restore-key-not-needed)
(%ck:+clock-on-token+ :clock-on-token)
(%ck:+protected-authentication-path+ :protected-authentication-path)
(%ck:+dual-crypto-operations+ :dual-crypto-operations)
(%ck:+token-initialized+ :token-initialized)
(%ck:+secondary-authentication+ :secondary-authentication)
(%ck:+user-pin-count-low+ :user-pin-count-low)
(%ck:+user-pin-final-try+ :user-pin-final-try)
(%ck:+user-pin-locked+ :user-pin-locked)
(%ck:+user-pin-to-be-changed+ :user-pin-to-be-changed)
(%ck:+so-pin-count-low+ :so-pin-count-low)
(%ck:+so-pin-final-try+ :so-pin-final-try)
(%ck:+so-pin-locked+ :so-pin-locked)
(%ck:+so-pin-to-be-changed+ :so-pin-to-be-changed)))
(define-enum-converter user-type
((%ck:+so+ :so)
(%ck:+user+ :user)
(%ck:+context-specific+ :context-specific)))
(define-enum-converter state
((%ck:+ro-public-session+ :ro-public-session)
(%ck:+ro-user-functions+ :ro-user-functions)
(%ck:+rw-public-session+ :rw-public-session)
(%ck:+rw-user-functions+ :rw-user-functions)
(%ck:+rw-so-functions+ :rw-so-functions)))
(define-flag-converter convert-session-info-flags
((%ck:+rw-session+ :rw-session)
(%ck:+serial-session+ :serial-session)))
(define-flag-converter convert-wait-for-slot-event-flags
((%ck:+DONT-BLOCK+ :dont-block)))
(define-enum-converter object-class
((%ck:+o-data+ :data)
(%ck:+o-certificate+ :certificate)
(%ck:+o-public-key+ :public-key)
(%ck:+o-private-key+ :private-key)
(%ck:+o-secret-key+ :secret-key)
(%ck:+o-hw-feature+ :hw-feature)
(%ck:+o-domain-parameters+ :domain-parameters)
(%ck:+o-mechanism+ :mechanism)
(%ck:+vendor-defined+ :vendor-defined)))
(define-enum-converter hardware-feature
((%ck:+h-monotonic-counter+ :monotonic-count)
(%ck:+h-clock+ :clock)
(%ck:+h-user-interface+ :user-interface)
(%ck:+vendor-defined+ :vendor-defined)))
(define-enum-converter key-type
((%ck:+k-rsa+ :rsa)
(%ck:+k-dsa+ :dsa)
(%ck:+k-dh+ :dh)
(%ck:+k-ecdsa+ :ecdsa)
(%ck:+k-ec+ :ec)
(%ck:+k-x9-42-dh+ :x9-42-dh)
(%ck:+k-kea+ :kea)
(%ck:+k-generic-secret+ :generic-secret)
(%ck:+k-rc2+ :rc2)
(%ck:+k-rc4+ :rc4)
(%ck:+k-des+ :des)
(%ck:+k-des2+ :des2)
(%ck:+k-des3+ :des3)
(%ck:+k-cast+ :cast)
(%ck:+k-cast3+ :cast3)
(%ck:+k-cast128+ :cast128)
(%ck:+k-rc5+ :rc5)
(%ck:+k-idea+ :idea)
(%ck:+k-skipjack+ :skipjack)
(%ck:+k-baton+ :baton)
(%ck:+k-juniper+ :juniper)
(%ck:+k-cdmf+ :cdmf)
(%ck:+k-aes+ :aes)
(%ck:+k-blowfish+ :blowfish)
(%ck:+k-twofish+ :twofish)
(%ck:+vendor-defined+ :vendor-defined)))
(define-enum-converter certificate-type
((%ck:+c-x-509+ :x-509)
(%ck:+c-x-509-attr-cert+ :x-509-attr-cert)
(%ck:+c-wtls+ :wtls)
(%ck:+vendor-defined+ :vendor-defined)))
(define-enum-converter attribute-type
((%ck:+a-class+ :class)
(%ck:+a-token+ :token)
(%ck:+a-private+ :private)
(%ck:+a-label+ :label)
(%ck:+a-application+ :application)
(%ck:+a-value+ :value)
(%ck:+a-object-id+ :object-id)
(%ck:+a-certificate-type+ :certificate-type)
(%ck:+a-issuer+ :issuer)
(%ck:+a-serial-number+ :serial-number)
(%ck:+a-ac-issuer+ :ac-issuer)
(%ck:+a-owner+ :owner)
(%ck:+a-attr-types+ :attr-types)
(%ck:+a-trusted+ :trusted)
(%ck:+a-certificate-category+ :certificate-category)
(%ck:+a-java-midp-security-domain+ :java-midp-security-domain)
(%ck:+a-url+ :url)
(%ck:+a-hash-of-subject-public-key+ :hash-of-subject-public-key)
(%ck:+a-hash-of-issuer-public-key+ :hash-of-issuer-public-key)
(%ck:+a-check-value+ :check-value)
(%ck:+a-key-type+ :key-type)
(%ck:+a-subject+ :subject)
(%ck:+a-id+ :id)
(%ck:+a-sensitive+ :sensitive)
(%ck:+a-encrypt+ :encrypt)
(%ck:+a-decrypt+ :decrypt)
(%ck:+a-wrap+ :wrap)
(%ck:+a-unwrap+ :unwrap)
(%ck:+a-sign+ :sign)
(%ck:+a-sign-recover+ :sign-recover)
(%ck:+a-verify+ :verify)
(%ck:+a-verify-recover+ :verify-recover)
(%ck:+a-derive+ :derive)
(%ck:+a-start-date+ :start-date)
(%ck:+a-end-date+ :end-date)
(%ck:+a-modulus+ :modulus)
(%ck:+a-modulus-bits+ :modulus-bits)
(%ck:+a-public-exponent+ :public-exponent)
(%ck:+a-private-exponent+ :private-exponent)
(%ck:+a-prime-1+ :prime-1)
(%ck:+a-prime-2+ :prime-2)
(%ck:+a-exponent-1+ :exponent-1)
(%ck:+a-exponent-2+ :exponent-2)
(%ck:+a-coefficient+ :coefficient)
(%ck:+a-prime+ :prime)
(%ck:+a-subprime+ :subprime)
(%ck:+a-base+ :base)
(%ck:+a-prime-bits+ :prime-bits)
(%ck:+a-sub-prime-bits+ :sub-prime-bits)
(%ck:+a-value-bits+ :value-bits)
(%ck:+a-value-len+ :value-len)
(%ck:+a-extractable+ :extractable)
(%ck:+a-local+ :local)
(%ck:+a-never-extractable+ :never-extractable)
(%ck:+a-always-sensitive+ :always-sensitive)
(%ck:+a-key-gen-mechanism+ :key-gen-mechanism)
(%ck:+a-modifiable+ :modifiable)
(%ck:+a-ecdsa-params+ :ecdsa-params)
(%ck:+a-ec-params+ :ec-params)
(%ck:+a-ec-point+ :ec-point)
(%ck:+a-secondary-auth+ :secondary-auth)
(%ck:+a-auth-pin-flags+ :auth-pin-flags)
(%ck:+a-always-authenticate+ :always-authenticate)
(%ck:+a-wrap-with-trusted+ :wrap-with-trusted)
(%ck:+a-hw-feature-type+ :hw-feature-type)
(%ck:+a-reset-on-init+ :reset-on-init)
(%ck:+a-has-reset+ :has-reset)
(%ck:+a-pixel-x+ :pixel-x)
(%ck:+a-pixel-y+ :pixel-y)
(%ck:+a-resolution+ :resolution)
(%ck:+a-char-rows+ :char-rows)
(%ck:+a-char-columns+ :char-columns)
(%ck:+a-color+ :color)
(%ck:+a-bits-per-pixel+ :bits-per-pixel)
(%ck:+a-char-sets+ :char-sets)
(%ck:+a-encoding-methods+ :encoding-methods)
(%ck:+a-mime-types+ :mime-types)
(%ck:+a-mechanism-type+ :mechanism-type)
(%ck:+a-required-cms-attributes+ :required-cms-attributes)
(%ck:+a-default-cms-attributes+ :default-cms-attributes)
(%ck:+a-supported-cms-attributes+ :supported-cms-attributes)
(%ck:+a-wrap-template+ :wrap-template)
(%ck:+a-unwrap-template+ :unwrap-template)
(%ck:+a-allowed-mechanisms+ :allowed-mechanisms)
(%ck:+vendor-defined+ :vendor-defined)))
(define-enum-converter mechanism-type
((%ck:+m-rsa-pkcs-key-pair-gen+ :rsa-pkcs-key-pair-gen)
(%ck:+m-rsa-pkcs+ :rsa-pkcs)
(%ck:+m-rsa-9796+ :rsa-9796)
(%ck:+m-rsa-x-509+ :rsa-x-509)
(%ck:+m-md2-rsa-pkcs+ :md2-rsa-pkcs)
(%ck:+m-md5-rsa-pkcs+ :md5-rsa-pkcs)
(%ck:+m-sha1-rsa-pkcs+ :sha1-rsa-pkcs)
(%ck:+m-ripemd128-rsa-pkcs+ :ripemd128-rsa-pkcs)
(%ck:+m-ripemd160-rsa-pkcs+ :ripemd160-rsa-pkcs)
(%ck:+m-rsa-pkcs-oaep+ :rsa-pkcs-oaep)
(%ck:+m-rsa-x9-31-key-pair-gen+ :rsa-x9-31-key-pair-gen)
(%ck:+m-rsa-x9-31+ :rsa-x9-31)
(%ck:+m-sha1-rsa-x9-31+ :sha1-rsa-x9-31)
(%ck:+m-rsa-pkcs-pss+ :rsa-pkcs-pss)
(%ck:+m-sha1-rsa-pkcs-pss+ :sha1-rsa-pkcs-pss)
(%ck:+m-dsa-key-pair-gen+ :dsa-key-pair-gen)
(%ck:+m-dsa+ :dsa)
(%ck:+m-dsa-sha1+ :dsa-sha1)
(%ck:+m-dh-pkcs-key-pair-gen+ :dh-pkcs-key-pair-gen)
(%ck:+m-dh-pkcs-derive+ :dh-pkcs-derive)
(%ck:+m-x9-42-dh-key-pair-gen+ :x9-42-dh-key-pair-gen)
(%ck:+m-x9-42-dh-derive+ :x9-42-dh-derive)
(%ck:+m-x9-42-dh-hybrid-derive+ :x9-42-dh-hybrid-derive)
(%ck:+m-x9-42-mqv-derive+ :x9-42-mqv-derive)
(%ck:+m-sha256-rsa-pkcs+ :sha256-rsa-pkcs)
(%ck:+m-sha384-rsa-pkcs+ :sha384-rsa-pkcs)
(%ck:+m-sha512-rsa-pkcs+ :sha512-rsa-pkcs)
(%ck:+m-sha256-rsa-pkcs-pss+ :sha256-rsa-pkcs-pss)
(%ck:+m-sha384-rsa-pkcs-pss+ :sha384-rsa-pkcs-pss)
(%ck:+m-sha512-rsa-pkcs-pss+ :sha512-rsa-pkcs-pss)
(%ck:+m-rc2-key-gen+ :rc2-key-gen)
(%ck:+m-rc2-ecb+ :rc2-ecb)
(%ck:+m-rc2-cbc+ :rc2-cbc)
(%ck:+m-rc2-mac+ :rc2-mac)
(%ck:+m-rc2-mac-general+ :rc2-mac-general)
(%ck:+m-rc2-cbc-pad+ :rc2-cbc-pad)
(%ck:+m-rc4-key-gen+ :rc4-key-gen)
(%ck:+m-rc4+ :rc4)
(%ck:+m-des-key-gen+ :des-key-gen)
(%ck:+m-des-ecb+ :des-ecb)
(%ck:+m-des-cbc+ :des-cbc)
(%ck:+m-des-mac+ :des-mac)
(%ck:+m-des-mac-general+ :des-mac-general)
(%ck:+m-des-cbc-pad+ :des-cbc-pad)
(%ck:+m-des2-key-gen+ :des2-key-gen)
(%ck:+m-des3-key-gen+ :des3-key-gen)
(%ck:+m-des3-ecb+ :des3-ecb)
(%ck:+m-des3-cbc+ :des3-cbc)
(%ck:+m-des3-mac+ :des3-mac)
(%ck:+m-des3-mac-general+ :des3-mac-general)
(%ck:+m-des3-cbc-pad+ :des3-cbc-pad)
(%ck:+m-cdmf-key-gen+ :cdmf-key-gen)
(%ck:+m-cdmf-ecb+ :cdmf-ecb)
(%ck:+m-cdmf-cbc+ :cdmf-cbc)
(%ck:+m-cdmf-mac+ :cdmf-mac)
(%ck:+m-cdmf-mac-general+ :cdmf-mac-general)
(%ck:+m-cdmf-cbc-pad+ :cdmf-cbc-pad)
(%ck:+m-md2+ :md2)
(%ck:+m-md2-hmac+ :md2-hmac)
(%ck:+m-md2-hmac-general+ :md2-hmac-general)
(%ck:+m-md5+ :md5)
(%ck:+m-md5-hmac+ :md5-hmac)
(%ck:+m-md5-hmac-general+ :md5-hmac-general)
(%ck:+m-sha-1+ :sha-1)
(%ck:+m-sha-1-hmac+ :sha-1-hmac)
(%ck:+m-sha-1-hmac-general+ :sha-1-hmac-general)
(%ck:+m-ripemd128+ :ripemd128)
(%ck:+m-ripemd128-hmac+ :ripemd128-hmac)
(%ck:+m-ripemd128-hmac-general+ :ripemd128-hmac-general)
(%ck:+m-ripemd160+ :ripemd160)
(%ck:+m-ripemd160-hmac+ :ripemd160-hmac)
(%ck:+m-ripemd160-hmac-general+ :ripemd160-hmac-general)
(%ck:+m-sha256+ :sha256)
(%ck:+m-sha256-hmac+ :sha256-hmac)
(%ck:+m-sha256-hmac-general+ :sha256-hmac-general)
(%ck:+m-sha384+ :sha384)
(%ck:+m-sha384-hmac+ :sha384-hmac)
(%ck:+m-sha384-hmac-general+ :sha384-hmac-general)
(%ck:+m-sha512+ :sha512)
(%ck:+m-sha512-hmac+ :sha512-hmac)
(%ck:+m-sha512-hmac-general+ :sha512-hmac-general)
(%ck:+m-cast-key-gen+ :cast-key-gen)
(%ck:+m-cast-ecb+ :cast-ecb)
(%ck:+m-cast-cbc+ :cast-cbc)
(%ck:+m-cast-mac+ :cast-mac)
(%ck:+m-cast-mac-general+ :cast-mac-general)
(%ck:+m-cast-cbc-pad+ :cast-cbc-pad)
(%ck:+m-cast3-key-gen+ :cast3-key-gen)
(%ck:+m-cast3-ecb+ :cast3-ecb)
(%ck:+m-cast3-cbc+ :cast3-cbc)
(%ck:+m-cast3-mac+ :cast3-mac)
(%ck:+m-cast3-mac-general+ :cast3-mac-general)
(%ck:+m-cast3-cbc-pad+ :cast3-cbc-pad)
(%ck:+m-cast5-key-gen+ :cast5-key-gen)
(%ck:+m-cast128-key-gen+ :cast128-key-gen)
(%ck:+m-cast5-ecb+ :cast5-ecb)
(%ck:+m-cast128-ecb+ :cast128-ecb)
(%ck:+m-cast5-cbc+ :cast5-cbc)
(%ck:+m-cast128-cbc+ :cast128-cbc)
(%ck:+m-cast5-mac+ :cast5-mac)
(%ck:+m-cast128-mac+ :cast128-mac)
(%ck:+m-cast5-mac-general+ :cast5-mac-general)
(%ck:+m-cast128-mac-general+ :cast128-mac-general)
(%ck:+m-cast5-cbc-pad+ :cast5-cbc-pad)
(%ck:+m-cast128-cbc-pad+ :cast128-cbc-pad)
(%ck:+m-rc5-key-gen+ :rc5-key-gen)
(%ck:+m-rc5-ecb+ :rc5-ecb)
(%ck:+m-rc5-cbc+ :rc5-cbc)
(%ck:+m-rc5-mac+ :rc5-mac)
(%ck:+m-rc5-mac-general+ :rc5-mac-general)
(%ck:+m-rc5-cbc-pad+ :rc5-cbc-pad)
(%ck:+m-idea-key-gen+ :idea-key-gen)
(%ck:+m-idea-ecb+ :idea-ecb)
(%ck:+m-idea-cbc+ :idea-cbc)
(%ck:+m-idea-mac+ :idea-mac)
(%ck:+m-idea-mac-general+ :idea-mac-general)
(%ck:+m-idea-cbc-pad+ :idea-cbc-pad)
(%ck:+m-generic-secret-key-gen+ :generic-secret-key-gen)
(%ck:+m-concatenate-base-and-key+ :concatenate-base-and-key)
(%ck:+m-concatenate-base-and-data+ :concatenate-base-and-data)
(%ck:+m-concatenate-data-and-base+ :concatenate-data-and-base)
(%ck:+m-xor-base-and-data+ :xor-base-and-data)
(%ck:+m-extract-key-from-key+ :extract-key-from-key)
(%ck:+m-ssl3-pre-master-key-gen+ :ssl3-pre-master-key-gen)
(%ck:+m-ssl3-master-key-derive+ :ssl3-master-key-derive)
(%ck:+m-ssl3-key-and-mac-derive+ :ssl3-key-and-mac-derive)
(%ck:+m-ssl3-master-key-derive-dh+ :ssl3-master-key-derive-dh)
(%ck:+m-tls-pre-master-key-gen+ :tls-pre-master-key-gen)
(%ck:+m-tls-master-key-derive+ :tls-master-key-derive)
(%ck:+m-tls-key-and-mac-derive+ :tls-key-and-mac-derive)
(%ck:+m-tls-master-key-derive-dh+ :tls-master-key-derive-dh)
(%ck:+m-ssl3-md5-mac+ :ssl3-md5-mac)
(%ck:+m-ssl3-sha1-mac+ :ssl3-sha1-mac)
(%ck:+m-md5-key-derivation+ :md5-key-derivation)
(%ck:+m-md2-key-derivation+ :md2-key-derivation)
(%ck:+m-sha1-key-derivation+ :sha1-key-derivation)
(%ck:+m-pbe-md2-des-cbc+ :pbe-md2-des-cbc)
(%ck:+m-pbe-md5-des-cbc+ :pbe-md5-des-cbc)
(%ck:+m-pbe-md5-cast-cbc+ :pbe-md5-cast-cbc)
(%ck:+m-pbe-md5-cast3-cbc+ :pbe-md5-cast3-cbc)
(%ck:+m-pbe-md5-cast5-cbc+ :pbe-md5-cast5-cbc)
(%ck:+m-pbe-md5-cast128-cbc+ :pbe-md5-cast128-cbc)
(%ck:+m-pbe-sha1-cast5-cbc+ :pbe-sha1-cast5-cbc)
(%ck:+m-pbe-sha1-cast128-cbc+ :pbe-sha1-cast128-cbc)
(%ck:+m-pbe-sha1-rc4-128+ :pbe-sha1-rc4-128)
(%ck:+m-pbe-sha1-rc4-40+ :pbe-sha1-rc4-40)
(%ck:+m-pbe-sha1-des3-ede-cbc+ :pbe-sha1-des3-ede-cbc)
(%ck:+m-pbe-sha1-des2-ede-cbc+ :pbe-sha1-des2-ede-cbc)
(%ck:+m-pbe-sha1-rc2-128-cbc+ :pbe-sha1-rc2-128-cbc)
(%ck:+m-pbe-sha1-rc2-40-cbc+ :pbe-sha1-rc2-40-cbc)
(%ck:+m-pkcs5-pbkd2+ :pkcs5-pbkd2)
(%ck:+m-pba-sha1-with-sha1-hmac+ :pba-sha1-with-sha1-hmac)
(%ck:+m-key-wrap-lynks+ :key-wrap-lynks)
(%ck:+m-key-wrap-set-oaep+ :key-wrap-set-oaep)
(%ck:+m-skipjack-key-gen+ :skipjack-key-gen)
(%ck:+m-skipjack-ecb64+ :skipjack-ecb64)
(%ck:+m-skipjack-cbc64+ :skipjack-cbc64)
(%ck:+m-skipjack-ofb64+ :skipjack-ofb64)
(%ck:+m-skipjack-cfb64+ :skipjack-cfb64)
(%ck:+m-skipjack-cfb32+ :skipjack-cfb32)
(%ck:+m-skipjack-cfb16+ :skipjack-cfb16)
(%ck:+m-skipjack-cfb8+ :skipjack-cfb8)
(%ck:+m-skipjack-wrap+ :skipjack-wrap)
(%ck:+m-skipjack-private-wrap+ :skipjack-private-wrap)
(%ck:+m-skipjack-relayx+ :skipjack-relayx)
(%ck:+m-kea-key-pair-gen+ :kea-key-pair-gen)
(%ck:+m-kea-key-derive+ :kea-key-derive)
(%ck:+m-fortezza-timestamp+ :fortezza-timestamp)
(%ck:+m-baton-key-gen+ :baton-key-gen)
(%ck:+m-baton-ecb128+ :baton-ecb128)
(%ck:+m-baton-ecb96+ :baton-ecb96)
(%ck:+m-baton-cbc128+ :baton-cbc128)
(%ck:+m-baton-counter+ :baton-counter)
(%ck:+m-baton-shuffle+ :baton-shuffle)
(%ck:+m-baton-wrap+ :baton-wrap)
(%ck:+m-ecdsa-key-pair-gen+ :ecdsa-key-pair-gen)
(%ck:+m-ec-key-pair-gen+ :ec-key-pair-gen)
(%ck:+m-ecdsa+ :ecdsa)
(%ck:+m-ecdsa-sha1+ :ecdsa-sha1)
(%ck:+m-ecdh1-derive+ :ecdh1-derive)
(%ck:+m-ecdh1-cofactor-derive+ :ecdh1-cofactor-derive)
(%ck:+m-ecmqv-derive+ :ecmqv-derive)
(%ck:+m-juniper-key-gen+ :juniper-key-gen)
(%ck:+m-juniper-ecb128+ :juniper-ecb128)
(%ck:+m-juniper-cbc128+ :juniper-cbc128)
(%ck:+m-juniper-counter+ :juniper-counter)
(%ck:+m-juniper-shuffle+ :juniper-shuffle)
(%ck:+m-juniper-wrap+ :juniper-wrap)
(%ck:+m-fasthash+ :fasthash)
(%ck:+m-aes-key-gen+ :aes-key-gen)
(%ck:+m-aes-ecb+ :aes-ecb)
(%ck:+m-aes-cbc+ :aes-cbc)
(%ck:+m-aes-mac+ :aes-mac)
(%ck:+m-aes-mac-general+ :aes-mac-general)
(%ck:+m-aes-cbc-pad+ :aes-cbc-pad)
(%ck:+m-dsa-parameter-gen+ :dsa-parameter-gen)
(%ck:+m-dh-pkcs-parameter-gen+ :dh-pkcs-parameter-gen)
(%ck:+m-x9-42-dh-parameter-gen+ :x9-42-dh-parameter-gen)
(%ck:+vendor-defined+ :vendor-defined)))
(define-flag-converter convert-mechanism-info-flags
((%ck:+f-hw+ :hw)
(%ck:+f-encrypt+ :encrypt)
(%ck:+f-decrypt+ :decrypt)
(%ck:+f-digest+ :digest)
(%ck:+f-sign+ :sign)
(%ck:+f-sign-recover+ :sign-recover)
(%ck:+f-verify+ :verify)
(%ck:+f-verify-recover+ :verify-recover)
(%ck:+f-generate+ :generate)
(%ck:+f-generate-key-pair+ :generate-key-pair)
(%ck:+f-wrap+ :wrap)
(%ck:+f-unwrap+ :unwrap)
(%ck:+f-derive+ :derive)
(%ck:+f-extension+ :extension)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; PKCS11-ERROR
(define-condition pkcs11-error (error)
((label :initarg :label :reader pkcs11-error-label)
(code :initarg :code :reader pkcs11-error-code)
(function :initarg :function :reader pkcs11-error-function))
(:report (lambda (condition stream)
(format stream "PKCS11 Error: ~A (~A) in ~A"
(pkcs11-error-label condition)
(pkcs11-error-code condition)
(pkcs11-error-function condition))
condition)))
(defun check-rv (rv &optional function continue)
(unless (zerop rv)
(let ((args (list 'pkcs11-error :label (return-value :decode rv)
:code rv
:function function)))
(if continue
(apply (function cerror) "Ignore and continue" args)
(apply (function error) args))))
(values))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
(defun ckbool (generalized-boolean)
(if (integerp generalized-boolean)
(if (zerop generalized-boolean)
%ck:+false+
%ck:+true+)
(if generalized-boolean
%ck:+true+
%ck:+false+)))
(defun unavailable-information-p (value)
(= %ck:+unavailable-information+
(logand %ck:+unavailable-information+ value)))
(defun invalid-pointer-p (pointer)
(or (null-pointer-p pointer)
(unavailable-information-p (pointer-address pointer))))
(defmacro with-pkcs11 (&body body)
`(progn
(check-rv (%ck:initialize (null-pointer)) "C_Initialize" :continue)
(unwind-protect (progn ,@body)
(check-rv (%ck:finalize (null-pointer)) "C_Finalize" :continue))))
(defstruct version
major
minor)
(defun version (operation version)
(ecase operation
((:decode) (with-foreign-slots ((%ck:major %ck:minor) version (:struct %ck:version))
(make-version :major %ck:major
:minor %ck:minor)))))
(defstruct info
cryptoki-version
manufacturer-id
flags
library-description
library-version)
(defun get-info ()
"RETURN: an INFO structure."
(with-foreign-object (info '(:struct %ck:info))
(check-rv (%ck:get-info info) "C_GetInfo")
(flet ((str (slot size)
(foreign-string-to-lisp
(foreign-slot-pointer info '(:struct %ck:info) slot)
:count size :encoding :ascii))
(ver (slot)
(version :decode (foreign-slot-pointer info '(:struct %ck:info) slot))))
(make-info
:cryptoki-version (ver '%ck:cryptoki-version)
:manufacturer-id (str '%ck:manufacturer-id 32)
;; flags is reserved for future extensions, should be 0.
:flags (foreign-slot-value info '(:struct %ck:info) '%ck:flags)
:library-description (str '%ck:library-description 32)
:library-version (ver '%ck:library-version)))))
(defun get-slot-list (token-present)
"RETURN: a list of SLOT-IDs."
(with-foreign-object (count :ulong)
(handler-case
(progn
(check-rv (%ck:get-slot-list (ckbool token-present) (null-pointer) count) "C_GetSlotList")
(let ((slot-count (mem-ref count :ulong)))
(when (plusp slot-count)
(with-foreign-object (slot-ids '%ck:slot-id slot-count)
(check-rv (%ck:get-slot-list (ckbool token-present) slot-ids count))
(loop :for i :below slot-count
:collect (mem-aref slot-ids '%ck:slot-id i))))))
(error (err)
(format *error-output* "ERROR: ~A~%" err)
'()))))
(defstruct slot-info
slot-description
manufacturer-id
flags
hardware-version
firmware-version)
(defun get-slot-info (slot-id)
"RETURN: a SLOT-INFO structure."
(check-type slot-id slot-id)
(with-foreign-object (info '(:struct %ck:slot-info))
(check-rv (%ck:get-slot-info slot-id info) "C_GetSlotInfo")
(flet ((str (slot size)
(foreign-string-to-lisp
(foreign-slot-pointer info '(:struct %ck:slot-info) slot)
:count size :encoding :ascii))
(ver (slot)
(version :decode (foreign-slot-pointer info '(:struct %ck:slot-info) slot))))
(make-slot-info
:slot-description (str '%ck:slot-description 64)
:manufacturer-id (str '%ck:manufacturer-id 32)
:flags (convert-slot-info-flags :decode (foreign-slot-value info '(:struct %ck:slot-info) '%ck:flags))
:hardware-version (ver '%ck:hardware-version)
:firmware-version (ver '%ck:firmware-version)))))
(defstruct token-info
label manufacturer-id model serial-number flags max-session-count
session-count max-rw-session-count rw-session-count max-pin-len
min-pin-len total-public-memory free-public-memory
total-private-mmeory free-private-memory hardware-version
firmware-version utc-time)
(defun get-token-info (slot-id)
"RETURN: a TOKEN-INFO structure."
(check-type slot-id slot-id)
(with-foreign-object (info '(:struct %ck:token-info))
(check-rv (%ck:get-token-info slot-id info) "C_GetTokenInfo")
(flet ((str (slot size)
(foreign-string-to-lisp
(foreign-slot-pointer info '(:struct %ck:token-info) slot)
:count size :encoding :ascii))
(ver (slot)
(version :decode (foreign-slot-pointer info '(:struct %ck:token-info) slot)))
(long (slot)
(let ((value (foreign-slot-value info '(:struct %ck:token-info) slot)))
(cond
((= value %ck:+unavailable-information+) nil)
((= value %ck:+effectively-infinite+) :infinite)
(t value)))))
(make-token-info
:label (str '%ck:label 32)
:manufacturer-id (str '%ck:manufacturer-id 32)
:model (str '%ck:model 16)
:serial-number (str '%ck:serial-number 16)
:flags (convert-token-info-flags :decode (foreign-slot-value info '(:struct %ck:token-info) '%ck:flags))
:max-session-count (long '%ck:max-session-count)
:session-count (long '%ck:session-count)
:max-rw-session-count (long '%ck:max-rw-session-count)
:rw-session-count (long '%ck:rw-session-count)
:max-pin-len (long '%ck:max-pin-len)
:min-pin-len (long '%ck:min-pin-len)
:total-public-memory (long '%ck:total-public-memory)
:free-public-memory (long '%ck:free-public-memory)
:total-private-mmeory (long '%ck:total-private-mmeory)
:free-private-memory (long '%ck:free-private-memory)
:hardware-version (ver '%ck:hardware-version)
:firmware-version (ver '%ck:firmware-version)
:utc-time (str '%ck:utc-time 16)))))
(defun wait-for-slot-event (flags)
"RETURN: The SLOT-ID where an event occured."
(check-type flags (or integer keyword))
(with-foreign-object (slot-id :ulong)
(check-rv (%ck:wait-for-slot-event (if (integerp flags)
flags
(convert-wait-for-slot-event-flags :encode flags))
slot-id
(null-pointer))
"C_WaitForSlotEvent")
(mem-ref slot-id :ulong)))
(defun get-mechanism-list (slot-id)
"RETURN: a list of MECHANISM-TYPE."
(check-type slot-id slot-id)
(with-foreign-object (count :ulong)
(check-rv (%ck:get-mechanism-list slot-id (null-pointer) count) "C_GetMechanismList")
(let ((mechanism-count (mem-ref count :ulong)))
(when (plusp mechanism-count)
(with-foreign-object (mechanism-types '%ck:mechanism-type mechanism-count)
(check-rv (%ck:get-mechanism-list slot-id mechanism-types count))
(loop :for i :below mechanism-count
:collect (mechanism-type :decode (mem-aref mechanism-types '%ck:mechanism-type i))))))))
(defstruct mechanism-info
min-key-size max-key-size flags)
(defun get-mechanism-info (slot-id mechanism-type)
"RETURN: a MECHANIS-INFO structure."
(check-type slot-id slot-id)
(check-type mechanism-type mechanism-type)
(with-foreign-object (info '(:struct %ck:mechanism-info))
(check-rv (%ck:get-mechanism-info slot-id
(if (integerp mechanism-type)
mechanism-type
(mechanism-type :encode mechanism-type))
info)
"C_GetMechanismInfo")
(flet ((long (slot)
(foreign-slot-value info '(:struct %ck:mechanism-info) slot)))
(make-mechanism-info
:min-key-size (long '%ck:min-key-size)
:max-key-size (long '%ck:min-key-size)
:flags (convert-mechanism-info-flags :decode (foreign-slot-value info '(:struct %ck:mechanism-info) '%ck:flags))))))
(defun string-from-utf-8 (bytes)
(octets-to-string bytes :encoding :utf-8 :errorp t))
(defun string-to-utf-8 (string &key size padchar)
;; Note: we could be more optimized by storing directly a pre-allocated result vector,
;; but it's expected to be used only on small strings…
(let ((bytes (string-to-octets string :encoding :utf-8 :use-bom nil)))
(when (and size (< size (length bytes)))
(setf bytes (subseq bytes 0 size))
(unless (ignore-errors (octets-to-string bytes :encoding :utf-8 :errorp t))
(error "Truncated utf-8 byte sequence in the middle of a utf-8 code sequence!~%string: ~S~%bytes: ~S~%"
string bytes)))
(if (and padchar size (< (length bytes) size))
(let ((padstring (string-to-octets (string padchar) :encoding :utf-8 :use-bom nil)))
(unless (zerop (mod (- size (length bytes)) (length padstring)))
(error "pad character is encoded as a utf-8 code sequence of length ~D, which is not a divisor of the required padding length ~D. Try to specify an ASCII character as pad character!"
(length padstring) (- size (length bytes))))
(let ((result (apply (function make-array) size :element-type 'octet
(when (= 1 (length padstring))
(list :initial-element (aref padstring 0))))))
(replace result bytes)
(unless (= 1 (length padstring))
(loop :for s :from (length bytes) :below (length result) :by (length padstring)
:do (replace result padstring :start1 s)))
result))
bytes)))
(defun init-token (slot-id pin label)
"RETURN: the PIN string as returned by C_InitToken."
(check-type slot-id slot-id)
(check-type pin string)
(check-type label string)
(warn "Not tested yet! Please, provide new smart-cards!")
(let* ((label (string-to-utf-8 label :size 32 :padchar #\space))
(pin (string-to-utf-8 pin))
(pinlen (length pin)))
(with-foreign-objects ((flabel :uchar 32)
(fpin :uchar pinlen)
(fpinlen :ulong))
(dotimes (i 32) (setf (mem-aref flabel :uchar i) (aref label i)))
(dotimes (i pinlen) (setf (mem-aref fpin :uchar i) (aref pin i)))
(setf (mem-ref fpinlen :ulong) pinlen)
(check-rv (%ck:init-token slot-id fpin fpinlen flabel) "C_InitToken")
(foreign-string-to-lisp fpin :count fpinlen :encoding :ascii))))
(defparameter *references* '() "A-list mapping foreign pointers with lisp objets")
(defstruct entry
slot-id reference pointer session)
(defun enter-reference (slot-id reference)
(let ((pointer (foreign-alloc :ulong :initial-element #x1BADBEEF)))
(push (make-entry :slot-id slot-id :pointer pointer :reference reference) *references*)
pointer))
(defun find-entry-with-pointer (pointer)
(find pointer *references* :key (function entry-pointer)))
(defun find-entry-with-session (session)
(find session *references* :key (function entry-session)))
(defun associate-pointer-with-session (pointer session)
(let ((entry (find-entry-with-pointer pointer)))
(when entry
(setf (entry-session entry) session))))
(defun clear-entry-with-pointer (pointer)
(setf *references* (delete (find-entry-with-pointer pointer) *references*)))
(defun clear-entry-with-session (session)
(setf *references* (delete (find-entry-with-session session) *references*)))
(defun clear-entries-with-slot-id (slot-id)
(setf *references* (delete slot-id *references* :key (function entry-slot-id))))
(defun open-session (slot-id flags application-reference notify-function)
"RETURN: a SESSION-HANDLER."
(check-type slot-id slot-id)
(check-type notify-function null "TODO: Sorry, notify-function are not supported yet.") ; TODO.
(let ((application-reference (if application-reference
(enter-reference slot-id application-reference)
(null-pointer))))
(with-foreign-object (session-handle '%ck:session-handle)
(check-rv (%ck:open-session slot-id
(if (integerp flags)
flags
(convert-session-info-flags :encode flags))
application-reference
(null-pointer) ; TODO notify-function
session-handle)
"C_OpenSession")
(let ((session (mem-ref session-handle '%ck:session-handle)))
(associate-pointer-with-session application-reference session)
session))))
(defun close-session (session-handle)
(check-type session-handle session-handle)
(check-rv (%ck:close-session session-handle) "C_CloseSession")
(clear-entry-with-session session-handle)
(values))
(defun close-all-sessions (slot-id)
(check-type slot-id slot-id)
(check-rv (%ck:close-all-sessions slot-id) "C_CloseAllSessions")
(clear-entries-with-slot-id slot-id)
(values))
(defmacro with-open-session ((session-var slot-id &key flags application-reference notify-function
(if-open-session-fails :error)) &body body)
(let ((vflags (gensym))
(vsession (gensym)))
`(flet ((open-it ()
(open-session ,slot-id
(let ((,vflags ,flags))
(if (integerp ,vflags)
(logior ,vflags %ck:+serial-session+)
(cons :serial-session ,vflags)))
,application-reference
,notify-function)))
(let* ((,vsession (ecase ,if-open-session-fails
((:error) (open-it))
((nil) (ignore-errors (open-it)))))
(,session-var ,vsession))
(unwind-protect (progn ,@body)
(when ,vsession (close-session ,vsession)))))))
(defstruct session-info
slot-id state flags device-error)
(defun get-session-info (session)
"RETURN: a SESSION-INFO structure."
(check-type session session-handle)
(with-foreign-object (info '(:struct %ck:session-info))
(check-rv (%ck:get-session-info session info) "C_GetSessionInfo")
(flet ((long (slot)
(foreign-slot-value info '(:struct %ck:session-info) slot)))
(make-session-info
:slot-id (long '%ck:slot-id)
:state (state :decode (long '%ck:state))
:flags (convert-session-info-flags :decode (long '%ck:flags))
:device-error (long '%ck:device-error)))))
;; Probably better not to keep long lived C buffers.
;; Furthermore, the operation can be resumed in a different process,
;; so it's better to convert to lisp data that's more easily
;; serializable.
;;
;; (defstruct operation-state
;; data
;; size)
;; (defun free-operation-state (operation-state)
;; (foreign-free (operation-state-data operation-state)))
;; (make-operation-state :data operation-state
;; :size (mem-ref operation-state-len :ulong))
(defun get-operation-state (session)
"RETURN: a vector of octet containing the session state."
(check-type session session-handle)
(with-foreign-object (operation-state-len :ulong)
(check-rv (%ck:get-operation-state session (null-pointer) operation-state-len) "C_GetOperationState")
(with-foreign-object (operation-state :uchar (mem-ref operation-state-len :ulong))
(check-rv (%ck:get-operation-state session operation-state operation-state-len) "C_GetOperationState")
(foreign-vector operation-state :uchar 'octet (mem-ref operation-state-len :ulong)))))
(defun set-operation-state (session state &key (encryption-key 0) (authentication-key 0))
(check-type session session-handle)
(check-type state (vector octet))
(check-type encryption-key object-handle)
(check-type authentication-key object-handle)
(with-foreign-objects ((operation-state :uchar (length state))
(operation-state-len :ulong))
(loop :for i :below (length state)
:do (setf (mem-aref operation-state :uchar i) (aref state i)))
(setf (mem-ref operation-state-len :ulong) (length state))
(check-rv (%ck:set-operation-state session operation-state operation-state-len
encryption-key authentication-key)
"C_SetOperationState")))
(defun login (session user-type pin)
(check-type session session-handle)
(check-type user-type (or integer keyword))
(check-type pin (or null string))
(if pin
(let* ((pin (string-to-utf-8 pin))
(pinlen (length pin)))
(with-foreign-objects ((fpin :uchar pinlen))
(dotimes (i pinlen) (setf (mem-aref fpin :uchar i) (aref pin i)))
(check-rv (%ck:login session (if (integerp user-type)
user-type
(user-type :encode user-type))
fpin pinlen)
"C_Login")))
(check-rv (%ck:login session (if (integerp user-type)
user-type
(user-type :encode user-type))
(null-pointer) 0)
"C_Login")))
(defun logout (session)
(check-type session session-handle)
(check-rv (%ck:logout session) "C_Logout"))
(defvar *verbose* t)
(defun call-logged-in (session slot-id thunk &key why)
"RETURN: the results of THUNK, or NIL when login was impossible."
(check-type session session-handle)
(check-type slot-id slot-id)
(check-type thunk (or function symbol))
(when (handler-case
(let* ((info (get-token-info slot-id))
(flags (token-info-flags info)))
(login session %ck:+user+ (if (member :protected-authentication-path flags)
(progn
(format t "~&~@[Logging for ~A.~%~]Please, enter pin on pin-pad (~:[~D digits~;~D to ~D digits~]).~%"
why
(/= (token-info-min-pin-len info) (token-info-max-pin-len info))
(token-info-min-pin-len info)
(token-info-max-pin-len info))
(finish-output)
nil)
(read-pin (token-info-min-pin-len info) (token-info-max-pin-len info))))
t)
(pkcs11-error (err)
(princ err *error-output*)
(terpri *error-output*)
nil))
(unwind-protect (progn
(when *verbose*
(fresh-line)
(format t "~&Logged in~@[, for ~A~].~%" why)
(finish-output))
(funcall thunk))
(logout session)
(when *verbose*
(fresh-line)
(format t "~&Logged out~@[ for ~A~].~%" why)
(finish-output)))))
(defmacro do-logged-in ((session slot-id &optional why) &body body)
`(call-logged-in ,session ,slot-id (lambda () ,@body) :why ,why))
(defun init-pin (session pin)
(check-type session session-handle)
(check-type pin string)
(let* ((pin (string-to-utf-8 pin))
(pinlen (length pin)))
(with-foreign-objects ((fpin :uchar pinlen)
(fpinlen :ulong))
(dotimes (i pinlen) (setf (mem-aref fpin :uchar i) (aref pin i)))
(setf (mem-ref fpinlen :ulong) pinlen)
(check-rv (%ck:init-pin session fpin fpinlen) "C_InitPIN"))))
(defun set-pin (session old-pin new-pin)
(check-type session session-handle)
(check-type old-pin string)
(check-type new-pin string)
(let* ((old-pin (string-to-utf-8 old-pin))
(new-pin (string-to-utf-8 new-pin))
(old-pinlen (length old-pin))
(new-pinlen (length new-pin)))
(with-foreign-objects ((fold-pin :uchar old-pinlen)
(fnew-pin :uchar new-pinlen)
(fold-pinlen :ulong)
(fnew-pinlen :ulong))
(dotimes (i old-pinlen) (setf (mem-aref fold-pin :uchar i) (aref old-pin i)))
(dotimes (i new-pinlen) (setf (mem-aref fnew-pin :uchar i) (aref new-pin i)))
(setf (mem-ref fold-pinlen :ulong) old-pinlen)
(setf (mem-ref fnew-pinlen :ulong) new-pinlen)
(check-rv (%ck:set-pin session fold-pin fold-pinlen fnew-pin fnew-pinlen) "C_SetPIN"))))
(defun read-pin (&optional min (max min))
"Reads a PIN as a string, prompting for at least MIN characters, and at most MAX."
(format *query-io* "~%Please enter your PIN~@[~* (~:[~D digits~;~D to ~D digits~])~]: "
min (and min max (/= min max)) min max)
(finish-output *query-io*)
(prog1 (read-line *query-io*)
(terpri *query-io*)))
(defun integer-to-bytes (value &key (endian :little)
(step 8) ; bits
size ; bits
min-size ; bits
max-size) ; bits
"Converts an integer into a byte vector.
ENDIAN: the byte order :little or :big -endian.
SIZE: the size in bits of the integer.
MIN-SIZE: the minimum size in bits for the integer.
MAX-SIZE: the maximum size in bits for the integer.
STEP: SIZE, MIN-SIZE and MAX-SIZE, when specified,
should be multiples of STEP.
The integer size is ceiled by STEP.
SIZE and (MIN-SIZE or MAX-SIZE) are mutually exclusive.
"
(check-type endian (member :little :big))
(assert (not (and size (or min-size max-size)))
(size min-size max-size)
"size and (min-size or max-size) are mutually exclusive.")
(flet ((call-do-size (size thunk-i thunk-l)
(cond
((null size))
((integerp size) (funcall thunk-i size))
((and (consp size) (eql 'member (first size)))
(dolist (size (rest size))
(funcall thunk-l size)))
(t (error "Invalid size: ~S Should be an integer or (member integer…)." size)))))
(macrolet ((do-size ((size) &body body)
(let ((fbody (gensym)))
`(flet ((,fbody (,size) ,@body))
(call-do-size ,size (function ,fbody) (function ,fbody))))))
(macrolet ((check-step (size)
`(assert (or (null ,size) (zerop (mod ,size step)))
(,size step)
"~A = ~D should be a multiple of ~A = ~D"
',size ,size 'step step)))
(do-size (size) (check-step size))
(check-step min-size)
(check-step max-size))
(let ((value-length (* (ceiling (integer-length value) step) step)))
(when size
(block size-ok
(call-do-size size
(lambda (size)
(if (<= value-length size)
(setf value-length size)
(error "Value #x~X has ~D bits (rounded to ~D) which is more than the specified size ~D"
value value-length step size))
(return-from size-ok))
(lambda (size)
(when (= value-length size)
(return-from size-ok))))
(error "Value #x~X has ~D bits (rounded to ~D) which is not one of ~S"
value value-length step (rest size))))
(when (and min-size (< value-length min-size))
(setf value-length min-size))
(when (and max-size (< max-size value-length))
(error "Value #x~X has ~D bits (rounded to ~D) which is less than the specified max-size ~D"
value value-length step max-size))
(loop :with vector := (make-array (ceiling value-length 8) :element-type 'octet)
:with increment := (if (eql endian :little) +1 -1)
:repeat (length vector)
:for i := (if (eql endian :little) 0 (1- (length vector))) :then (+ i increment)
:for b :from 0 :by 8
:do (setf (aref vector i) (ldb (byte 8 b) value))
:finally (return vector))))))
(defun test/integer-to-bytes ()
(assert (equalp (list (integer-to-bytes #x312312312312312301020304 :endian :little)
(integer-to-bytes #x312312312312312301020304 :endian :big))
'(#(4 3 2 1 35 49 18 35 49 18 35 49)
#(49 35 18 49 35 18 49 35 1 2 3 4))))
(assert (equalp (list (integer-to-bytes #x312312312312312301020304 :endian :little :step 64)
(integer-to-bytes #x312312312312312301020304 :endian :big :step 64))
'(#(4 3 2 1 35 49 18 35 49 18 35 49 0 0 0 0)
#(0 0 0 0 49 35 18 49 35 18 49 35 1 2 3 4))))
(assert (equalp (list (integer-to-bytes #x312312312312312301020304 :endian :little :size 128)
(integer-to-bytes #x312312312312312301020304 :endian :big :step 128))
'(#(4 3 2 1 35 49 18 35 49 18 35 49 0 0 0 0)
#(0 0 0 0 49 35 18 49 35 18 49 35 1 2 3 4))))
(assert (equalp (list (integer-to-bytes #x312312312312312301020304 :endian :little :step 32 :min-size 160)
(integer-to-bytes #x312312312312312301020304 :endian :big :step 32 :min-size 160))
'(#(4 3 2 1 35 49 18 35 49 18 35 49 0 0 0 0 0 0 0 0)
#(0 0 0 0 0 0 0 0 49 35 18 49 35 18 49 35 1 2 3 4))))
:success)
(test/integer-to-bytes)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Attribute
(defmacro attr-> (struct slot)
`(foreign-slot-value ,struct '(:struct %ck:attribute) ',slot))
(defun attr-aptr (template index)
(mem-aptr template '(:struct %ck:attribute) index))
;; For conversion of integers to:
;; :big-integer is most significant byte first (Big endian).
;; :der is most significant byte first (Big endian).
;; :bytes is less significant byte first (Little endian).
;; :bytes-noint rejects integers.
;; (:big-integer [:size s])
;; (:big-integer [:min-size s1] [:max-size s2] [:step s3])
;; s := integer | (member integer…)
(defparameter *attribute-type-map*
'((:class (:ulong object-class))
(:token :bool)
(:private :bool)
(:label :string) ; rfc2279 (utf-8)
(:application :string) ; rfc2279 (utf-8)
(:value :bytes-noint) ; or rfc2279 (utf-8)
(:object-id :bytes) ; DER encoding of the OID indicating the data object type (empty by default)
(:certificate-type (:ulong certificate-type))
(:issuer :bytes)
(:serial-number :bytes)
(:ac-issuer :string)
(:owner :string)
(:attr-types (:ulong attribute-type))
(:trusted :bool)
(:certificate-category :ulong)
(:java-midp-security-domain :bytes)
(:url :string)
(:hash-of-subject-public-key :bytes)
(:hash-of-issuer-public-key :bytes)
(:check-value :bytes)
(:key-type (:ulong key-type))
(:subject :bytes)
(:id :bytes) ; DER-encoding of the object identifier indicating the domain parameters
; Big endian: #xe828bd080fd2500000104d494f4300010101
; <-> #(#xe8 #x28 #xbd #x08 #x0f #xd2 #x50 #x00 #x00
; #x10 #x4d #x49 #x4f #x43 #x00 #x01 #x01 #x01)
(:sensitive :bool)
(:encrypt :bool)
(:decrypt :bool)
(:wrap :bool)
(:unwrap :bool)
(:sign :bool)
(:sign-recover :bool)
(:verify :bool)
(:verify-recover :bool)
(:derive :bool)
(:start-date :date)
(:end-date :date)
(:modulus :big-integer)
(:modulus-bits :ulong)
(:public-exponent :big-integer)
(:private-exponent :big-integer)
(:prime-1 :big-integer)
(:prime-2 :big-integer)
(:exponent-1 :big-integer)
(:exponent-2 :big-integer)
(:coefficient :big-integer)
(:prime (:big-integer :min-size 512 :max-size 1024 :step 64))
(:subprime (:big-integer :size (member 160 224 256)))
(:base :big-integer)
(:prime-bits :ulong)
(:sub-prime-bits :ulong)
(:value-bits :ulong)
(:value-len :ulong)
(:extractable :bool)
(:local :bool)
(:never-extractable :bool)
(:always-sensitive :bool)
(:key-gen-mechanism (:ulong mechanism-type))
(:modifiable :bool)
(:ecdsa-params :bytes)
(:ec-params :bytes)
(:ec-point :bytes)
(:secondary-auth :bytes)
(:auth-pin-flags :bytes)
(:always-authenticate :bool)
(:wrap-with-trusted :bool)
(:hw-feature-type (:ulong hardware-feature))
(:reset-on-init :bool)
(:has-reset :bool)
(:pixel-x :ulong)
(:pixel-y :ulong)
(:resolution :ulong)
(:char-rows :ulong)
(:char-columns :ulong)
(:color :bool)
(:bits-per-pixel :ulong)
(:char-sets :string) ; rfc2279 (utf-8)
(:encoding-methods :string) ; rfc2279 (utf-8)
(:mime-types :string) ; rfc2279 (utf-8)
(:mechanism-type (:ulong mechanism-type))
(:required-cms-attributes :bytes)
(:default-cms-attributes :bytes)
(:supported-cms-attributes :bytes)
(:wrap-template (:array :attribute))
(:unwrap-template (:array :attribute))
(:allowed-mechanisms (:array (:ulong mechanism-type)))
(:vendor-defined :bytes)))
(defun attribute-type-to-ltype (atype &optional type)
(or (second (assoc (attribute-type :decode atype) *attribute-type-map*))
(error "Unknown attribute type: ~S~@[ (type = ~S)~]"
(attribute-type :decode atype) type)))
(defun attribute-copy (destination source)
(setf (attr-> destination %ck:type) (attr-> source %ck:type)
(attr-> destination %ck:value-len) (attr-> source %ck:value-len)
(attr-> destination %ck:value) (attr-> source %ck:value))
destination)
(defun attribute-allocate-buffer (attribute)
(let* ((len (attr-> attribute %ck:value-len))
(val (foreign-alloc :uchar :count len :initial-element 0)))
(setf (attr-> attribute %ck:value) val)))
(defun attribute-allocate-ulong-array (attribute)
(let* ((len (attr-> attribute %ck:value-len))
(val (foreign-alloc :ulong :count len :initial-element 0)))
(setf (attr-> attribute %ck:value) val)))
(defun attribute-allocate-attribute-array (attribute)
(let* ((len (attr-> attribute %ck:value-len))
(val (foreign-alloc :pointer :count len :initial-element (null-pointer))))
(setf (attr-> attribute %ck:value) val)))
(defun base-ltype-p (ltype)
(if (atom ltype)
ltype
(find (first ltype) '(:big-integer))))
(defun big-integer-attributes (ltype)
(cond
((atom ltype) '())
((eql :big-integer (first ltype)) (rest ltype))
(t '())))
(defun attribute-fill (attribute type value)
;; :ulong - 4 bytes in big-endian order?
;; :bool - 1 byte 0 or 1
;; :string - any number of bytes. the strings are utf-8 encoded.
;; if we get a byte vector in, we pass it as is.
;; :bytes - a vector of bytes. If we get a string, we encode it in utf-8, if we get an integer, we encode in little-endian order.
;; :bytes-noint - a vector of bytes. If we get a string, we encode it in utf-8, if we get an integer, we reject it.
;; :big-integer - a vector of bytes. If we get an integer, we encode in big-endian order.
;; :date - a date (string) or universal-time.
;; (:array :ulong) - a vector of ulong.
;; (:array :attribute) - a vector of attributes (passed to the C_ function is a vector of pointers to attribute structures).
;; For strings, bytes and arrays, if the value is nil, then we set the pValue to NULL.
(flet ((set-attribute-fields (attribute atype ctype count &optional value)
(assert (not (and (null count) value)))
(let* ((len (* (or count 0) (foreign-type-size ctype)))
(val (cond
((null count) (null-pointer))
(value value)
(t (foreign-alloc :uchar :count len)))))
(setf (attr-> attribute %ck:type) atype
(attr-> attribute %ck:value) val
(attr-> attribute %ck:value-len) len)
val)))
(let* ((atype (if (integerp type)
type
(attribute-type :encode type)))
(ltype (attribute-type-to-ltype atype type))
(base-ltype (base-ltype-p ltype)))
(case base-ltype
((:ulong) (set-attribute-fields attribute atype :ulong 1
(foreign-alloc :ulong :initial-element value)))
((:bool) (set-attribute-fields attribute atype :uchar 1
(foreign-alloc :uchar :initial-element (ckbool value))))
((:string :bytes :bytes-noint :big-integer)
(let* ((value (typecase value
(null nil)
(integer (case base-ltype
(:string (prin1-to-string value))
(:bytes (integer-to-bytes value :endian :little))
(:big-integer (apply (function integer-to-bytes) value :endian :big (big-integer-attributes ltype)))
(:bytes-noint (error "Please give a vector of bytes, not an integer for ~S" attribute))))
((or string symbol character) (string value))
((or vector list)
(if (every (lambda (element)
(typep element 'octet))
value)
value
(prin1-to-string value)))
(t (prin1-to-string value))))
(value (if (stringp value)
(string-to-utf-8 value)
value)))
(set-attribute-fields attribute atype :uchar
(when value (length value)) ;; TODO: why nil instead of 0?
(when value (foreign-vector-copy-from
(foreign-alloc :uchar :count (length value))
:uchar
(length value) value)))))
((:date)
(let ((value (etypecase value
(integer (multiple-value-bind (se mi ho da mo ye) (decode-universal-time value 0)
(format nil "~4,'0D~2,'0D~2,'0D~2,'0D~2,'0D~2,'0D00"
ye mo da ho mi se)))
(string value))))
(set-attribute-fields attribute atype :uchar (length value)
(foreign-vector-copy-from
(foreign-alloc :uchar :count (length value))
:uchar
(length value) value))))
(otherwise
(unless (consp ltype)
(error "Bad attribute lisp type: ~S from attribute type: ~S" ltype type))
(ecase (first ltype)
((:ulong)
(set-attribute-fields attribute atype :ulong 1
(foreign-alloc :ulong
:initial-element
(if (integerp value)
value
(funcall (second ltype) :encode value)))))
((:array)
(set-attribute-fields attribute atype :uchar
(* (foreign-type-size :ulong)
(length value))
(foreign-vector-copy-from
(foreign-alloc :ulong :count (length value))
:ulong (length value)
value)))
((:attribute)
;; value is a sequence of attributes
(let ((template (template-encode value)))
(set-attribute-fields attribute atype :uchar
(car template) (cdr template))))
(otherwise
(ecase (first (second ltype))
((:ulong)
;; value is a sequence of integers.
(set-attribute-fields attribute atype :uchar
(* (foreign-type-size :ulong)
(length value))
(let ((converter (second (second ltype))))
(foreign-vector-copy-from value :ulong (length value)
(map 'vector (lambda (value)
(if (integerp value)
value
(funcall converter :encode value)))
value))))))))))))
attribute)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Template
(deftype template ()
`(cons integer
#+ccl ccl:macptr
#-ccl (progn (warn "What is the type of foreign pointer in ~A" (lisp-implementation-type))
t)))
(defun template-find-attribute (template atype)
"RETURN: a foreign pointer to the attribute of type ATYPE in the TEMPLATE, or the foreign null pointer."
(check-type template template)
(loop
:with atype := (attribute-type :encode atype)
:with attributes := (cdr template)
:for i :below (car template)
:for attribute := (attr-aptr attributes i)
:unless (null-pointer-p attribute)
:do (when (= (attr-> attribute %ck:type) atype)
(return attribute)))
(null-pointer))
(defun template-free (template)
"TEMPLATE is a cons (count . foreign-vector).
foreign-vector is a CK_ATTRIBUTE[count] array.
This function frees each foreign pointer in the foreign vector, and frees the foreign vector.
The cdr of the TEMPLATE cons cell is set to NIL."
(check-type template template)
(let ((vector (cdr template)))
(dotimes (i (car template))
(let ((attribute (attr-aptr vector i)))
(when (= (logand %ck:+array-attribute+ (attr-> attribute %ck:type))
%ck:+array-attribute+)
(template-free (cons (attr-> attribute %ck:value-len)
(attr-> attribute %ck:value))))))
(foreign-free vector)
(setf (cdr template) nil)
(values)))
(defun attribute-dump (attribute)
"RETURN: ATTRIBUTE"
(let ((*print-circle* nil))
(format t "~1@*~16,'0X~%~0@*~A~2@*type=~4X(hex) ~:*~D(dec)~%~0@*~A~4@*size=~4D~%~0@*~A~5@*value=~16,'0X~%"
*dump-prefix*
(pointer-address attribute)
(attr-> attribute %ck:type)
(attribute-type :decode (attr-> attribute %ck:type))
(attr-> attribute %ck:value-len)
(pointer-address (attr-> attribute %ck:value)))
(if (= %ck:+array-attribute+ (logand %ck:+array-attribute+ (attr-> attribute %ck:type)))
(let ((*dump-prefix* (concatenate 'string *dump-prefix* " ")))
(template-dump (cons (attr-> attribute %ck:value-len)
(attr-> attribute %ck:value))))
(let ((*dump-prefix* (concatenate 'string *dump-prefix* " ")))
(cond ((unavailable-information-p (attr-> attribute %ck:value-len))
(format t "~AType indicates unavailable information.~%" *dump-prefix*))
((null-pointer-p (attr-> attribute %ck:value))
(format t "~AValue is NULL!~%" *dump-prefix*))
((unavailable-information-p (pointer-address (attr-> attribute %ck:value)))
(format t "~AValue indicates unavailable information.~%" *dump-prefix*))
(t
(dump (attr-> attribute %ck:value)
(attr-> attribute %ck:value-len)
:print-characters t))))))
attribute)
(defun validate-pointer (pointer)
"RETURN: POINTER"
(let ((address (pointer-address pointer)))
(assert (/= 0 address) () "Null pointer!")
(assert (/= -1 address) () "Unavailable_information in pointer!")
(assert (< #x10000 address) () "Small address!"))
pointer)
(defun template-dump (template)
"TEMPLATE is a cons (count . foreign-vector).
This function frees each foreign pointer in the foreign vector, and frees the foreign vector.
The cdr of the TEMPLATE cons cell is set to NIL.
RETURN: TEMPLATE"
(check-type template template)
(let ((vector (cdr template))
(*print-circle* nil))
(format t "~&~ADumping template ~S~%" *dump-prefix* template)
(unless (null-pointer-p vector)
(validate-pointer vector)
(dump vector (* (car template) (foreign-type-size '(:struct %ck:attribute))))
(let ((*dump-prefix* (concatenate 'string *dump-prefix* " ")))
(dotimes (i (car template))
(let ((attribute (attr-aptr vector i)))
(format t "~AAttribute[~D]=" *dump-prefix* i)
(let ((*dump-prefix* (concatenate 'string *dump-prefix* " ")))
(attribute-dump attribute))))))
(finish-output)
#-(and)(pause () "dumped"))
template)
(defun attribute-decode (attribute)
"RETURN: a cons cell containing the ATTRIBUTE key value pair,
(:UNAVAILABLE-INFORMATION . NIL) if attribute is invalid, or
NIL if ATTRIBUTE is the foreign null pointer."
(cond
((null-pointer-p attribute)
nil)
((invalid-pointer-p attribute)
'(:unavailable-information))
(t
(let ((type (attr-> attribute %ck:type)))
;; CONS here matches TEMPLATE-ENCODE (atype . value).
(cons (attribute-type :decode type)
(let* ((ltype (or (second (assoc (attribute-type :decode type) *attribute-type-map*))
(error "Unknown attribute type: ~S" type)))
(base-ltype (base-ltype-p ltype))
(len (attr-> attribute %ck:value-len))
(val (attr-> attribute %ck:value)))
(if (or (unavailable-information-p type)
(invalid-pointer-p val)
(unavailable-information-p len))
:unavailable-information
(case base-ltype
((:ulong)
(assert (= (foreign-type-size :ulong) len))
(mem-ref val :ulong))
((:bool)
(if (zerop len)
0 ; libiaspkcs11 returns 0-length values…
(progn
(assert (= (foreign-type-size :uchar) len))
(mem-ref val :uchar))))
((:bytes :bytes-noint :big-integer)
(foreign-vector-copy-to val :uchar len (make-array len :element-type 'octet)))
((:string)
(foreign-string-to-lisp val :count len :encoding :utf-8))
((:date)
(foreign-string-to-lisp val :count len :encoding :utf-8)
#-(and) (let ((date (foreign-string-to-lisp var :count len :encoding :utf-8)))
(encode-universal-time
(parse-integer date :start 12 :end 14 :junk-allowed nil)
(parse-integer date :start 10 :end 12 :junk-allowed nil)
(parse-integer date :start 8 :end 10 :junk-allowed nil)
(parse-integer date :start 6 :end 8 :junk-allowed nil)
(parse-integer date :start 4 :end 6 :junk-allowed nil)
(parse-integer date :start 0 :end 4 :junk-allowed nil)
0)))
(otherwise
(unless (consp ltype)
(error "Bad attribute lisp type: ~S from attribute type: ~S" ltype type))
(ecase (first ltype)
((:ulong)
(funcall (second ltype) :decode (mem-ref val :ulong)))
((:array)
(if (atom (second ltype))
(ecase (second ltype)
((:ulong)
;; value is a sequence of integers.
(foreign-vector-copy-from val :ulong len (make-array len)))
((:attribute)
;; value is a sequence of attributes
(template-decode (cons len val))))
(ecase (first (second ltype))
((:ulong)
;; value is a sequence of integer codes.
(let ((converter (second (second ltype))))
(map 'list (lambda (value)
(funcall converter :encode value))
(foreign-vector-copy-from val :ulong len (make-array len))))))))))))))))))
(defun template-decode (template)
"TEMPLATE: a cons containing the number of attributes and a foreign pointer to the attributes.
RETURN: An a-list of (key . value) decoded attributes."
(check-type template template)
(handler-bind ((error (function invoke-debugger)))
(let ((vector (cdr template))
(result '()))
(dotimes (i (car template) (nreverse result))
(let ((attribute (attr-aptr vector i)))
;; Could test for value-len=-1 and skip those,
;; but attribute-decode returns :unavailable-information for them.
(push (attribute-decode attribute) result))))))
(defun template-allocate-buffers (template)
"Allocates buffers for all the attributes in the template.
TEMPLATE: a cons containing the number of attributes and a foreign pointer to the attributes.
RETURN: TEMPLATE"
(check-type template template)
;; Allocate for the value attribute a buffer of size the value of the attribute value-len.
(let ((vector (cdr template)))
(dotimes (i (car template))
(let ((attribute (attr-aptr vector i)))
(when (null-pointer-p (attr-> attribute %ck:value))
(let ((type (attr-> attribute %ck:type)))
(cond
((or (= type %ck:+a-wrap-template+) (= type %ck:+a-unwrap-template+))
(attribute-allocate-attribute-array attribute))
((= type %ck:+a-allowed-mechanisms+)
(attribute-allocate-ulong-array attribute))
(t
(attribute-allocate-buffer attribute))))))))
template)
(defun template-encode (template)
"Takes a list of (<attribute-type> . <attribute-value>) and
allocates and fills a foreign vector of CK_ATTRIBUTE_PTR and
returns a cons (count . foreign-vector).
For strings, bytes and arrays, if the value is nil, then we set the pValue to NULL."
(check-type template list)
(let* ((count (length template))
(result (foreign-alloc '(:struct %ck:attribute) :count count))
(aborted nil))
(macrolet ()
(unwind-protect
(handler-bind ((error (lambda (condition)
(setf aborted t)
(error condition))))
(loop
;; (atype . value) here matches attribute-decode CONS.
:for (atype . value) :in template
:for i :from 0
:for attribute := (attr-aptr result i)
:do (attribute-fill attribute atype value)
:finally (let ((template (cons count result)))
(return template))))
(when aborted
(template-free (cons count result)))))))
(defun template-pack (template)
"Modifes the template, removing the attributes that have unavailable information values.
RETURN: TEMPLATE
"
(check-type template template)
(loop
:with vector := (cdr template)
:with length := (car template)
:with j := 0
:for i :below length
:for attribute := (attr-aptr vector i)
:do (let ((type (attr-> attribute %ck:type))
(len (attr-> attribute %ck:value-len)))
(unless (or (unavailable-information-p type)
(unavailable-information-p len))
(when (< j i)
(attribute-copy (attr-aptr vector j) attribute))
(incf j)))
:finally (setf (car template) j)
(return template)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Object
(defun create-object (session template)
(check-type session session-handle)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(with-foreign-object (object '%ck:object-handle)
(check-rv (%ck:create-object session (cdr template) (car template) object) "C_CreateObject")
(mem-ref object '%ck:object-handle))
(template-free template))))
(defun copy-object (session old-object template)
(check-type session session-handle)
(check-type old-object object-handle)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(with-foreign-object (object '%ck:object-handle)
(check-rv (%ck:copy-object session old-object (cdr template) (car template) object) "C_CopyObject")
(mem-ref object '%ck:object-handle))
(template-free template))))
(defun destroy-object (session old-object)
(check-type session session-handle)
(check-type old-object object-handle)
(check-rv (%ck:destroy-object session old-object) "C_DestroyObject"))
(defun get-object-size (session object)
(check-type session session-handle)
(check-type object object-handle)
(with-foreign-object (size :ulong)
(check-rv (%ck:get-object-size session object size) "C_GetObjectSize")
(mem-ref size :ulong)))
;; HERE
(defun get-attribute-value (session object template)
(check-type session session-handle)
(check-type object object-handle)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(let ((status
(handler-case
(progn
#+debug (ignore-errors (write-line "Before 1st C_GetAttributeValue") (template-dump template))
(check-rv (%ck:get-attribute-value session object (cdr template) (car template)) "C_GetAttributeValue")
#+debug (ignore-errors (write-line "After 1st C_GetAttributeValue") (template-dump template))
(values))
(:no-error () :ok)
(pkcs11-error (err)
(case (pkcs11-error-label err)
((:attribute-sensitive :attribute-type-invalid :buffer-too-small)
(setf template (template-allocate-buffers (template-pack template)))
;; try again:
(handler-case
(progn
#+debug (ignore-errors (write-line "Before 2nd C_GetAttributeValue") (template-dump template))
(check-rv (%ck:get-attribute-value session object (cdr template) (car template)) "C_GetAttributeValue")
#+debug (ignore-errors (write-line "After 2nd C_GetAttributeValue") (template-dump template))
(values))
(:no-error () :ok)
(pkcs11-error (err)
(case (pkcs11-error-label err)
((:attribute-sensitive :attribute-type-invalid :buffer-too-small)
(pkcs11-error-label err))
(otherwise (error err))))))
(otherwise (error err)))))))
(values (template-decode template) status))
(template-free template))))
(defun set-attribute-value (session object template)
(check-type session session-handle)
(check-type object object-handle)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(check-rv (%ck:set-attribute-value session object (cdr template) (car template))
"C_SetAttributeValue")
(template-free template))))
(defun find-objects-init (session template)
(check-type session session-handle)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(check-rv (%ck:find-objects-init session (cdr template) (car template)) "C_FindObjectsInit")
(template-free template))))
(defun find-objects (session)
(check-type session session-handle)
(let ((buffer-size 128)
(result '()))
(with-foreign-objects ((objects '%ck:object-handle buffer-size)
(count :ulong))
(check-rv (%ck:find-objects session objects buffer-size count) "C_FindObjects")
(dotimes (i (mem-ref count :ulong))
(push (mem-aref objects :ulong i) result)))
(nreverse result)))
(defun find-objects-final (session)
(check-type session session-handle)
(check-rv (%ck:find-objects-final session) "C_FindObjectsFinal"))
(defun find-all-objects (session template)
(check-type session session-handle)
(check-type template list)
(find-objects-init session template)
(unwind-protect
(loop
:for objects := (find-objects session)
:while objects
:append objects)
(find-objects-final session)))
(defun template-from-attribute-type-map (attribute-type-map)
(mapcar (lambda (entry)
;; This CONS here matches attribute-decode CONS.
(cons (first entry)
(let ((type (second entry)))
(if (atom type)
(ecase type
((:ulong) 0)
((:bool) nil)
((:string) nil)
((:bytes :bytes-noint :big-integer) nil)
((:date) "0000000000000000"))
(ecase (first type)
((:ulong) 0)
((:big-integer) nil)
((:array) nil))))))
attribute-type-map))
(defun object-get-all-attributes (session object)
(check-type session session-handle)
(check-type object object-handle)
(get-attribute-value session object
(template-from-attribute-type-map *attribute-type-map*)))
(defun object-get-attributes (session object attributes)
(check-type session session-handle)
(check-type object object-handle)
(get-attribute-value session object
(template-from-attribute-type-map
(remove-if-not (lambda (entry)
(member (first entry) attributes))
*attribute-type-map*))))
;;; Encryption
;; Single block:
;;
;; (progn (encrypt-init session mechanims key)
;; (encrypt bytes [encrypted-length])) -> encrypted-vector
;; Multiple blocks:
;;
;; (loop
;; :with encrypted-blocks := '()
;; :for block :in blocks
;; :initially (encrypt-init session mechanims key)
;; :do (push (encrypt-update session block) encrypted-blocks)
;; :finally (push (encrypt-final session) encrypted-blocks)
;; (return (apply (function concatenate) 'vector (nreverse encrypted-blocks))))n
;;; Decryption
;; Single block:
;;
;; (progn (decrypt-init session mechanims key)
;; (decrypt bytes [decrypted-length])) -> decrypted-vector
;; Multiple blocks:
;;
;; (loop
;; :with decrypted-blocks := '()
;; :for block :in blocks
;; :initially (decrypt-init session mechanims key)
;; :do (push (decrypt-update session block) decrypted-blocks)
;; :finally (push (decrypt-final session) decrypted-blocks)
;; (return (apply (function concatenate) 'vector (nreverse decrypted-blocks))))n
(deftype mechanism () `(or integer keyword list))
(defun set-mechanism (fmechanism mechanism)
;; mechanism is either a mechanism-type integer or keyword, or a list (mechanism-type parameter parameter-length)
(check-type mechanism mechanism)
(setf (foreign-slot-value fmechanism '(:struct %ck:mechanism) '%ck:mechanism) (mechanism-type :encode (if (listp mechanism) (first mechanism) mechanism))
(foreign-slot-value fmechanism '(:struct %ck:mechanism) '%ck:parameter) (or (when (listp mechanism) (second mechanism)) (null-pointer))
(foreign-slot-value fmechanism '(:struct %ck:mechanism) '%ck:parameter-len) (or (when (listp mechanism) (third mechanism)) 0)))
(defmacro define-pkcs11-initializing-function (name low-name c-name &key (keyp t))
`(defun ,name (session mechanism ,@(when keyp `(key)))
(check-type session session-handle)
(check-type mechanism mechanism)
,@(when keyp `((check-type key object-handle)))
(with-foreign-object (fmechanism '(:struct %ck:mechanism))
(set-mechanism fmechanism mechanism)
(check-rv (,low-name session fmechanism ,@(when keyp `(key))) ,c-name))))
(defmacro define-pkcs11-processing-function (name low-name c-name &key (input '()) (outputp t))
"Defines a function to process buffers.
NAME: the symbol naming the defined function.
LOW-NAME: the symbol naming the underlying FFI function.
C-NAME: the string naming the C function (for error reporting).
INPUT: a list of base parameters; additionnal &key parameters will be provided.
OUTPUTP: whether the function returns some output buffer.
NOTE When OUTPUTP, an additionnal &key OUTPUT parameter allow
to pass a pre-allocated buffer. For all the INPUT and
OUTPUT parameters <p>, the additionnal &key <p>-START and
<p>-END parameters are provided to specify the range of
the buffers to use. Those buffers are byte vectors.
RETURN: the OUTPUT byte vector; the position beyond the last byte written.
"
(let ((all-params (append input (when outputp (list 'output)))))
`(defun ,name (session ,@input &key
,@(when outputp `(output))
,@(mapcan (lambda (parameter)
(list `(,(scat parameter '-start) 0)
`(,(scat parameter '-end) (length ,parameter))))
all-params))
(check-type session session-handle)
,@(mapcar (lambda (parameter) `(check-type ,parameter vector)) input)
,@(when outputp `((check-type output (or null vector))))
,@(mapcan (lambda (parameter)
(list `(check-type ,(scat parameter '-start) (integer 0))
`(check-type ,(scat parameter '-end) (integer 0))))
all-params)
(let (,@(mapcar (lambda (parameter)
`(,(scat parameter '-size) (- ,(scat parameter '-end) ,(scat parameter '-start))))
all-params))
(with-foreign-objects (,@(mapcan (lambda (parameter)
(list `(,(scat 'f parameter) :uchar ,(scat parameter '-size))
`(,(scat 'f parameter '-length) :ulong)))
all-params))
,@(mapcan (lambda (parameter)
(list `(foreign-vector-copy-from ,(scat 'f parameter)
:uchar
,(scat parameter '-size)
,parameter
:startl ,(scat parameter '-start)
:endl ,(scat parameter '-end))))
input)
,@(mapcan (lambda (parameter)
(list `(setf (mem-ref ,(scat 'f parameter '-length) :ulong)
,(scat parameter '-size))))
all-params)
(check-rv (,low-name session
,@(mapcan (lambda (parameter) (list (scat 'f parameter) (scat parameter '-size)))
input)
,@(mapcan (lambda (parameter) (list (scat 'f parameter) (scat 'f parameter '-length)))
(when outputp '(output))))
,c-name)
,@(when outputp
`((let ((output (or output (make-array output-end :element-type 'octet)))
(folen (mem-ref foutput-length :ulong)))
(foreign-vector-copy-to foutput :uchar folen
output :startl output-start :endl output-end)
(values output (+ output-start folen))))))))))
(define-pkcs11-initializing-function encrypt-init %ck:encrypt-init "C_EncryptInit")
(define-pkcs11-processing-function encrypt %ck:encrypt "C_Encrypt" :input (clear) :outputp t)
(define-pkcs11-processing-function encrypt-update %ck:encrypt-update "C_EncryptUpdate" :input (clear) :outputp t)
(define-pkcs11-processing-function encrypt-final %ck:encrypt-final "C_EncryptFinal" :input () :outputp t)
(define-pkcs11-initializing-function decrypt-init %ck:decrypt-init "C_DecryptInit")
(define-pkcs11-processing-function decrypt %ck:decrypt "C_Decrypt" :input (crypted) :outputp t)
(define-pkcs11-processing-function decrypt-update %ck:decrypt-update "C_DecryptUpdate" :input (crypted) :outputp t)
(define-pkcs11-processing-function decrypt-final %ck:decrypt-final "C_DecryptFinal" :input () :outputp t)
(define-pkcs11-initializing-function sign-init %ck:sign-init "C_SignInit")
(define-pkcs11-processing-function sign %ck:sign "C_Sign" :input (text) :outputp t)
(define-pkcs11-processing-function sign-update %ck:sign-update "C_SignUpdate" :input (text) :outputp nil)
(define-pkcs11-processing-function sign-final %ck:sign-final "C_SignFinal" :input () :outputp t)
(define-pkcs11-initializing-function sign-recover-init %ck:sign-recover-init "C_SignRecoverInit")
(define-pkcs11-processing-function sign-recover %ck:sign-recover "C_SignRecover" :input (text) :outputp t)
(define-pkcs11-initializing-function verify-init %ck:verify-init "C_VerifyInit")
(define-pkcs11-processing-function verify %ck:verify "C_Verify" :input (text signature) :outputp nil)
(define-pkcs11-processing-function verify-update %ck:verify-update "C_VerifyUpdate" :input (text) :outputp nil)
(define-pkcs11-processing-function verify-final %ck:verify-final "C_VerifyFinal" :input (signature) :outputp nil)
(define-pkcs11-initializing-function verify-recover-init %ck:verify-recover-init "C_VerifyRecoverInit")
(define-pkcs11-processing-function verify-recover %ck:verify-recover "C_VerifyRecover" :input (signature) :outputp t)
(define-pkcs11-initializing-function digest-init %ck:digest-init "C_DigestInit" :keyp nil)
(define-pkcs11-processing-function digest %ck:digest "C_Digest" :input (data) :outputp t)
(define-pkcs11-processing-function digest-update %ck:digest-update "C_DigestUpdate" :input (data) :outputp nil)
(define-pkcs11-processing-function digest-final %ck:digest-final "C_DigestFinal" :input () :outputp t)
(define-pkcs11-processing-function digest-encrypt-update %ck:digest-encrypt-update "C_DigestEncryptUpdate" :input (clear) :outputp t)
(define-pkcs11-processing-function decrypt-digest-update %ck:decrypt-digest-update "C_DecryptDigestUpdate" :input (crypted) :outputp t)
(define-pkcs11-processing-function sign-encrypt-update %ck:sign-encrypt-update "C_SignEncryptUpdate" :input (clear) :outputp t)
(define-pkcs11-processing-function decrypt-verify-update %ck:decrypt-verify-update "C_DecryptVerifyUpdate" :input (crypted) :outputp t)
(defun digest-key (session key)
(check-type session session-handle)
(check-type key object-handle)
(check-rv (%ck:digest-key session key) "C_DigestKey"))
(defun generate-key (session mechanism template)
"Generates a new KEY following the TEMPLATE for the given encrytion MECHANISM.
RETURN: the new key object-handle."
(check-type session session-handle)
(check-type mechanism mechanism)
(check-type template list)
(let ((template (template-encode template)))
(unwind-protect
(with-foreign-objects ((fmechanism '(:struct %ck:mechanism))
(fkey '%ck:object-handle))
(set-mechanism fmechanism mechanism)
(check-rv (%ck:generate-key session fmechanism (cdr template) (car template) fkey) "C_GenerateKey")
(mem-ref fkey '%ck:object-handle))
(template-free template))))
(defun generate-key-pair (session mechanism public-key-template private-key-template)
"Generates a new key pair (public and private keys) following the PUBLIC-KEY-TEMPLATE and PRIVATE-KEY-TEMPLATE for the given encrytion MECHANISM.
RETURN: a list containing the public and private key object-handles."
(check-type session session-handle)
(check-type mechanism mechanism)
(check-type public-key-template list)
(check-type private-key-template list)
(let ((public-key-template (template-encode public-key-template)))
(unwind-protect
(let ((private-key-template (template-encode private-key-template)))
(unwind-protect
(with-foreign-objects ((fmechanism '(:struct %ck:mechanism))
(fpublic-key '%ck:object-handle)
(fprivate-key '%ck:object-handle))
(set-mechanism fmechanism mechanism)
(check-rv (%ck:generate-key-pair session fmechanism
(cdr public-key-template) (car public-key-template)
(cdr private-key-template) (car private-key-template)
fpublic-key
fprivate-key)
"C_GenerateKeyPair")
(list (mem-ref fpublic-key '%ck:object-handle)
(mem-ref fprivate-key '%ck:object-handle)))
(template-free private-key-template)))
(template-free public-key-template))))
#-(and)
(progn
(defun wrap-key (session mechanism wrapping-key key)
(check-type session session-handle)
(check-type mechanism mechanism)
(check-type wrapping-key object-handle)
(check-type key object-handle)
(with-foreign-objects ((fmechanism '(:struct %ck:mechanism))
)
(set-mechanism fmechanism mechanism)
(check-rv (%ck:wrap-key session fmechanism
wrapping-key key
)
"C_WrapKey"))
(defcfun (wrap-key) rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(wrapping-key object-handle)
(key object-handle)
(wrapped-key (:pointer :uchar))
(wrapped-key-len (:pointer :ulong))))
(defcfun (unwrap-key "C_UnwrapKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(unwrapping-key object-handle)
(wrapped-key (:pointer :uchar))
(wrapped-key-len :ulong)
(templ (:pointer (:struct attribute)))
(attribute-count :ulong)
(key (:pointer object-handle)))
(defcfun (derive-key "C_DeriveKey") rv
(session session-handle)
(mechanism (:pointer (:struct mechanism)))
(base-key object-handle)
(templ (:pointer (:struct attribute)))
(attribute-count :ulong)
(key (:pointer object-handle))))
#||
(with-pkcs11
(let ((slotid 0))
(with-open-session (session slotid)
(call-logged-in session slotid (lambda () (encrypt-init session :rsa-pkcs 140415298986736))))))
;; function not supported
(with-pkcs11
(let ((slotid 0))
(with-open-session (session slotid)
(call-logged-in session slotid (lambda () (encrypt-init session :rsa-pkcs 140415299275584))))))
;; function not supported
(with-pkcs11
(let ((slotid 0))
(with-open-session (session slotid)
(call-logged-in session slotid (lambda () (encrypt-init session :rsa-pkcs 140415299275584))))))
(with-pkcs11
(let ((slotid 1))
(with-open-session (session slotid)
(call-logged-in session slotid (lambda () (encrypt-init session :rsa-pkcs 140588238480352))))))
;; function not implemented (with those keys?)
(with-pkcs11
(let ((slotid 1))
(with-open-session (session slotid)
(call-logged-in session slotid (lambda () (get-mechanism-list 0))))))
(with-pkcs11
(get-mechanism-list 1))
(:sha-1 :sha256 :sha384 :sha512 :md5 :ripemd160 4624 :rsa-pkcs :sha1-rsa-pkcs :sha256-rsa-pkcs :rsa-pkcs-key-pair-gen)
||#
(defun seed-random (session seed)
(with-foreign-object (fseed :uchar (length seed))
(dotimes (i (length seed)) (setf (mem-aref fseed :uchar i) (aref seed i)))
(check-rv (%ck:seed-random session fseed (length seed)) "C_SeedRandom")))
(defun generate-random (session length)
(with-foreign-object (frandom :uchar length)
(check-rv (%ck:generate-random session frandom length) "C_GenerateRandom")
(foreign-vector frandom :uchar 'octet length)))
(defun decode-oid (bytes)
;; It looks like the oid stored in iac/ecc are missing the first two numbers…
(list* 2 5 ; iso.ITU-T / X.500
(flexi-streams:with-input-from-sequence (stream bytes)
(asinine:decode-oid stream))))
(defun encode-oid (oid)
(flexi-streams:with-output-to-sequence (stream)
(asinine:encode-oid stream (if (and (= 2 (first oid))
(= 5 (second oid)))
(cddr oid)
oid))))
;; (decode-oid #(232 40 189 8 15 210 80 0 0 16 77 73 79 67 0 1 1 1))
;; --> (2 5 4 29 8 15 10576 0 0 16 77 73 79 67 0 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)
;;;; THE END ;;;;
| 109,269 | Common Lisp | .lisp | 2,009 | 44.111996 | 194 | 0.536913 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f92b60c6f684e8b74f6e7a4a1566afecff793fb0aa223ccfdad5d951738445a6 | 4,910 | [
-1
] |
4,911 | cffi-utils.lisp | informatimago_lisp/clext/pkcs11/cffi-utils.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: cffi-utils.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Small CFFI tools.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2018-04-25 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2018 - 2018
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(defpackage "COM.INFORMATIMAGO.CLEXT.PKCS11.CFFI-UTILS"
(:use "COMMON-LISP" "CFFI")
(:export "*DUMP-PREFIX*" "DUMP"
"FOREIGN-VECTOR" "FOREIGN-VECTOR-COPY-FROM" "FOREIGN-VECTOR-COPY-TO"
"MEMCPY"))
(in-package "COM.INFORMATIMAGO.CLEXT.PKCS11.CFFI-UTILS")
(defun memcpy (destination source byte-count)
(loop
:repeat byte-count
:do (setf (mem-ref destination :uchar) (mem-ref source :uchar))
(incf-pointer destination)
(incf-pointer source)
:finally (return destination)))
(defun foreign-vector-copy-from (pointer ctype size lisp-vector
&key (convert (function identity))
(startf 0) (startl 0) (endl (length lisp-vector)))
"Copies SIZE elements from the lisp subsequence: VECTOR STARTL ENDL, to
the foreign vector of CTYPE at POINTER offset by STARTF, each
element being transformed by the CONVERT function.
Returns POINTER."
"Copies SIZE elements from the lisp VECTOR to the foreign vector of CTYPE at POINTER.
Returns the destination POINTER."
(loop
:repeat size
:for i :from startf
:for j :from startl :below endl
:do (setf (mem-aref pointer ctype i) (funcall convert (elt lisp-vector j)))
:finally (return pointer)))
(defun foreign-vector-copy-to (pointer ctype size lisp-vector
&key (convert (function identity))
(startf 0) (startl 0) (endl (length lisp-vector)))
"Copies SIZE elements from the foreign vector of CTYPE at POINTER
offset by STARTF, to the lisp subsequence: LISP-VECTOR STARTL ENDL,
each element being transformed by the CONVERT function.
Returns the destination LISP-VECTOR."
(loop
:repeat size
:for i :from startf
:for j :from startl :below endl
:do (setf (elt lisp-vector j) (funcall convert (mem-aref pointer ctype i)))
:finally (return lisp-vector)))
(defun foreign-vector (pointer ctype ltype size)
(foreign-vector-copy-to pointer ctype size (make-array size :element-type ltype)))
(defun foreign-null-terminated-vector-length (pointer ctype)
(loop
:for i :from 0
:until (zerop (mem-aref pointer ctype i))
:finally (return i)))
(defun foreign-null-terminated-vector (pointer ctype ltype size &key (convert (function identity)))
(declare (ignore size)) ; TODO: or use it as max???
(let ((len (foreign-null-terminated-vector-length pointer ctype)))
(foreign-vector-copy-to pointer ctype len (make-array len :element-type ltype) :convert convert)))
(defvar *dump-prefix* "")
(defun dump (pointer size &key print-characters)
(let ((*print-circle* nil))
(loop
:for i :from 0 :by 16
:while (< i size)
:do (format t "~&~A~16,'0X: " *dump-prefix* (+ i (cffi:pointer-address pointer)))
(loop
:repeat 16
:for j :from i
:if (< j size)
:do (format t "~2,'0X " (cffi:mem-aref pointer :uint8 j))
:else
:do (write-string " "))
(when print-characters
(loop
:repeat 16
:for j :from i
:if (< j size)
:do (format t "~C" (let ((code (cffi:mem-aref pointer :uint8 j)))
(if (<= 32 code 126)
(code-char code)
#\.)))
:else
:do (write-string " "))))
:finally (terpri)))
;;;; THE END ;;;;
| 4,827 | Common Lisp | .lisp | 112 | 36.642857 | 102 | 0.604211 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | f8e0cc55a31eab0a6659a7003eea3579a744276050f40d02fed6c02da60469ba | 4,911 | [
-1
] |
4,912 | run-program-test.lisp | informatimago_lisp/clext/run-program/run-program-test.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: run-program-test.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Tests the run-program function.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2012-03-25 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST"
(:use "COMMON-LISP"
"COM.INFORMATIMAGO.COMMON-LISP.CESARUM.SIMPLE-TEST"
"COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM")
(:export "TEST/RUN-PROGRAM")
(:documentation "
"))
(in-package "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM.TEST")
(defun dump-stream (stream)
(loop :for line = (read-line stream nil nil) :while line :do (write-line line)))
(defun dump-file (path)
(with-open-file (inp path) (dump-stream inp)))
(defun text-file-contents (path)
(with-open-file (inp path)
(loop
:for line = (read-line inp nil nil)
:while line :collect line)))
(defun text-stream-contents (inp)
(loop
:for line = (read-line inp nil nil)
:while line :collect line))
(defun create-test-input-file ()
(with-open-file (testinp "TESTINP.TXT"
:direction :output
:if-exists :supersede
:if-does-not-exist :create)
(write-string "Hao
Wang
logicien
americain
algorithme
en
question
a
ete
publie
en
1960
dans
IBM
Journal
"
testinp)))
(defun check-sorted-output-stream (stream)
(let ((stream-contents (text-stream-contents stream))
(sorted-list (sort (copy-seq '("Hao" "Wang" "logicien" "americain"
"algorithme" "en" "question" "a" "ete" "publie"
"en" "1960" "dans" "IBM" "Journal"))
(function string<))))
(check equal sorted-list stream-contents
() "~%~20A=~S~%~20A=~S~%"
"sorted-list" sorted-list
"stream-contents" stream-contents)))
(defun check-sorted-output-file ()
(with-open-file (stream "TESTOUT.TXT")
(check-sorted-output-stream stream)))
(defvar *verbose* nil)
(define-test test/run-program (&key ((:verbose *verbose*) *verbose*))
(create-test-input-file)
(assert-true (zerop (process-status (run-program "true" '() :wait t))))
(assert-true (zerop (process-status (prog1 (run-program "true" '() :wait nil)
(sleep 1)))))
(assert-true (plusp (process-status (run-program "false" '() :wait t))))
(assert-true (plusp (process-status (prog1 (run-program "false" '() :wait nil)
(sleep 1)))))
(run-program "true" '() :wait nil :error "TESTERR.TXT")
(sleep 1)
(check equal '() (text-file-contents "TESTERR.TXT"))
(run-program "true" '() :wait t :error "TESTERR.TXT")
(check equal '() (text-file-contents "TESTERR.TXT"))
(let ((process (run-program "sh" '("-c" "echo error 1>&2")
:wait nil :input nil :output nil :error :stream)))
(check equal '("error")
(unwind-protect
(text-stream-contents (process-error process))
(close (process-error process)))))
(ignore-errors (delete-file "TESTERR.TXT"))
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error "TESTERR.TXT")
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(with-open-file (err "TESTERR.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock
)
(run-program "sh" '("-c" "echo error 1>&2")
:wait t :input nil :output nil :error err))
(check equal '("error") (text-file-contents "TESTERR.TXT"))
(run-program "printf" '("Hello\\nWorld\\n") :wait t)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil)
(let ((process (run-program "printf" '("Hello\\nWorld\\n") :wait nil :output :stream)))
(check equal '("Hello" "World")
(unwind-protect
(loop
:for line = (read-line (process-output process) nil nil)
:while line :collect line)
(close (process-output process)))))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait nil :output out)
(sleep 1))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "printf" '("Hello\\nWorld\\n") :wait t :output out))
(check equal '("Hello" "World") (text-file-contents "TESTOUT.TXT"))
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input "TESTINP.TXT" :output "TESTOUT.TXT")
(sleep 1)
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input "TESTINP.TXT" :output out))
(check-sorted-output-file)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output "TESTOUT.TXT"))
(check-sorted-output-file)
(with-open-file (out "TESTOUT.TXT"
:direction :output :if-does-not-exist :create :if-exists :supersede
#+ccl :sharing #+ccl :lock)
(with-open-file (inp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait t :input inp :output out)))
(check-sorted-output-file)
(let ((process (run-program "sort" '() :environment '(("LC_CTYPE" . "C") ("LC_COLLATE" . "C"))
:wait nil :input :stream :output :stream :error nil)))
(with-open-file (testinp "TESTINP.TXT"
#+ccl :sharing #+ccl :lock)
(loop :for line = (read-line testinp nil nil)
:while line :do (write-line line (process-input process))))
(close (process-input process))
(check-sorted-output-stream (process-output process))
(close (process-output process)))
(mapc (lambda (file) (ignore-errors (delete-file file)))
'("TESTINP.TXT" "TESTOUT.TXT" "TESTERR.TXT")))
(defun test/all ()
(test/run-program :verbose nil))
;;;; THE END ;;;;
| 8,029 | Common Lisp | .lisp | 179 | 37.189944 | 98 | 0.576775 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 6c87989a5aa5815029331325cdffa353094e47d1397199099a12ee5bb0d24a00 | 4,912 | [
-1
] |
4,913 | run-program.lisp | informatimago_lisp/clext/run-program/run-program.lisp | ;;;; -*- mode:lisp;coding:utf-8 -*-
;;;;**************************************************************************
;;;;FILE: run-program.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; This package exports a stand alone RUN-PROGRAM function that
;;;; runs on various implementations.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2015-03-15 <PJB> Updated.
;;;; 2012-03-24 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2012 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;**************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM"
(:use "COMMON-LISP")
#+allegro (:use "EXCL" "EXCL.OSI" )
#+clisp (:use "EXT" "POSIX")
#+ecl (:use "EXT")
#+(or abcl cmu) (:use "EXTENSIONS")
#+clozure (:use "CCL")
#+sbcl (:use "SB-EXT")
(:shadow "MAKE-PROCESS"
. #1=("RUN-PROGRAM"
"PROCESS"
"PROCESS-P"
"PROCESS-ALIVE-P"
"PROCESS-INPUT"
"PROCESS-OUTPUT"
"PROCESS-ERROR"
"PROCESS-PID"
"PROCESS-STATUS"
"PROCESS-SIGNAL"))
(:export . #1#)
(:documentation "
"))
(in-package "COM.INFORMATIMAGO.CLEXT.RUN-PROGRAM")
;;;---------------------------------------------------------------------
;;; PROCESS
;;;---------------------------------------------------------------------
;; RUN-PROGRAM returns a PROCESS structure.
;; (PROCESS-ALIVE-P p) indicates whether the process p is still running (it calls waitpid).
;; if the process is alive, then:
;; (PROCESS-INPUT p) returns the input stream of the process, (an output-stream).
;; (PROCESS-OUTPUT p) returns the output stream of the process, (an input-stream).
;; (PROCESS-ERROR p) returns the error stream of the process, (an input-stream).
;; Either stream may be NIL, depending on the :input, :output and
;; :error arguments of RUN-PROGRAM.
;; (PROCESS-PID p) returns the PID of the process.
;; When the process is no more alive:
;; (PROCESS-STATUS p) returns the exit status of the process
;; (PROCESS-SIGNAL p) returns the signal that killed the process (only on unix).
(defstruct process
"The result of RUN-PROGRAM"
#+(or abcl clozure cmu sbcl scl) process
#+(or allegro clisp) input
#+(or allegro clisp) output
#+(or allegro clisp) error
#+(or allegro clisp) pid
#+(or allegro clisp) %exit-status
#+(or allegro clisp) signal
program arguments environment)
(defun decode-unix-status (status)
(values (ldb (byte 7 0) status)
(ldb (byte 9 7) status)))
#+(or allegro clisp)
(defun process-status (process)
(or (process-%exit-status process)
#+allegro (multiple-value-bind (exit-status pid signal)
(WAITPID (process-pid process) :wnohang t)
(declare (ignore pid))
(when exit-status
(setf (process-signal process) signal
(process-%exit-status process) exit-status)))
#+clisp (multiple-value-bind (pid how status)
(handler-case
(WAIT :PID (process-pid process)
:NOHANG t
:UNTRACED nil :STOPPED nil :EXITED t
:CONTINUED nil :NOWAIT nil)
(OS-ERROR (err)
(format *trace-output* "~%Got os-error ~A~%" err)
(finish-output *trace-output*)
(values nil :exited 0)))
;; (declare (ignore pid))
(format *trace-output* "~%Got wait result: pid = ~A how = ~A status = ~A~%"
pid how status)
(finish-output *trace-output*)
(case how
(:exited (setf (process-%exit-status process) status))
(:signaled (setf (process-signal process) status
(process-%exit-status process) (- status)))))))
#+(or allegro clisp)
(defun process-alive-p (process)
"Whether the process is still running."
(not (process-status process)))
#+(or abcl cmu clozure sbcl)
(defun process-alive-p (process)
#+(or abcl cmu sbcl) (process-alive-p (process-process process))
#+clozure (eql (external-process-status (process-process process)) :running))
#+(or abcl cmu clozure sbcl)
(defun process-input (process)
#+(or abcl cmu sbcl) (process-input (process-process process))
#+clozure (external-process-input-stream (process-process process)) )
#+(or abcl cmu clozure sbcl)
(defun process-output (process)
#+(or abcl cmu sbcl) (process-output (process-process process))
#+clozure (external-process-output-stream (process-process process)))
#+(or abcl cmu clozure sbcl)
(defun process-error (process)
#+(or abcl cmu sbcl) (process-error (process-process process))
#+clozure (external-process-error-stream (process-process process)) )
#+(or abcl cmu clozure sbcl)
(defun process-pid (process)
#+abcl (declare (ignore process))
#+abcl -1 ; no process-pid in abcl
#+(or cmu sbcl) (process-pid (process-process process))
#+clozure (ccl::external-process-pid (process-process process)))
#+(or abcl cmu clozure sbcl)
(defun process-status (process)
#+abcl (process-exit-code (process-process process))
#+(or cmu sbcl) (process-status (process-process process))
#+clozure (nth-value 1 (external-process-status (process-process process))))
;;;---------------------------------------------------------------------
;;; RUN-PROGRAM
;;;---------------------------------------------------------------------
(defun run-program (program arguments &key (wait t) (input nil) (output nil) (error nil)
(input-element-type 'character)
(input-external-format :default)
(output-element-type 'character)
(output-external-format :default)
(environment nil environmentp))
"Runs the program with the given list of arguments.
If WAIT is true, then run-program returns only when the program is
finished, otherwise, it returns as soon as the program is launched,
and the caller must call PROCESS-ALIVE-P or PROCESS-STATUS on the
resulting process, to check when the program is finished.
INPUT, OUTPUT and ERROR specify the redirection of the stdin, stdout
and stderr of the program. They can be NIL (/dev/null), :stream (a
pipe with the lisp process is created), a string or pathname to
redirect to or from a file, or a file or socket stream to redirect to
or from it.
ENVIRONMENT is an alist of STRINGs (name . value) describing the new
environment. The default is to copy the environment of the current
process.
"
(declare (ignorable input-element-type input-external-format
output-element-type output-external-format))
(check-type input (or null (member :stream) string pathname stream))
(check-type output (or null (member :stream) string pathname stream))
(check-type error (or null (member :stream) string pathname stream))
#+allegro
(if wait
(multiple-value-bind (exit-status signal)
(decode-unix-status
(apply (function run-shell-command)
(concatenate 'vector (list program program) arguments)
:wait t
:input input :if-input-does-not-exist :error
:output output :if-output-exists :supersede
:error-output error :if-error-output-exists :supersede
:separate-streams t
(when environmentp (list :environment environment))))
(make-process :%exit-status exit-status :signal signal
:program program
:arguments arguments
:environment (if environmentp environment :inherit)))
(multiple-value-bind (inp out err pid)
(apply (function run-shell-command)
(concatenate 'vector (list program program) arguments)
:separate-streams t
:wait nil
:input input :if-input-does-not-exist :error
:output output :if-output-exists :supersede
:error-output error :if-error-output-exists :supersede
(when environmentp (list :environment environment)))
(make-process :input inp :output out :error err :pid pid
:program program
:arguments arguments
:environment (if environmentp environment :inherit))))
;; clisp make-{input,output,io}-pipe an run-program don't work with
;; stderr. The only function that allows to redirect stderr is
;; ext::launch. It takes streams (with underlying file
;; descriptor/handle), nil, :pipe or :terminal.
#+clisp
(labels ((run (input-stream output-stream error-stream)
(multiple-value-bind (pid-or-status inp out err)
(ext::launch program :ARGUMENTS arguments
:WAIT wait
:INPUT input-stream
:OUTPUT output-stream
:ERROR error-stream
:BUFFERED t
:ELEMENT-TYPE output-element-type
:EXTERNAL-FORMAT output-external-format)
(make-process :input inp :output out :error err
(if wait :%exit-status :pid) pid-or-status
:program program
:arguments arguments
:environment (if environmentp environment :inherit))))
(call-with-stream (direction thing thunk)
(check-type direction (member :input :output))
(let ((if-does-not-exist :create)
(if-exists :supersede))
(typecase thing
(null
(funcall thunk nil))
((or string pathname)
(let ((path (pathname thing)))
(with-open-file (stream path
:direction direction
:if-exists if-exists
:if-does-not-exist if-does-not-exist)
(funcall thunk stream))))
(stream
(funcall thunk stream))
((member :stream)
(funcall thunk :pipe))))))
(call-with-stream :input input
(lambda (input)
(call-with-stream :output output
(lambda (output)
(call-with-stream :output error
(lambda (error)
(run input output error))))))))
#+abcl
(let ((process (make-process :process (apply (function run-program) program arguments
:wait nil
(when environmentp
(list :environment environment)))
:program program
:arguments arguments
:environment (if environmentp environment :inherit))))
;; Note this is susceptible to deadlocks, depending on the
;; read/write pattern of the command. It's up to the caller to
;; pass :stream and to deal with it itself.
(flet ((copy-stream (inp out)
(loop
:for line = (read-line inp nil nil)
:while line
:do (write-line line out))))
(typecase input
(null (close (process-input process)))
((or string pathname) (with-open-file (inp input)
(unwind-protect
(copy-stream inp (process-input process))
(close (process-input process)))))
(stream (unwind-protect
(copy-stream input (process-input process))
(close (process-input process))))))
(flet ((call-with-streams (argument-stream process-stream thunk)
(typecase argument-stream
(null (close process-stream)
(funcall thunk nil nil))
((or string pathname) (with-open-file (out argument-stream
:direction :output
:if-does-not-exist :create
:if-exists :supersede)
(unwind-protect
(funcall thunk process-stream out)
(close process-stream))))
(stream (unwind-protect
(funcall thunk process-stream argument-stream)
(close process-stream)))
(otherwise (funcall thunk nil nil)))))
(call-with-streams output (process-output process)
(lambda (out-in out-out)
(call-with-streams error (process-error process)
(lambda (err-in err-out)
(loop :while (or out-in err-in) :do
(when out-in
(let ((line (read-line out-in nil nil)))
(if line
(write-line line out-out)
(setf out-in nil))))
(when err-in
(let ((line (read-line err-in nil nil)))
(if line
(write-line line err-out)
(setf err-in nil))))))))))
(when wait
(loop :while (process-alive-p process) :do (sleep 0.1)))
process)
#+clozure
(flet ((wrap-stream (direction stream)
;; Since stream may not be shared, we make a new stream for
;; the process.
(declare (ignore direction)) stream #-(and)
(typecase stream
(stream (ccl::make-basic-stream-instance
(find-class (if (eql :input direction)
'ccl::basic-file-character-input-stream
'ccl::basic-file-character-output-stream))
:stream-device (ccl::stream-device stream direction)
:direction direction
:element-type output-element-type
:encoding output-external-format
:line-termination #+windows :windows #-windows :unix
:sharing :lock
:auto-close t))
(otherwise stream))))
(make-process
:process (apply (function ccl:run-program)
program arguments
:wait wait
:input (wrap-stream :input input) :if-input-does-not-exist :error
:output (wrap-stream :output output) :if-output-exists :supersede
:error (wrap-stream :error error) :if-error-exists :supersede
:element-type output-element-type
:external-format (list :domain nil
:character-encoding output-external-format
:line-termination #+windows :windows #-windows :unix)
:sharing :lock
(when environmentp
(list :env environment)))
:program program
:arguments arguments
:environment (if environmentp environment :inherit)))
;; Note; in ecl run-program the :error arguments are limited to
;; :output nil t and string/pathname, no :stream :-(
#+ecl
(make-process :process (EXT:RUN-PROGRAM program arguments
:wait wait
:input input
:output output
:error error)
:program program
:arguments arguments
:environment (if environmentp environment :inherit))
#+sbcl
(make-process :process (sb-ext:run-program
program arguments
:wait wait
:input input :if-input-does-not-exist :error
:output output :if-output-exists :supersede
:error error :if-error-exists :supersede
:external-format output-external-format
:search #+win32 t #-win32 nil)
:program program
:arguments arguments
:environment (if environmentp environment :inherit))
#+(or cmu scl)
(make-process :process (ext:run-program
program arguments
:wait wait
:input input :if-input-does-not-exist :error
:output output :if-output-exists :supersede
:error error :if-error-exists :supersede)
:program program
:arguments arguments
:environment (if environmentp environment :inherit))
#-(or allegro clisp abcl clozure cmu ecl sbcl scl)
(error "~S not implemented for ~A" 'run-program
(lisp-implementation-version)))
;;--------------------------------------------------
;; Not necessary: ext::launch takes :pipe arguments.
;;--------------------------------------------------
;;
;;
;;
;;
;;
;; #+(and clisp unix) (ffi:def-call-out pipe (:name "pipe")
;; (:arguments (pipefd (FFI:C-PTR (FFI:C-ARRAY FFI:INT 2)) :out :alloca))
;; (:return-type ffi:int)
;; (:language :stdc)
;; (:library *libc*))
;; #+(and clisp unix) (ffi:def-c-const +cmd-setfd+ (:name "F_SETFD") (:type ffi:int))
;; #+(and clisp unix) (ffi:def-c-const +fd-close-on-exec+ (:name "FD_CLOEXEC") (:type ffi:int))
;; #+(and clisp unix) (ffi:def-c-const +cmd-setfl+ (:name "F_SETFL") (:type ffi:int))
;; #+(and clisp unix) (ffi:def-c-const +fl-non-block+ (:name "O_NONBLOCK") (:type ffi:int))
;; #+(and clisp unix) (ffi:def-call-out fcntl (:name "fcntl")
;; (:arguments (fd ffi:int :in)
;; (cmd ffi:int :in)
;; (flag ffi:long :in))
;; (:return-type ffi:int)
;; (:language :stdc)
;; (:library *libc*))
;;
;; #+(and clisp win32) (ffi:def-c-type handle ffi:c-pointer)
;; #+(and clisp win32) (ffi:def-c-type dword ffi:uint32)
;; #+(and clisp win32) (ffi:def-c-type word ffi:uint16)
;; #+(and clisp win32) (ffi:def-c-type bool ffi:uint8)
;;
;; #+(and clisp win32) (ffi:def-c-type SECURITY-ATTRIBUTES
;; (ffi:c-struct vector
;; (nlength dword)
;; (lpsecuritydescriptor ffi:c-pointer)
;; (binherithandle bool)))
;;
;; #+(and clisp win32) (ffi:def-call-out create-pipe (:name "CreatePipe")
;; (:arguments (hreadpipe (ffi:c-ptr handle) :out)
;; (hwritepipe (ffi:c-ptr handle) :out)
;; (lppipeattributes (ffi:c-pointer security-attributes) :in)
;; (nsize dword :in))
;; (:return-type bool)
;; (:language :stdc-stdcall)
;; (:library "kernel32.dll"))
;;
;; #+clisp
;; (defun make-pipe ()
;; "Returns two streams, an output stream writing to the pipe and an
;; input stream reading from the pipe."
;; (flet ((ms (fd dir)
;; (ext:make-stream fd
;; :direction dir
;; :element-type 'character
;; :external-format CUSTOM:*DEFAULT-FILE-ENCODING*
;; :buffered t)))
;; #+unix
;; (multiple-value-bind (ret pipes) (pipe)
;; (if (zerop ret)
;; (values (ms (aref pipes 1) :output)
;; (ms (aref pipes 0) :input))
;; (error "pipe(): returned ~A" ret)))
;; #+win32
;; (multiple-value-bind (ret pipe-read pipe-write) (create-pipe nil 4096)
;; (if (zerop ret)
;; (error "pipe(): returned ~A" ret)
;; (values (ms (FFI:FOREIGN-ADDRESS-UNSIGNED pipe-write) :output)
;; (ms (FFI:FOREIGN-ADDRESS-UNSIGNED pipe-read) :input))))
;; #-(or unix win32)
;; (error "~S not implemented for this target" 'make-pipe)))
;; Note: While it may seem reasonable to write:
;;
;; (with-open-file (err "TESTERR.TXT"
;; :direction :output :if-does-not-exist :create
;; :if-exists :supersede)
;; (write-line "The error output of the command is:" err)
;; (finish-output err)
;; (run-program "sh" '("-c" "echo error 1>&2")
;; :wait t :input nil :output nil :error err)
;; (write-line "That was the error output of the command." err))
;;
;; and even:
;;
;; (with-open-file (inp "TESTINP.TXT")
;; (read-line inp) ; eat the first line
;; (run-program "bash" '("-c" "read line ; exit 0")
;; :wait t :input inp :output nil :error nil)
;; (read-line inp))
;;
;; In both cases, since we have dup'ed the file descriptor in the
;; parent and child processes, we have two file positions, and
;; therefore the I/O done by the parent after the child is run will
;; overwrite or read the data written or read by the child.
;; Some implementations copy the input filee to a temporary file, and
;;
;;;; THE END ;;;;
| 24,638 | Common Lisp | .lisp | 472 | 38.319915 | 120 | 0.494507 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 35ec456131d6fd8cc81c789dff894b6eab9d15645d322b783ddcb4876daae01f | 4,913 | [
-1
] |
4,914 | cliki.lisp | informatimago_lisp/cl-loaders/cliki.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cliki.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Loads cliki under sbcl.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-12-25 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(if (string= (lisp-implementation-type) "SBCL")
(sb-ext:without-package-locks (require 'cliki))
(format t "~&cliki works only on SBCL~%"))
| 1,564 | Common Lisp | .lisp | 38 | 39.947368 | 83 | 0.59252 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | da40e90f640cde70eb96ed3529c74b6aa346ef0be4405aaa9a1c7cdf145850a1 | 4,914 | [
-1
] |
4,915 | uffi.lisp | informatimago_lisp/cl-loaders/uffi.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: uffi.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; UFFI loader.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2003-06-05 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2003 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(unless (find-package "ASDF")
(load "LOADER:CCLAN.LISP"))
(push (directory-namestring (translate-logical-pathname "UFFI:UFFI.ASD"))
asdf:*central-registry*)
(asdf:operate 'asdf:load-op :uffi)
;;;; uffi.lisp -- 2003-06-05 21:06:08 -- pascal ;;;;
| 1,689 | Common Lisp | .lisp | 41 | 39.853659 | 83 | 0.587591 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | c6a2a9a90fbec64d7ecd9514237b1e195623cfa4732651f4e209f7c01cb76b56 | 4,915 | [
-1
] |
4,916 | stumpwm.lisp | informatimago_lisp/cl-loaders/stumpwm.lisp | ;;;; -*- coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load "loaders:clocc")
(load "port:shell")
(load "loaders:cclan")
(push "/usr/local/src/stumpwm/" asdf:*central-registry*)
(asdf:operate 'asdf:load-op 'stumpwm)
(stumpwm:stumpwm "" :display 1)
| 318 | Common Lisp | .lisp | 9 | 34 | 56 | 0.704545 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 6f3bef989506c7b55cab4fc686646ff60dcf99135ff6e9eb7aaaa69cba4c7881 | 4,916 | [
-1
] |
4,917 | plisp.lisp | informatimago_lisp/cl-loaders/plisp.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: plisp.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Loader for the plisp package.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-10-05 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(defpackage "COM.1729.PLISP"
(:use "COMMON-LISP")
(:export "PS-INIT" "PS-COMPILE"))
(in-package "COM.1729.PLISP")
;;; This builds an executable postscript compiler
(load "PACKAGES:COM;1729;PLISP;COMPILER;VARS") ; has defvars
(load "PACKAGES:COM;1729;PLISP;COMPILER;MACROS") ; useful macros
(load "PACKAGES:COM;1729;PLISP;COMPILER;TOP") ; top level control
(load "PACKAGES:COM;1729;PLISP;COMPILER;COMPILE") ; guts of the compilation process
(load "PACKAGES:COM;1729;PLISP;COMPILER;OUTPUT") ; output routines
(load "PACKAGES:COM;1729;PLISP;COMPILER;DEFPS") ; definitions of postscript functions
(load "PACKAGES:COM;1729;PLISP;COMPILER;ARGS")
(load "PACKAGES:COM;1729;PLISP;COMPILER;NAMES")
(load "PACKAGES:COM;1729;PLISP;COMPILER;FLOW")
(load "PACKAGES:COM;1729;PLISP;COMPILER;UTIL")
;; Simple-minded iteration through the common-lisp directory -
;; may need changing depending of OS
;; (LET ((DIR "PACKAGES:COM;1729;PLISP;COMMON-LISP;"))
;; (DOLIST (X '("BIND" "CONTROL" "FUNCTIONAL" "LISP-UTIL"
;; "LOOP" "MVALUES" "NUMERIC" "FOR"))
;; (LOAD (CONCATENATE 'STRING DIR X))))
;; This only needs to be done once. ps-init is in defps
(ps-init)
;;;; plisp.lisp -- -- ;;;;
| 2,690 | Common Lisp | .lisp | 59 | 44.288136 | 88 | 0.632684 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 7a1d23517bb68b3b752fd68ba35dbfb32b9c88a62c22ec25e6c9e3038bb6eb3e | 4,917 | [
-1
] |
4,918 | lmud.lisp | informatimago_lisp/cl-loaders/lmud.lisp | ;;;; -*- coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(dolist (file '(split-sequence
defpkg
mixins
attributes
species
thing
universe
comestible
living
character
room
dice
commands
comdefs
driver))
(load (merge-pathnames (make-pathname :name (string file)
:version :newest)
"PACKAGES:NET;COMMON-LISP;LMUD;LMUD;")))
;;;; lmud.lisp -- -- ;;;;
| 772 | Common Lisp | .lisp | 22 | 19.954545 | 77 | 0.394102 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | e58c8678fd132e6ee14bba05aae0f71d36fdf4a1cc9cf4d04fae3590432f8d70 | 4,918 | [
-1
] |
4,919 | pseudo.lisp | informatimago_lisp/cl-loaders/pseudo.lisp | ;;;; -*- coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
;; LOADER:PSEUDO.LISP
;; ----------------------------------------------------------------------
;; -- PSEUDO -- Pseudo-Scheme --
;; -----------------------------
(in-package :common-lisp-user)
(defvar *pseudoscheme-directory* *default-pathname-defaults*)
(defvar *use-scheme-read* nil)
(defvar *use-scheme-write* t)
(pushnew :unix *features*)
(progn
(load (com.informatimago.tools.pathname:translate-logical-pathname #P"PACKAGES:EDU;MIT;AI;PSEUDO;LOADIT"))
(load-pseudoscheme (com.informatimago.tools.pathname:translate-logical-pathname #P"PACKAGES:EDU;MIT;AI;PSEUDO;")))
(defun scheme () (ps:scheme))
(format t "~2%Use: (scheme)~2%")
;;;; THE END ;;;;
| 787 | Common Lisp | .lisp | 18 | 42.111111 | 116 | 0.623037 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | b5dafd36f81e2849d0b90f452b857cffa1ff7b1637106a5da0cd610696a0c2ea | 4,919 | [
-1
] |
4,920 | clx.lisp | informatimago_lisp/cl-loaders/clx.lisp | ;;;; -*- coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(in-package "COMMON-LISP-USER")
#+sbcl (progn
(load "db-sockets")
(pushnew :db-sockets *features*) )
#+clisp (defparameter saved-wofpc custom:*warn-on-floating-point-contagion*)
#+clisp (setq custom:*warn-on-floating-point-contagion* nil)
(let ((home (or #+sbcl (sb-ext:posix-getenv "HOME")
#+clisp (ext:getenv "HOME")
"/home/pascal")))
(setf (logical-pathname-translations "HOME")
(list
(list "**;*.*" (concatenate 'string home "/**/*.*"))
(list ";**;*.*" (concatenate 'string home "/**/*.*")))))
(pushnew :clx-debugging *features*)
(defparameter *clx-sources*
'(
;; First load port:
"clocc:clocc;src;port;ext"
"clocc:clocc;src;port;gray"
"clocc:clocc;src;port;path"
"clocc:clocc;src;port;sys"
"clocc:clocc;src;port;net"
"clocc:clocc;src;port;proc"
;; Then split-sequence
"clocc:clocc;src;defsystem-4;src;utilities;split-sequence"
;; Then load the true system:
"clocc:clocc;src;gui;clx;package"
"clocc:clocc;src;gui;clx;depdefs"
"clocc:clocc;src;gui;clx;clx"
"clocc:clocc;src;gui;clx;dependent"
"clocc:clocc;src;gui;clx;macros" ; these are just macros
"clocc:clocc;src;gui;clx;bufmac" ; these are just macros
"clocc:clocc;src;gui;clx;buffer"
"clocc:clocc;src;gui;clx;display"
"clocc:clocc;src;gui;clx;gcontext"
"clocc:clocc;src;gui;clx;input"
"clocc:clocc;src;gui;clx;requests"
"clocc:clocc;src;gui;clx;fonts"
"clocc:clocc;src;gui;clx;graphics"
"clocc:clocc;src;gui;clx;text"
"clocc:clocc;src;gui;clx;attributes"
"clocc:clocc;src;gui;clx;translate"
"clocc:clocc;src;gui;clx;keysyms"
"clocc:clocc;src;gui;clx;manager"
"clocc:clocc;src;gui;clx;image"
"clocc:clocc;src;gui;clx;resource"
"clocc:clocc;src;gui;clx;shape"
;; Then hello world!
"clocc:clocc;src;gui;clx;demo;hello"
))
(dolist (file *clx-sources*) (load file))
#+clisp (setq custom:*warn-on-floating-point-contagion* saved-wofpc)
(defun compile-clx ()
(dolist (file *clx-sources*)
(format t "Compiling ~A~%" file)
(load (compile-file file))))
(defun test-clx ()
(xlib::hello-world ""))
(load "PACKAGE:CLX-DEMOS;QIX.LISP")
(load "PACKAGE:CLX-DEMOS;SOKOBAN.LISP")
;; note: sokoban only works with clisp clx for it needs xpm extension.
;; With common-lisp-controller: (please note that the patches included in
;; the clocc-port subdirectory have not yet been send upstream, so the
;; cvs and cclan version won't do)
;; Put the source in for example ~/common-lisp/src/clx and add the
;; following to your startup script ( ~/.sbclrc or ~/.cmucl-init.lisp)
;; |;;; -*- Mode: Lisp; Package: USER; Base: 10; Syntax: Common-Lisp -*-
;; |
;; |(load "/etc/sbclrc")
;; |
;; |(format t "Hello Peter!~%")
;; |
;; |(common-lisp-controller:add-project-directory
;; | #p"/home/pvaneynd/common-lisp/src/"
;; | #p"/home/pvaneynd/common-lisp/fasl-sbcl/"
;; | '("CLX")
;; | "/home/pvaneynd/common-lisp/systems/")
;; then you can do:
;; * (require :db-sockets)
;; * (pushnew :db-sockets *features*)
;; * (require :clocc-port)
;; * (mk:oos :clx :compile)
;; * (mk:oos :clx :load)
;;;; clx.lisp -- 2003-05-13 21:58:49 -- pascal ;;;;
| 3,397 | Common Lisp | .lisp | 87 | 35.068966 | 77 | 0.653155 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | a66924816955e08bfede8714cdbe5609298041170fada014464f838d1dae42f6 | 4,920 | [
-1
] |
4,921 | garnet.lisp | informatimago_lisp/cl-loaders/garnet.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: garnet.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Loader for garnet.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-03-29 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load "PACKAGES:NET;SOURCEFORGE;GARNET;GARNET-LOADER")
| 1,472 | Common Lisp | .lisp | 36 | 39.777778 | 83 | 0.590656 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | eacb1a513be95ec6c807dfa81ffd26bf5c167285b7566b0342e25d6603a66740 | 4,921 | [
-1
] |
4,922 | html-parser.lisp | informatimago_lisp/cl-loaders/html-parser.lisp | ;;;; -*- coding:utf-8 -*-
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(let ((path
"/local/share/lisp/packages/edu/mit/ai/cl-http-70-23/html-parser/v10/"))
(setf (logical-pathname-translations "HTML-PARSER")
`(("**;*.*.*" path)))
(mapc (lambda (f) (load (compile-file (concatenate 'string path f ".lisp"))))
'(
"packages"
"tokenizer"
"plist"
"defs"
"patmatch"
"rewrite-engine"
"rewrite-rules"
"html-tags"
"html-reader"
"html-parser"
"html-utilities"))
)
;;;; html-parser.lisp -- 2003-09-15 04:54:44 -- pascal ;;;;
| 728 | Common Lisp | .lisp | 22 | 25.545455 | 79 | 0.529161 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | be82ab3b7e54ad65ce79d59e527c6bd5967f6d731a69e6a8e3db0f09cace449d | 4,922 | [
-1
] |
4,923 | cl-pdf.lisp | informatimago_lisp/cl-loaders/cl-pdf.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cl-pdf.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Loads com.fractalconcept.cl-pdf
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2004-10-05 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2004 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load "LOADERS:ASDF")
(pushnew "PACKAGES:COM;FRACTALCONCEPT;CL-PDF;" asdf:*central-registry*)
(asdf:operate 'asdf:load-op :cl-pdf)
;;;; cl-pdf.lisp -- -- ;;;;
| 1,639 | Common Lisp | .lisp | 39 | 40.923077 | 83 | 0.57572 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | 29aabdd7cc008160de04d7999fa9a6843b97eb992f5b066918ebe2f1b45266f9 | 4,923 | [
-1
] |
4,924 | cclan.lisp | informatimago_lisp/cl-loaders/cclan.lisp | ;;;; -*- coding:utf-8 -*-
;;;;****************************************************************************
;;;;FILE: cclan.lisp
;;;;LANGUAGE: Common-Lisp
;;;;SYSTEM: Common-Lisp
;;;;USER-INTERFACE: NONE
;;;;DESCRIPTION
;;;;
;;;; Loads CCLAN.
;;;;
;;;;AUTHORS
;;;; <PJB> Pascal J. Bourguignon <[email protected]>
;;;;MODIFICATIONS
;;;; 2003-06-05 <PJB> Created.
;;;;BUGS
;;;;LEGAL
;;;; AGPL3
;;;;
;;;; Copyright Pascal J. Bourguignon 2003 - 2016
;;;;
;;;; This program is free software: you can redistribute it and/or modify
;;;; it under the terms of the GNU Affero 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 Affero General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU Affero General Public License
;;;; along with this program. If not, see <http://www.gnu.org/licenses/>
;;;;****************************************************************************
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load "CCLAN:ASDF;ASDF.LISP")
(load "CCLAN:CCLAN-GET;PACKAGE.LISP")
(load "CCLAN:CCLAN-GET;CCLAN-GET.ASD")
(asdf:operate 'asdf:load-op :cclan-get)
(setf cclan-get::*cclan-tarball-directory* "SHARE-LISP:CCLAN;TARBALL;"
cclan-get::*cclan-source-directory* "SHARE-LISP:CCLAN;SOURCE;"
cclan-get::*cclan-asdf-registry* "SHARE-LISP:CCLAN;REGISTRY;")
(push cclan-get::*cclan-asdf-registry* asdf:*central-registry*)
(format t "Push on ASDF:*CENTRAL-REGISTRY* directories where .asd files are ~
to be found.~%")
;;;; cclan.lisp -- -- ;;;;
| 2,022 | Common Lisp | .lisp | 46 | 42.326087 | 83 | 0.596553 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | bf1987d3aeab12deb20dda6a2b69254921cdb8e5dcd05df82e397c32eca10af0 | 4,924 | [
-1
] |
4,925 | aima.lisp | informatimago_lisp/cl-loaders/aima.lisp | ;;;; -*- coding:utf-8 -*-
;; ----------------------------------------------------------------------
;; -- CMU-AI -- AIMA: Artificial Inteligence - A Modern Approach --
;; ----------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(setf *readtable* (copy-readtable nil)))
(load "cmu-ai:bookcode;aima;aima")
(aima-load 'all)
(defun compile-aima ()
(aima-compile)
(test 'all))
;;;; aima.lisp -- 2003-05-02 08:02:18 -- pascal ;;;;
| 523 | Common Lisp | .lisp | 12 | 41.75 | 77 | 0.441815 | informatimago/lisp | 20 | 6 | 0 | AGPL-3.0 | 9/19/2024, 11:26:28 AM (Europe/Amsterdam) | d1a75902ab89b4adeba7c3a4824cfd156088fdf765787d0079c40b51082e1b8d | 4,925 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.