id
int64 0
45.1k
| file_name
stringlengths 4
68
| file_path
stringlengths 14
193
| content
stringlengths 32
9.62M
| size
int64 32
9.62M
| language
stringclasses 1
value | extension
stringclasses 6
values | total_lines
int64 1
136k
| avg_line_length
float64 3
903k
| max_line_length
int64 3
4.51M
| alphanum_fraction
float64 0
1
| repo_name
stringclasses 779
values | repo_stars
int64 0
882
| repo_forks
int64 0
108
| repo_open_issues
int64 0
90
| repo_license
stringclasses 8
values | repo_extraction_date
stringclasses 146
values | sha
stringlengths 64
64
| __index_level_0__
int64 0
45.1k
| exdup_ids_cmlisp_stkv2
sequencelengths 1
47
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,445 | parser.lisp | hoytech_antiweb/bundled/cl-ppcre/parser.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/parser.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; The parser will - with the help of the lexer - parse a regex
;;; string and convert it into a "parse tree" (see docs for details
;;; about the syntax of these trees). Note that the lexer might return
;;; illegal parse trees. It is assumed that the conversion process
;;; later on will track them down.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defun group (lexer)
(declare #.*standard-optimize-settings*)
"Parses and consumes a <group>.
The productions are: <group> -> \"\(\"<regex>\")\"
\"\(?:\"<regex>\")\"
\"\(?>\"<regex>\")\"
\"\(?<flags>:\"<regex>\")\"
\"\(?=\"<regex>\")\"
\"\(?!\"<regex>\")\"
\"\(?<=\"<regex>\")\"
\"\(?<!\"<regex>\")\"
\"\(?\(\"<num>\")\"<regex>\")\"
\"\(?\(\"<regex>\")\"<regex>\")\"
\"\(?<name>\"<regex>\")\" \(when *ALLOW-NAMED-REGISTERS* is T)
<legal-token>
where <flags> is parsed by the lexer function MAYBE-PARSE-FLAGS.
Will return <parse-tree> or \(<grouping-type> <parse-tree>) where
<grouping-type> is one of six keywords - see source for details."
(multiple-value-bind (open-token flags)
(get-token lexer)
(cond ((eq open-token :open-paren-paren)
;; special case for conditional regular expressions; note
;; that at this point we accept a couple of illegal
;; combinations which'll be sorted out later by the
;; converter
(let* ((open-paren-pos (car (lexer-last-pos lexer)))
;; check if what follows "(?(" is a number
(number (try-number lexer :no-whitespace-p t))
;; make changes to extended-mode-p local
(*extended-mode-p* *extended-mode-p*))
(declare (type fixnum open-paren-pos))
(cond (number
;; condition is a number (i.e. refers to a
;; back-reference)
(let* ((inner-close-token (get-token lexer))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(unless (eq inner-close-token :close-paren)
(signal-ppcre-syntax-error*
(+ open-paren-pos 2)
"Opening paren has no matching closing paren"))
(unless (eq close-token :close-paren)
(signal-ppcre-syntax-error*
open-paren-pos
"Opening paren has no matching closing paren"))
(list :branch number reg-expr)))
(t
;; condition must be a full regex (actually a
;; look-behind or look-ahead); and here comes a
;; terrible kludge: instead of being cleanly
;; separated from the lexer, the parser pushes
;; back the lexer by one position, thereby
;; landing in the middle of the 'token' "(?(" -
;; yuck!!
(decf (lexer-pos lexer))
(let* ((inner-reg-expr (group lexer))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(unless (eq close-token :close-paren)
(signal-ppcre-syntax-error*
open-paren-pos
"Opening paren has no matching closing paren"))
(list :branch inner-reg-expr reg-expr))))))
((member open-token '(:open-paren
:open-paren-colon
:open-paren-greater
:open-paren-equal
:open-paren-exclamation
:open-paren-less-equal
:open-paren-less-exclamation
:open-paren-less-letter)
:test #'eq)
;; make changes to extended-mode-p local
(let ((*extended-mode-p* *extended-mode-p*))
;; we saw one of the six token representing opening
;; parentheses
(let* ((open-paren-pos (car (lexer-last-pos lexer)))
(register-name (when (eq open-token :open-paren-less-letter)
(parse-register-name-aux lexer)))
(reg-expr (reg-expr lexer))
(close-token (get-token lexer)))
(when (or (eq open-token :open-paren)
(eq open-token :open-paren-less-letter))
;; if this is the "("<regex>")" or "(?"<name>""<regex>")" production we have to
;; increment the register counter of the lexer
(incf (lexer-reg lexer)))
(unless (eq close-token :close-paren)
;; the token following <regex> must be the closing
;; parenthesis or this is a syntax error
(signal-ppcre-syntax-error*
open-paren-pos
"Opening paren has no matching closing paren"))
(if flags
;; if the lexer has returned a list of flags this must
;; have been the "(?:"<regex>")" production
(cons :group (nconc flags (list reg-expr)))
(if (eq open-token :open-paren-less-letter)
(list :named-register
;; every string was reversed, so we have to
;; reverse it back to get the name
(nreverse register-name)
reg-expr)
(list (case open-token
((:open-paren)
:register)
((:open-paren-colon)
:group)
((:open-paren-greater)
:standalone)
((:open-paren-equal)
:positive-lookahead)
((:open-paren-exclamation)
:negative-lookahead)
((:open-paren-less-equal)
:positive-lookbehind)
((:open-paren-less-exclamation)
:negative-lookbehind))
reg-expr))))))
(t
;; this is the <legal-token> production; <legal-token> is
;; any token which passes START-OF-SUBEXPR-P (otherwise
;; parsing had already stopped in the SEQ method)
open-token))))
(defun greedy-quant (lexer)
(declare #.*standard-optimize-settings*)
"Parses and consumes a <greedy-quant>.
The productions are: <greedy-quant> -> <group> | <group><quantifier>
where <quantifier> is parsed by the lexer function GET-QUANTIFIER.
Will return <parse-tree> or (:GREEDY-REPETITION <min> <max> <parse-tree>)."
(let* ((group (group lexer))
(token (get-quantifier lexer)))
(if token
;; if GET-QUANTIFIER returned a non-NIL value it's the
;; two-element list (<min> <max>)
(list :greedy-repetition (first token) (second token) group)
group)))
(defun quant (lexer)
(declare #.*standard-optimize-settings*)
"Parses and consumes a <quant>.
The productions are: <quant> -> <greedy-quant> | <greedy-quant>\"?\".
Will return the <parse-tree> returned by GREEDY-QUANT and optionally
change :GREEDY-REPETITION to :NON-GREEDY-REPETITION."
(let* ((greedy-quant (greedy-quant lexer))
(pos (lexer-pos lexer))
(next-char (next-char lexer)))
(when next-char
(if (char= next-char #\?)
(setf (car greedy-quant) :non-greedy-repetition)
(setf (lexer-pos lexer) pos)))
greedy-quant))
(defun seq (lexer)
(declare #.*standard-optimize-settings*)
"Parses and consumes a <seq>.
The productions are: <seq> -> <quant> | <quant><seq>.
Will return <parse-tree> or (:SEQUENCE <parse-tree> <parse-tree>)."
(flet ((make-array-from-two-chars (char1 char2)
(let ((string (make-array 2
:element-type 'character
:fill-pointer t
:adjustable t)))
(setf (aref string 0) char1)
(setf (aref string 1) char2)
string)))
;; Note that we're calling START-OF-SUBEXPR-P before we actually try
;; to parse a <seq> or <quant> in order to catch empty regular
;; expressions
(if (start-of-subexpr-p lexer)
(let ((quant (quant lexer)))
(if (start-of-subexpr-p lexer)
(let* ((seq (seq lexer))
(quant-is-char-p (characterp quant))
(seq-is-sequence-p (and (consp seq)
(eq (first seq) :sequence))))
(cond ((and quant-is-char-p
(characterp seq))
(make-array-from-two-chars seq quant))
((and quant-is-char-p
(stringp seq))
(vector-push-extend quant seq)
seq)
((and quant-is-char-p
seq-is-sequence-p
(characterp (second seq)))
(cond ((cddr seq)
(setf (cdr seq)
(cons
(make-array-from-two-chars (second seq)
quant)
(cddr seq)))
seq)
(t (make-array-from-two-chars (second seq) quant))))
((and quant-is-char-p
seq-is-sequence-p
(stringp (second seq)))
(cond ((cddr seq)
(setf (cdr seq)
(cons
(progn
(vector-push-extend quant (second seq))
(second seq))
(cddr seq)))
seq)
(t
(vector-push-extend quant (second seq))
(second seq))))
(seq-is-sequence-p
;; if <seq> is also a :SEQUENCE parse tree we merge
;; both lists into one to avoid unnecessary consing
(setf (cdr seq)
(cons quant (cdr seq)))
seq)
(t (list :sequence quant seq))))
quant))
:void)))
(defun reg-expr (lexer)
(declare #.*standard-optimize-settings*)
"Parses and consumes a <regex>, a complete regular expression.
The productions are: <regex> -> <seq> | <seq>\"|\"<regex>.
Will return <parse-tree> or (:ALTERNATION <parse-tree> <parse-tree>)."
(let ((pos (lexer-pos lexer)))
(case (next-char lexer)
((nil)
;; if we didn't get any token we return :VOID which stands for
;; "empty regular expression"
:void)
((#\|)
;; now check whether the expression started with a vertical
;; bar, i.e. <seq> - the left alternation - is empty
(list :alternation :void (reg-expr lexer)))
(otherwise
;; otherwise un-read the character we just saw and parse a
;; <seq> plus the character following it
(setf (lexer-pos lexer) pos)
(let* ((seq (seq lexer))
(pos (lexer-pos lexer)))
(case (next-char lexer)
((nil)
;; no further character, just a <seq>
seq)
((#\|)
;; if the character was a vertical bar, this is an
;; alternation and we have the second production
(let ((reg-expr (reg-expr lexer)))
(cond ((and (consp reg-expr)
(eq (first reg-expr) :alternation))
;; again we try to merge as above in SEQ
(setf (cdr reg-expr)
(cons seq (cdr reg-expr)))
reg-expr)
(t (list :alternation seq reg-expr)))))
(otherwise
;; a character which is not a vertical bar - this is
;; either a syntax error or we're inside of a group and
;; the next character is a closing parenthesis; so we
;; just un-read the character and let another function
;; take care of it
(setf (lexer-pos lexer) pos)
seq)))))))
(defun reverse-strings (parse-tree)
(declare #.*standard-optimize-settings*)
(cond ((stringp parse-tree)
(nreverse parse-tree))
((consp parse-tree)
(loop for parse-tree-rest on parse-tree
while parse-tree-rest
do (setf (car parse-tree-rest)
(reverse-strings (car parse-tree-rest))))
parse-tree)
(t parse-tree)))
(defun parse-string (string)
(declare #.*standard-optimize-settings*)
"Translate the regex string STRING into a parse tree."
(let* ((lexer (make-lexer string))
(parse-tree (reverse-strings (reg-expr lexer))))
;; check whether we've consumed the whole regex string
(if (end-of-string-p lexer)
parse-tree
(signal-ppcre-syntax-error*
(lexer-pos lexer)
"Expected end of string"))))
| 15,605 | Common Lisp | .lisp | 309 | 34.02589 | 100 | 0.499673 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | fc9843fed13740696af0fe1b34ff491635f20f4a17756cdf99fb44e570b63f7b | 2,445 | [
-1
] |
2,446 | load.lisp | hoytech_antiweb/bundled/cl-ppcre/load.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/load.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
(let ((cl-ppcre-base-directory
(make-pathname :name nil :type nil :version nil
:defaults (parse-namestring *load-truename*)))
must-compile)
(with-compilation-unit ()
(dolist (file '("packages"
"specials"
"util"
"errors"
#-:use-acl-regexp2-engine "lexer"
#-:use-acl-regexp2-engine "parser"
#-:use-acl-regexp2-engine "regex-class"
#-:use-acl-regexp2-engine "convert"
#-:use-acl-regexp2-engine "optimize"
#-:use-acl-regexp2-engine "closures"
#-:use-acl-regexp2-engine "repetition-closures"
#-:use-acl-regexp2-engine "scanner"
"api"
"ppcre-tests"))
(let ((pathname (make-pathname :name file :type "lisp" :version nil
:defaults cl-ppcre-base-directory)))
;; don't use COMPILE-FILE in Corman Lisp, it's broken - LOAD
;; will yield compiled functions anyway
#-:cormanlisp
(let ((compiled-pathname (compile-file-pathname pathname)))
(unless (and (not must-compile)
(probe-file compiled-pathname)
(< (file-write-date pathname)
(file-write-date compiled-pathname)))
(setq must-compile t)
(compile-file pathname))
(setq pathname compiled-pathname))
(load pathname)))))
| 3,112 | Common Lisp | .lisp | 57 | 44.614035 | 98 | 0.628571 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a32c71f640e1d60dcf84c4a058e41608ab1cec29ce68beb89aee290ecd748fc5 | 2,446 | [
-1
] |
2,447 | closures.lisp | hoytech_antiweb/bundled/cl-ppcre/closures.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/closures.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Here we create the closures which together build the final
;;; scanner.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(declaim (inline *string*= *string*-equal))
(defun *string*= (string2 start1 end1 start2 end2)
"Like STRING=, i.e. compares the special string *STRING* from START1
to END1 with STRING2 from START2 to END2. Note that there's no
boundary check - this has to be implemented by the caller."
(declare #.*standard-optimize-settings*)
(declare (type fixnum start1 end1 start2 end2))
(loop for string1-idx of-type fixnum from start1 below end1
for string2-idx of-type fixnum from start2 below end2
always (char= (schar *string* string1-idx)
(schar string2 string2-idx))))
(defun *string*-equal (string2 start1 end1 start2 end2)
"Like STRING-EQUAL, i.e. compares the special string *STRING* from
START1 to END1 with STRING2 from START2 to END2. Note that there's no
boundary check - this has to be implemented by the caller."
(declare #.*standard-optimize-settings*)
(declare (type fixnum start1 end1 start2 end2))
(loop for string1-idx of-type fixnum from start1 below end1
for string2-idx of-type fixnum from start2 below end2
always (char-equal (schar *string* string1-idx)
(schar string2 string2-idx))))
(defgeneric create-matcher-aux (regex next-fn)
(declare #.*standard-optimize-settings*)
(:documentation "Creates a closure which takes one parameter,
START-POS, and tests whether REGEX can match *STRING* at START-POS
such that the call to NEXT-FN after the match would succeed."))
(defmethod create-matcher-aux ((seq seq) next-fn)
(declare #.*standard-optimize-settings*)
;; the closure for a SEQ is a chain of closures for the elements of
;; this sequence which call each other in turn; the last closure
;; calls NEXT-FN
(loop for element in (reverse (elements seq))
for curr-matcher = next-fn then next-matcher
for next-matcher = (create-matcher-aux element curr-matcher)
finally (return next-matcher)))
(defmethod create-matcher-aux ((alternation alternation) next-fn)
(declare #.*standard-optimize-settings*)
;; first create closures for all alternations of ALTERNATION
(let ((all-matchers (mapcar #'(lambda (choice)
(create-matcher-aux choice next-fn))
(choices alternation))))
;; now create a closure which checks if one of the closures
;; created above can succeed
(lambda (start-pos)
(declare (type fixnum start-pos))
(loop for matcher in all-matchers
thereis (funcall (the function matcher) start-pos)))))
(defmethod create-matcher-aux ((register register) next-fn)
(declare #.*standard-optimize-settings*)
;; the position of this REGISTER within the whole regex; we start to
;; count at 0
(let ((num (num register)))
(declare (type fixnum num))
;; STORE-END-OF-REG is a thin wrapper around NEXT-FN which will
;; update the corresponding values of *REGS-START* and *REGS-END*
;; after the inner matcher has succeeded
(flet ((store-end-of-reg (start-pos)
(declare (type fixnum start-pos)
(type function next-fn))
(setf (svref *reg-starts* num) (svref *regs-maybe-start* num)
(svref *reg-ends* num) start-pos)
(funcall next-fn start-pos)))
;; the inner matcher is a closure corresponding to the regex
;; wrapped by this REGISTER
(let ((inner-matcher (create-matcher-aux (regex register)
#'store-end-of-reg)))
(declare (type function inner-matcher))
;; here comes the actual closure for REGISTER
(lambda (start-pos)
(declare (type fixnum start-pos))
;; remember the old values of *REGS-START* and friends in
;; case we cannot match
(let ((old-*reg-starts* (svref *reg-starts* num))
(old-*regs-maybe-start* (svref *regs-maybe-start* num))
(old-*reg-ends* (svref *reg-ends* num)))
;; we cannot use *REGS-START* here because Perl allows
;; regular expressions like /(a|\1x)*/
(setf (svref *regs-maybe-start* num) start-pos)
(let ((next-pos (funcall inner-matcher start-pos)))
(unless next-pos
;; restore old values on failure
(setf (svref *reg-starts* num) old-*reg-starts*
(svref *regs-maybe-start* num) old-*regs-maybe-start*
(svref *reg-ends* num) old-*reg-ends*))
next-pos)))))))
(defmethod create-matcher-aux ((lookahead lookahead) next-fn)
(declare #.*standard-optimize-settings*)
;; create a closure which just checks for the inner regex and
;; doesn't care about NEXT-FN
(let ((test-matcher (create-matcher-aux (regex lookahead) #'identity)))
(declare (type function next-fn test-matcher))
(if (positivep lookahead)
;; positive look-ahead: check success of inner regex, then call
;; NEXT-FN
(lambda (start-pos)
(and (funcall test-matcher start-pos)
(funcall next-fn start-pos)))
;; negative look-ahead: check failure of inner regex, then call
;; NEXT-FN
(lambda (start-pos)
(and (not (funcall test-matcher start-pos))
(funcall next-fn start-pos))))))
(defmethod create-matcher-aux ((lookbehind lookbehind) next-fn)
(declare #.*standard-optimize-settings*)
(let ((len (len lookbehind))
;; create a closure which just checks for the inner regex and
;; doesn't care about NEXT-FN
(test-matcher (create-matcher-aux (regex lookbehind) #'identity)))
(declare (type function next-fn test-matcher)
(type fixnum len))
(if (positivep lookbehind)
;; positive look-behind: check success of inner regex (if we're
;; far enough from the start of *STRING*), then call NEXT-FN
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (>= (- start-pos (or *real-start-pos* *start-pos*)) len)
(funcall test-matcher (- start-pos len))
(funcall next-fn start-pos)))
;; negative look-behind: check failure of inner regex (if we're
;; far enough from the start of *STRING*), then call NEXT-FN
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (or (< (- start-pos (or *real-start-pos* *start-pos*)) len)
(not (funcall test-matcher (- start-pos len))))
(funcall next-fn start-pos))))))
(defmacro insert-char-class-tester ((char-class chr-expr) &body body)
"Utility macro to replace each occurence of '(CHAR-CLASS-TEST)
within BODY with the correct test (corresponding to CHAR-CLASS)
against CHR-EXPR."
(with-unique-names (%char-class)
;; the actual substitution is done here: replace
;; '(CHAR-CLASS-TEST) with NEW
(flet ((substitute-char-class-tester (new)
(subst new '(char-class-test) body
:test #'equalp)))
`(let* ((,%char-class ,char-class)
(hash (hash ,%char-class))
(count (if hash
(hash-table-count hash)
most-positive-fixnum))
;; collect a list of "all" characters in the hash if
;; there aren't more than two
(key-list (if (<= count 2)
(loop for chr being the hash-keys of hash
collect chr)
nil))
downcasedp)
(declare (type fixnum count))
;; check if we can partition the hash into three ranges (or
;; less)
(multiple-value-bind (min1 max1 min2 max2 min3 max3)
(create-ranges-from-hash hash)
;; if that didn't work and CHAR-CLASS is case-insensitive we
;; try it again with every character downcased
(when (and (not min1)
(case-insensitive-p ,%char-class))
(multiple-value-setq (min1 max1 min2 max2 min3 max3)
(create-ranges-from-hash hash :downcasep t))
(setq downcasedp t))
(cond ((= count 1)
;; hash contains exactly one character so we just
;; check for this single character; (note that this
;; actually can't happen because this case is
;; optimized away in CONVERT already...)
(let ((chr1 (first key-list)))
,@(substitute-char-class-tester
`(char= ,chr-expr chr1))))
((= count 2)
;; hash contains exactly two characters
(let ((chr1 (first key-list))
(chr2 (second key-list)))
,@(substitute-char-class-tester
`(let ((chr ,chr-expr))
(or (char= chr chr1)
(char= chr chr2))))))
((word-char-class-p ,%char-class)
;; special-case: hash is \w, \W, [\w], [\W] or
;; something equivalent
,@(substitute-char-class-tester
`(word-char-p ,chr-expr)))
((= count *regex-char-code-limit*)
;; according to the ANSI standard we might have all
;; possible characters in the hash even if it
;; doesn't contain CHAR-CODE-LIMIT characters but
;; this doesn't seem to be the case for current
;; implementations (also note that this optimization
;; implies that you must not have characters with
;; character codes beyond *REGEX-CHAR-CODE-LIMIT* in
;; your regexes if you've changed this limit); we
;; expect the compiler to optimize this T "test"
;; away
,@(substitute-char-class-tester t))
((and downcasedp min1 min2 min3)
;; three different ranges, downcased
,@(substitute-char-class-tester
`(let ((chr ,chr-expr))
(or (char-not-greaterp min1 chr max1)
(char-not-greaterp min2 chr max2)
(char-not-greaterp min3 chr max3)))))
((and downcasedp min1 min2)
;; two ranges, downcased
,@(substitute-char-class-tester
`(let ((chr ,chr-expr))
(or (char-not-greaterp min1 chr max1)
(char-not-greaterp min2 chr max2)))))
((and downcasedp min1)
;; one downcased range
,@(substitute-char-class-tester
`(char-not-greaterp min1 ,chr-expr max1)))
((and min1 min2 min3)
;; three ranges
,@(substitute-char-class-tester
`(let ((chr ,chr-expr))
(or (char<= min1 chr max1)
(char<= min2 chr max2)
(char<= min3 chr max3)))))
((and min1 min2)
;; two ranges
,@(substitute-char-class-tester
`(let ((chr ,chr-expr))
(or (char<= min1 chr max1)
(char<= min2 chr max2)))))
(min1
;; one range
,@(substitute-char-class-tester
`(char<= min1 ,chr-expr max1)))
(t
;; the general case; note that most of the above
;; "optimizations" are based on experiences and
;; benchmarks with CMUCL - if you're really
;; concerned with speed you might find out that the
;; general case is almost always the best one for
;; other implementations (because the speed of their
;; hash-table access in relation to other operations
;; might be better than in CMUCL)
,@(substitute-char-class-tester
`(gethash ,chr-expr hash)))))))))
(defmethod create-matcher-aux ((char-class char-class) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type function next-fn))
;; insert a test against the current character within *STRING*
(insert-char-class-tester (char-class (schar *string* start-pos))
(if (invertedp char-class)
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(not (char-class-test))
(funcall next-fn (1+ start-pos))))
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(char-class-test)
(funcall next-fn (1+ start-pos)))))))
(defmethod create-matcher-aux ((str str) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type fixnum *end-string-pos*)
(type function next-fn)
;; this special value is set by CREATE-SCANNER when the
;; closures are built
(special end-string))
(let* ((len (len str))
(case-insensitive-p (case-insensitive-p str))
(start-of-end-string-p (start-of-end-string-p str))
(skip (skip str))
(str (str str))
(chr (schar str 0))
(end-string (and end-string (str end-string)))
(end-string-len (if end-string
(length end-string)
nil)))
(declare (type fixnum len))
(cond ((and start-of-end-string-p case-insensitive-p)
;; closure for the first STR which belongs to the constant
;; string at the end of the regular expression;
;; case-insensitive version
(lambda (start-pos)
(declare (type fixnum start-pos end-string-len))
(let ((test-end-pos (+ start-pos end-string-len)))
(declare (type fixnum test-end-pos))
;; either we're at *END-STRING-POS* (which means that
;; it has already been confirmed that end-string
;; starts here) or we really have to test
(and (or (= start-pos *end-string-pos*)
(and (<= test-end-pos *end-pos*)
(*string*-equal end-string start-pos test-end-pos
0 end-string-len)))
(funcall next-fn (+ start-pos len))))))
(start-of-end-string-p
;; closure for the first STR which belongs to the constant
;; string at the end of the regular expression;
;; case-sensitive version
(lambda (start-pos)
(declare (type fixnum start-pos end-string-len))
(let ((test-end-pos (+ start-pos end-string-len)))
(declare (type fixnum test-end-pos))
;; either we're at *END-STRING-POS* (which means that
;; it has already been confirmed that end-string
;; starts here) or we really have to test
(and (or (= start-pos *end-string-pos*)
(and (<= test-end-pos *end-pos*)
(*string*= end-string start-pos test-end-pos
0 end-string-len)))
(funcall next-fn (+ start-pos len))))))
(skip
;; a STR which can be skipped because some other function
;; has already confirmed that it matches
(lambda (start-pos)
(declare (type fixnum start-pos))
(funcall next-fn (+ start-pos len))))
((and (= len 1) case-insensitive-p)
;; STR represent exactly one character; case-insensitive
;; version
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(char-equal (schar *string* start-pos) chr)
(funcall next-fn (1+ start-pos)))))
((= len 1)
;; STR represent exactly one character; case-sensitive
;; version
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(char= (schar *string* start-pos) chr)
(funcall next-fn (1+ start-pos)))))
(case-insensitive-p
;; general case, case-insensitive version
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((next-pos (+ start-pos len)))
(declare (type fixnum next-pos))
(and (<= next-pos *end-pos*)
(*string*-equal str start-pos next-pos 0 len)
(funcall next-fn next-pos)))))
(t
;; general case, case-sensitive version
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((next-pos (+ start-pos len)))
(declare (type fixnum next-pos))
(and (<= next-pos *end-pos*)
(*string*= str start-pos next-pos 0 len)
(funcall next-fn next-pos))))))))
(declaim (inline word-boundary-p))
(defun word-boundary-p (start-pos)
"Check whether START-POS is a word-boundary within *STRING*."
(declare #.*standard-optimize-settings*)
(declare (type fixnum start-pos))
(let ((1-start-pos (1- start-pos))
(*start-pos* (or *real-start-pos* *start-pos*)))
;; either the character before START-POS is a word-constituent and
;; the character at START-POS isn't...
(or (and (or (= start-pos *end-pos*)
(and (< start-pos *end-pos*)
(not (word-char-p (schar *string* start-pos)))))
(and (< 1-start-pos *end-pos*)
(<= *start-pos* 1-start-pos)
(word-char-p (schar *string* 1-start-pos))))
;; ...or vice versa
(and (or (= start-pos *start-pos*)
(and (< 1-start-pos *end-pos*)
(<= *start-pos* 1-start-pos)
(not (word-char-p (schar *string* 1-start-pos)))))
(and (< start-pos *end-pos*)
(word-char-p (schar *string* start-pos)))))))
(defmethod create-matcher-aux ((word-boundary word-boundary) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type function next-fn))
(if (negatedp word-boundary)
(lambda (start-pos)
(and (not (word-boundary-p start-pos))
(funcall next-fn start-pos)))
(lambda (start-pos)
(and (word-boundary-p start-pos)
(funcall next-fn start-pos)))))
(defmethod create-matcher-aux ((everything everything) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type function next-fn))
(if (single-line-p everything)
;; closure for single-line-mode: we really match everything, so we
;; just advance the index into *STRING* by one and carry on
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(funcall next-fn (1+ start-pos))))
;; not single-line-mode, so we have to make sure we don't match
;; #\Newline
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (< start-pos *end-pos*)
(char/= (schar *string* start-pos) #\Newline)
(funcall next-fn (1+ start-pos))))))
(defmethod create-matcher-aux ((anchor anchor) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type function next-fn))
(let ((startp (startp anchor))
(multi-line-p (multi-line-p anchor)))
(cond ((no-newline-p anchor)
;; this must be an end-anchor and it must be modeless, so
;; we just have to check whether START-POS equals
;; *END-POS*
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (= start-pos *end-pos*)
(funcall next-fn start-pos))))
((and startp multi-line-p)
;; a start-anchor in multi-line-mode: check if we're at
;; *START-POS* or if the last character was #\Newline
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((*start-pos* (or *real-start-pos* *start-pos*)))
(and (or (= start-pos *start-pos*)
(and (<= start-pos *end-pos*)
(> start-pos *start-pos*)
(char= #\Newline
(schar *string* (1- start-pos)))))
(funcall next-fn start-pos)))))
(startp
;; a start-anchor which is not in multi-line-mode, so just
;; check whether we're at *START-POS*
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (= start-pos (or *real-start-pos* *start-pos*))
(funcall next-fn start-pos))))
(multi-line-p
;; an end-anchor in multi-line-mode: check if we're at
;; *END-POS* or if the character we're looking at is
;; #\Newline
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (or (= start-pos *end-pos*)
(and (< start-pos *end-pos*)
(char= #\Newline
(schar *string* start-pos))))
(funcall next-fn start-pos))))
(t
;; an end-anchor which is not in multi-line-mode, so just
;; check if we're at *END-POS* or if we're looking at
;; #\Newline and there's nothing behind it
(lambda (start-pos)
(declare (type fixnum start-pos))
(and (or (= start-pos *end-pos*)
(and (= start-pos (1- *end-pos*))
(char= #\Newline
(schar *string* start-pos))))
(funcall next-fn start-pos)))))))
(defmethod create-matcher-aux ((back-reference back-reference) next-fn)
(declare #.*standard-optimize-settings*)
(declare (type function next-fn))
;; the position of the corresponding REGISTER within the whole
;; regex; we start to count at 0
(let ((num (num back-reference)))
(if (case-insensitive-p back-reference)
;; the case-insensitive version
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((reg-start (svref *reg-starts* num))
(reg-end (svref *reg-ends* num)))
;; only bother to check if the corresponding REGISTER as
;; matched successfully already
(and reg-start
(let ((next-pos (+ start-pos (- (the fixnum reg-end)
(the fixnum reg-start)))))
(declare (type fixnum next-pos))
(and
(<= next-pos *end-pos*)
(*string*-equal *string* start-pos next-pos
reg-start reg-end)
(funcall next-fn next-pos))))))
;; the case-sensitive version
(lambda (start-pos)
(declare (type fixnum start-pos))
(let ((reg-start (svref *reg-starts* num))
(reg-end (svref *reg-ends* num)))
;; only bother to check if the corresponding REGISTER as
;; matched successfully already
(and reg-start
(let ((next-pos (+ start-pos (- (the fixnum reg-end)
(the fixnum reg-start)))))
(declare (type fixnum next-pos))
(and
(<= next-pos *end-pos*)
(*string*= *string* start-pos next-pos
reg-start reg-end)
(funcall next-fn next-pos)))))))))
(defmethod create-matcher-aux ((branch branch) next-fn)
(declare #.*standard-optimize-settings*)
(let* ((test (test branch))
(then-matcher (create-matcher-aux (then-regex branch) next-fn))
(else-matcher (create-matcher-aux (else-regex branch) next-fn)))
(declare (type function then-matcher else-matcher))
(cond ((numberp test)
(lambda (start-pos)
(declare (type fixnum test))
(if (and (< test (length *reg-starts*))
(svref *reg-starts* test))
(funcall then-matcher start-pos)
(funcall else-matcher start-pos))))
(t
(let ((test-matcher (create-matcher-aux test #'identity)))
(declare (type function test-matcher))
(lambda (start-pos)
(if (funcall test-matcher start-pos)
(funcall then-matcher start-pos)
(funcall else-matcher start-pos))))))))
(defmethod create-matcher-aux ((standalone standalone) next-fn)
(declare #.*standard-optimize-settings*)
(let ((inner-matcher (create-matcher-aux (regex standalone) #'identity)))
(declare (type function next-fn inner-matcher))
(lambda (start-pos)
(let ((next-pos (funcall inner-matcher start-pos)))
(and next-pos
(funcall next-fn next-pos))))))
(defmethod create-matcher-aux ((filter filter) next-fn)
(declare #.*standard-optimize-settings*)
(let ((fn (fn filter)))
(lambda (start-pos)
(let ((next-pos (funcall fn start-pos)))
(and next-pos
(funcall next-fn next-pos))))))
(defmethod create-matcher-aux ((void void) next-fn)
(declare #.*standard-optimize-settings*)
;; optimize away VOIDs: don't create a closure, just return NEXT-FN
next-fn)
| 27,522 | Common Lisp | .lisp | 550 | 37.534545 | 102 | 0.562967 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 107eb3050cd4fb33f5bf329fcee87a3298ab63a7c58a0662b75e45f9dbce4480 | 2,447 | [
-1
] |
2,448 | optimize.lisp | hoytech_antiweb/bundled/cl-ppcre/optimize.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/optimize.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; This file contains optimizations which can be applied to converted
;;; parse trees.
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-ppcre)
(defgeneric flatten (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Merges adjacent sequences and alternations, i.e. it
transforms #<SEQ #<STR \"a\"> #<SEQ #<STR \"b\"> #<STR \"c\">>> to
#<SEQ #<STR \"a\"> #<STR \"b\"> #<STR \"c\">>. This is a destructive
operation on REGEX."))
(defmethod flatten ((seq seq))
(declare #.*standard-optimize-settings*)
;; this looks more complicated than it is because we modify SEQ in
;; place to avoid unnecessary consing
(let ((elements-rest (elements seq)))
(loop
(unless elements-rest
(return))
(let ((flattened-element (flatten (car elements-rest)))
(next-elements-rest (cdr elements-rest)))
(cond ((typep flattened-element 'seq)
;; FLATTENED-ELEMENT is a SEQ object, so we "splice"
;; it into out list of elements
(let ((flattened-element-elements
(elements flattened-element)))
(setf (car elements-rest)
(car flattened-element-elements)
(cdr elements-rest)
(nconc (cdr flattened-element-elements)
(cdr elements-rest)))))
(t
;; otherwise we just replace the current element with
;; its flattened counterpart
(setf (car elements-rest) flattened-element)))
(setq elements-rest next-elements-rest))))
(let ((elements (elements seq)))
(cond ((cadr elements)
seq)
((cdr elements)
(first elements))
(t (make-instance 'void)))))
(defmethod flatten ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; same algorithm as above
(let ((choices-rest (choices alternation)))
(loop
(unless choices-rest
(return))
(let ((flattened-choice (flatten (car choices-rest)))
(next-choices-rest (cdr choices-rest)))
(cond ((typep flattened-choice 'alternation)
(let ((flattened-choice-choices
(choices flattened-choice)))
(setf (car choices-rest)
(car flattened-choice-choices)
(cdr choices-rest)
(nconc (cdr flattened-choice-choices)
(cdr choices-rest)))))
(t
(setf (car choices-rest) flattened-choice)))
(setq choices-rest next-choices-rest))))
(let ((choices (choices alternation)))
(cond ((cadr choices)
alternation)
((cdr choices)
(first choices))
(t (signal-ppcre-syntax-error
"Encountered alternation without choices.")))))
(defmethod flatten ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test then-regex else-regex)
branch
(setq test
(if (numberp test)
test
(flatten test))
then-regex (flatten then-regex)
else-regex (flatten else-regex))
branch))
(defmethod flatten ((regex regex))
(declare #.*standard-optimize-settings*)
(typecase regex
((or repetition register lookahead lookbehind standalone)
;; if REGEX contains exactly one inner REGEX object flatten it
(setf (regex regex)
(flatten (regex regex)))
regex)
(t
;; otherwise (ANCHOR, BACK-REFERENCE, CHAR-CLASS, EVERYTHING,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY)
;; do nothing
regex)))
(defgeneric gather-strings (regex)
(declare #.*standard-optimize-settings*)
(:documentation "Collects adjacent strings or characters into one
string provided they have the same case mode. This is a destructive
operation on REGEX."))
(defmethod gather-strings ((seq seq))
(declare #.*standard-optimize-settings*)
;; note that GATHER-STRINGS is to be applied after FLATTEN, i.e. it
;; expects SEQ to be flattened already; in particular, SEQ cannot be
;; empty and cannot contain embedded SEQ objects
(let* ((start-point (cons nil (elements seq)))
(curr-point start-point)
old-case-mode
collector
collector-start
(collector-length 0)
skip)
(declare (type fixnum collector-length))
(loop
(let ((elements-rest (cdr curr-point)))
(unless elements-rest
(return))
(let* ((element (car elements-rest))
(case-mode (case-mode element old-case-mode)))
(cond ((and case-mode
(eq case-mode old-case-mode))
;; if ELEMENT is a STR and we have collected a STR of
;; the same case mode in the last iteration we
;; concatenate ELEMENT onto COLLECTOR and remember the
;; value of its SKIP slot
(let ((old-collector-length collector-length))
(unless (and (adjustable-array-p collector)
(array-has-fill-pointer-p collector))
(setq collector
(make-array collector-length
:initial-contents collector
:element-type 'character
:fill-pointer t
:adjustable t)
collector-start nil))
(adjust-array collector
(incf collector-length (len element))
:fill-pointer t)
(setf (subseq collector
old-collector-length)
(str element)
;; it suffices to remember the last SKIP slot
;; because due to the way MAYBE-ACCUMULATE
;; works adjacent STR objects have the same
;; SKIP value
skip (skip element)))
(setf (cdr curr-point) (cdr elements-rest)))
(t
(let ((collected-string
(cond (collector-start
collector-start)
(collector
;; if we have collected something already
;; we convert it into a STR
(make-instance 'str
:skip skip
:str collector
:case-insensitive-p
(eq old-case-mode
:case-insensitive)))
(t nil))))
(cond (case-mode
;; if ELEMENT is a string with a different case
;; mode than the last one we have either just
;; converted COLLECTOR into a STR or COLLECTOR
;; is still empty; in both cases we can now
;; begin to fill it anew
(setq collector (str element)
collector-start element
;; and we remember the SKIP value as above
skip (skip element)
collector-length (len element))
(cond (collected-string
(setf (car elements-rest)
collected-string
curr-point
(cdr curr-point)))
(t
(setf (cdr curr-point)
(cdr elements-rest)))))
(t
;; otherwise this is not a STR so we apply
;; GATHER-STRINGS to it and collect it directly
;; into RESULT
(cond (collected-string
(setf (car elements-rest)
collected-string
curr-point
(cdr curr-point)
(cdr curr-point)
(cons (gather-strings element)
(cdr curr-point))
curr-point
(cdr curr-point)))
(t
(setf (car elements-rest)
(gather-strings element)
curr-point
(cdr curr-point))))
;; we also have to empty COLLECTOR here in case
;; it was still filled from the last iteration
(setq collector nil
collector-start nil))))))
(setq old-case-mode case-mode))))
(when collector
(setf (cdr curr-point)
(cons
(make-instance 'str
:skip skip
:str collector
:case-insensitive-p
(eq old-case-mode
:case-insensitive))
nil)))
(setf (elements seq) (cdr start-point))
seq))
(defmethod gather-strings ((alternation alternation))
(declare #.*standard-optimize-settings*)
;; loop ON the choices of ALTERNATION so we can modify them directly
(loop for choices-rest on (choices alternation)
while choices-rest
do (setf (car choices-rest)
(gather-strings (car choices-rest))))
alternation)
(defmethod gather-strings ((branch branch))
(declare #.*standard-optimize-settings*)
(with-slots (test then-regex else-regex)
branch
(setq test
(if (numberp test)
test
(gather-strings test))
then-regex (gather-strings then-regex)
else-regex (gather-strings else-regex))
branch))
(defmethod gather-strings ((regex regex))
(declare #.*standard-optimize-settings*)
(typecase regex
((or repetition register lookahead lookbehind standalone)
;; if REGEX contains exactly one inner REGEX object apply
;; GATHER-STRINGS to it
(setf (regex regex)
(gather-strings (regex regex)))
regex)
(t
;; otherwise (ANCHOR, BACK-REFERENCE, CHAR-CLASS, EVERYTHING,
;; LOOKAHEAD, LOOKBEHIND, STR, VOID, FILTER, and WORD-BOUNDARY)
;; do nothing
regex)))
;; Note that START-ANCHORED-P will be called after FLATTEN and GATHER-STRINGS.
(defgeneric start-anchored-p (regex &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(:documentation "Returns T if REGEX starts with a \"real\" start
anchor, i.e. one that's not in multi-line mode, NIL otherwise. If
IN-SEQ-P is true the function will return :ZERO-LENGTH if REGEX is a
zero-length assertion."))
(defmethod start-anchored-p ((seq seq) &optional in-seq-p)
(declare (ignore in-seq-p))
;; note that START-ANCHORED-P is to be applied after FLATTEN and
;; GATHER-STRINGS, i.e. SEQ cannot be empty and cannot contain
;; embedded SEQ objects
(loop for element in (elements seq)
for anchored-p = (start-anchored-p element t)
;; skip zero-length elements because they won't affect the
;; "anchoredness" of the sequence
while (eq anchored-p :zero-length)
finally (return (and anchored-p (not (eq anchored-p :zero-length))))))
(defmethod start-anchored-p ((alternation alternation) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
;; clearly an alternation can only be start-anchored if all of its
;; choices are start-anchored
(loop for choice in (choices alternation)
always (start-anchored-p choice)))
(defmethod start-anchored-p ((branch branch) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(and (start-anchored-p (then-regex branch))
(start-anchored-p (else-regex branch))))
(defmethod start-anchored-p ((repetition repetition) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
;; well, this wouldn't make much sense, but anyway...
(and (plusp (minimum repetition))
(start-anchored-p (regex repetition))))
(defmethod start-anchored-p ((register register) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(start-anchored-p (regex register)))
(defmethod start-anchored-p ((standalone standalone) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(start-anchored-p (regex standalone)))
(defmethod start-anchored-p ((anchor anchor) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(declare (ignore in-seq-p))
(and (startp anchor)
(not (multi-line-p anchor))))
(defmethod start-anchored-p ((regex regex) &optional in-seq-p)
(declare #.*standard-optimize-settings*)
(typecase regex
((or lookahead lookbehind word-boundary void)
;; zero-length assertions
(if in-seq-p
:zero-length
nil))
(filter
(if (and in-seq-p
(len regex)
(zerop (len regex)))
:zero-length
nil))
(t
;; BACK-REFERENCE, CHAR-CLASS, EVERYTHING, and STR
nil)))
;; Note that END-STRING-AUX will be called after FLATTEN and GATHER-STRINGS.
(defgeneric end-string-aux (regex &optional old-case-insensitive-p)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the constant string (if it exists) REGEX
ends with wrapped into a STR object, otherwise NIL.
OLD-CASE-INSENSITIVE-P is the CASE-INSENSITIVE-P slot of the last STR
collected or :VOID if no STR has been collected yet. (This is a helper
function called by END-STRIN.)"))
(defmethod end-string-aux ((str str)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special last-str))
(cond ((and (not (skip str)) ; avoid constituents of STARTS-WITH
;; only use STR if nothing has been collected yet or if
;; the collected string has the same value for
;; CASE-INSENSITIVE-P
(or (eq old-case-insensitive-p :void)
(eq (case-insensitive-p str) old-case-insensitive-p)))
(setf last-str str
;; set the SKIP property of this STR
(skip str) t)
str)
(t nil)))
(defmethod end-string-aux ((seq seq)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special continuep))
(let (case-insensitive-p
concatenated-string
concatenated-start
(concatenated-length 0))
(declare (type fixnum concatenated-length))
(loop for element in (reverse (elements seq))
;; remember the case-(in)sensitivity of the last relevant
;; STR object
for loop-old-case-insensitive-p = old-case-insensitive-p
then (if skip
loop-old-case-insensitive-p
(case-insensitive-p element-end))
;; the end-string of the current element
for element-end = (end-string-aux element
loop-old-case-insensitive-p)
;; whether we encountered a zero-length element
for skip = (if element-end
(zerop (len element-end))
nil)
;; set CONTINUEP to NIL if we have to stop collecting to
;; alert END-STRING-AUX methods on enclosing SEQ objects
unless element-end
do (setq continuep nil)
;; end loop if we neither got a STR nor a zero-length
;; element
while element-end
;; only collect if not zero-length
unless skip
do (cond (concatenated-string
(when concatenated-start
(setf concatenated-string
(make-array concatenated-length
:initial-contents (reverse (str concatenated-start))
:element-type 'character
:fill-pointer t
:adjustable t)
concatenated-start nil))
(let ((len (len element-end))
(str (str element-end)))
(declare (type fixnum len))
(incf concatenated-length len)
(loop for i of-type fixnum downfrom (1- len) to 0
do (vector-push-extend (char str i)
concatenated-string))))
(t
(setf concatenated-string
t
concatenated-start
element-end
concatenated-length
(len element-end)
case-insensitive-p
(case-insensitive-p element-end))))
;; stop collecting if END-STRING-AUX on inner SEQ has said so
while continuep)
(cond ((zerop concatenated-length)
;; don't bother to return zero-length strings
nil)
(concatenated-start
concatenated-start)
(t
(make-instance 'str
:str (nreverse concatenated-string)
:case-insensitive-p case-insensitive-p)))))
(defmethod end-string-aux ((register register)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(end-string-aux (regex register) old-case-insensitive-p))
(defmethod end-string-aux ((standalone standalone)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(end-string-aux (regex standalone) old-case-insensitive-p))
(defmethod end-string-aux ((regex regex)
&optional (old-case-insensitive-p :void))
(declare #.*standard-optimize-settings*)
(declare (special last-str end-anchored-p continuep))
(typecase regex
((or anchor lookahead lookbehind word-boundary void)
;; a zero-length REGEX object - for the sake of END-STRING-AUX
;; this is a zero-length string
(when (and (typep regex 'anchor)
(not (startp regex))
(or (no-newline-p regex)
(not (multi-line-p regex)))
(eq old-case-insensitive-p :void))
;; if this is a "real" end-anchor and we haven't collected
;; anything so far we can set END-ANCHORED-P (where 1 or 0
;; indicate whether we accept a #\Newline at the end or not)
(setq end-anchored-p (if (no-newline-p regex) 0 1)))
(make-instance 'str
:str ""
:case-insensitive-p :void))
(t
;; (ALTERNATION, BACK-REFERENCE, BRANCH, CHAR-CLASS, EVERYTHING,
;; REPETITION, FILTER)
nil)))
(defun end-string (regex)
(declare (special end-string-offset))
(declare #.*standard-optimize-settings*)
"Returns the constant string (if it exists) REGEX ends with wrapped
into a STR object, otherwise NIL."
;; LAST-STR points to the last STR object (seen from the end) that's
;; part of END-STRING; CONTINUEP is set to T if we stop collecting
;; in the middle of a SEQ
(let ((continuep t)
last-str)
(declare (special continuep last-str))
(prog1
(end-string-aux regex)
(when last-str
;; if we've found something set the START-OF-END-STRING-P of
;; the leftmost STR collected accordingly and remember the
;; OFFSET of this STR (in a special variable provided by the
;; caller of this function)
(setf (start-of-end-string-p last-str) t
end-string-offset (offset last-str))))))
(defgeneric compute-min-rest (regex current-min-rest)
(declare #.*standard-optimize-settings*)
(:documentation "Returns the minimal length of REGEX plus
CURRENT-MIN-REST. This is similar to REGEX-MIN-LENGTH except that it
recurses down into REGEX and sets the MIN-REST slots of REPETITION
objects."))
(defmethod compute-min-rest ((seq seq) current-min-rest)
(declare #.*standard-optimize-settings*)
(loop for element in (reverse (elements seq))
for last-min-rest = current-min-rest then this-min-rest
for this-min-rest = (compute-min-rest element last-min-rest)
finally (return this-min-rest)))
(defmethod compute-min-rest ((alternation alternation) current-min-rest)
(declare #.*standard-optimize-settings*)
(loop for choice in (choices alternation)
minimize (compute-min-rest choice current-min-rest)))
(defmethod compute-min-rest ((branch branch) current-min-rest)
(declare #.*standard-optimize-settings*)
(min (compute-min-rest (then-regex branch) current-min-rest)
(compute-min-rest (else-regex branch) current-min-rest)))
(defmethod compute-min-rest ((str str) current-min-rest)
(declare #.*standard-optimize-settings*)
(+ current-min-rest (len str)))
(defmethod compute-min-rest ((filter filter) current-min-rest)
(declare #.*standard-optimize-settings*)
(+ current-min-rest (or (len filter) 0)))
(defmethod compute-min-rest ((repetition repetition) current-min-rest)
(declare #.*standard-optimize-settings*)
(setf (min-rest repetition) current-min-rest)
(compute-min-rest (regex repetition) current-min-rest)
(+ current-min-rest (* (minimum repetition) (min-len repetition))))
(defmethod compute-min-rest ((register register) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex register) current-min-rest))
(defmethod compute-min-rest ((standalone standalone) current-min-rest)
(declare #.*standard-optimize-settings*)
(declare (ignore current-min-rest))
(compute-min-rest (regex standalone) 0))
(defmethod compute-min-rest ((lookahead lookahead) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex lookahead) 0)
current-min-rest)
(defmethod compute-min-rest ((lookbehind lookbehind) current-min-rest)
(declare #.*standard-optimize-settings*)
(compute-min-rest (regex lookbehind) (+ current-min-rest (len lookbehind)))
current-min-rest)
(defmethod compute-min-rest ((regex regex) current-min-rest)
(declare #.*standard-optimize-settings*)
(typecase regex
((or char-class everything)
(1+ current-min-rest))
(t
;; zero min-len and no embedded regexes (ANCHOR,
;; BACK-REFERENCE, VOID, and WORD-BOUNDARY)
current-min-rest)))
| 25,312 | Common Lisp | .lisp | 532 | 34.554511 | 102 | 0.572013 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 34d1eaa20e0ab8755828d1ac5ca8a7ace49b193612fe0955071488e8c8a360b2 | 2,448 | [
-1
] |
2,449 | lispworks-defsystem.lisp | hoytech_antiweb/bundled/cl-ppcre/lispworks-defsystem.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/lispworks-defsystem.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; This system definition for LispWorks was kindly provided by Wade Humeniuk
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package #:cl-user)
(defparameter *cl-ppcre-base-directory*
(make-pathname :name nil :type nil :version nil
:defaults (parse-namestring *load-truename*)))
(defsystem cl-ppcre
(:default-pathname *cl-ppcre-base-directory*
:default-type :lisp-file)
:members ("packages"
"specials"
"util"
"errors"
"lexer"
"parser"
"regex-class"
"convert"
"optimize"
"closures"
"repetition-closures"
"scanner"
"api")
:rules ((:in-order-to :compile :all
(:requires (:load :previous)))
(:in-order-to :load :all
(:requires (:load :previous))))) | 2,375 | Common Lisp | .lisp | 48 | 43.520833 | 113 | 0.678741 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | cc535b1c0c0040e6210a2f3496de4b99a34b599cb6519a0084bc01bf4e80902e | 2,449 | [
-1
] |
2,450 | packages.lisp | hoytech_antiweb/bundled/cl-ppcre/packages.lisp | ;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*-
;;; $Header: /usr/cvs/hcsw/antiweb/bundled/cl-ppcre/packages.lisp,v 1.1 2008/04/26 02:40:56 doug Exp $
;;; Copyright (c) 2002-2007, Dr. Edmund Weitz. All rights reserved.
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;; * Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;; * Redistributions in binary form must reproduce the above
;;; copyright notice, this list of conditions and the following
;;; disclaimer in the documentation and/or other materials
;;; provided with the distribution.
;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(in-package :cl-user)
#-:cormanlisp
(defpackage #:cl-ppcre
(:nicknames #:ppcre)
#+genera (:shadowing-import-from #:common-lisp #:lambda #:simple-string #:string)
(:use #-genera #:cl #+genera #:future-common-lisp)
(:export #:create-scanner
#:parse-tree-synonym
#:define-parse-tree-synonym
#:scan
#:scan-to-strings
#:do-scans
#:do-matches
#:do-matches-as-strings
#:all-matches
#:all-matches-as-strings
#:split
#:regex-replace
#:regex-replace-all
#:regex-apropos
#:regex-apropos-list
#:quote-meta-chars
#:*regex-char-code-limit*
#:*use-bmh-matchers*
#:*allow-quoting*
#:*allow-named-registers*
#:ppcre-error
#:ppcre-invocation-error
#:ppcre-syntax-error
#:ppcre-syntax-error-string
#:ppcre-syntax-error-pos
#:register-groups-bind
#:do-register-groups))
#+:cormanlisp
(defpackage "CL-PPCRE"
(:nicknames "PPCRE")
(:use "CL")
(:export "CREATE-SCANNER"
"PARSE-TREE-SYNONYM"
"DEFINE-PARSE-TREE-SYNONYM"
"SCAN"
"SCAN-TO-STRINGS"
"DO-SCANS"
"DO-MATCHES"
"DO-MATCHES-AS-STRINGS"
"ALL-MATCHES"
"ALL-MATCHES-AS-STRINGS"
"SPLIT"
"REGEX-REPLACE"
"REGEX-REPLACE-ALL"
"REGEX-APROPOS"
"REGEX-APROPOS-LIST"
"QUOTE-META-CHARS"
"*REGEX-CHAR-CODE-LIMIT*"
"*USE-BMH-MATCHERS*"
"*ALLOW-QUOTING*"
"*ALLOW-NAMED-REGISTERS*"
"PPCRE-ERROR"
"PPCRE-INVOCATION-ERROR"
"PPCRE-SYNTAX-ERROR"
"PPCRE-SYNTAX-ERROR-STRING"
"PPCRE-SYNTAX-ERROR-POS"
"REGISTER-GROUPS-BIND"
"DO-REGISTER-GROUPS"))
#-:cormanlisp
(defpackage #:cl-ppcre-test
#+genera (:shadowing-import-from #:common-lisp #:lambda)
(:use #-genera #:cl #+genera #:future-common-lisp #:cl-ppcre)
(:export #:test))
#+:cormanlisp
(defpackage "CL-PPCRE-TEST"
(:use "CL" "CL-PPCRE")
(:export "TEST"))
| 3,748 | Common Lisp | .lisp | 96 | 31.729167 | 102 | 0.627952 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | f40ecd1be6b7ef4389934d8551153beae5b16a9c50ec07dd830b1cef81985ae5 | 2,450 | [
-1
] |
2,451 | parse.lisp | hoytech_antiweb/bundled/yason/parse.lisp | ;; This file is part of yason, a Common Lisp JSON parser/encoder
;;
;; Copyright (c) 2008 Hans Hübner
;; All rights reserved.
;;
;; Please see the file LICENSE in the distribution.
(in-package :yason)
(defconstant +default-string-length+ 20
"Default length of strings that are created while reading json input.")
(defvar *parse-object-key-fn* #'identity
"Function to call to convert a key string in a JSON array to a key
in the CL hash produced.")
(defvar *parse-json-arrays-as-vectors* nil
"If set to a true value, JSON arrays will be parsed as vectors, not
as lists.")
(defvar *parse-json-booleans-as-symbols* nil
"If set to a true value, JSON booleans will be read as the symbols
TRUE and FALSE, not as T and NIL, respectively.")
(defun make-adjustable-string ()
"Return an adjustable empty string, usable as a buffer for parsing strings and numbers."
(make-array +default-string-length+
:adjustable t :fill-pointer 0 :element-type 'character))
(defun parse-number (input)
;; would be
;; (cl-ppcre:scan-to-strings "^-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+|)(?:[eE][-+]?[0-9]+|)" buffer)
;; but we want to operate on streams
(let ((buffer (make-adjustable-string)))
(loop
while (position (peek-char nil input nil) ".0123456789+-Ee")
do (vector-push-extend (read-char input) buffer))
(values (read-from-string buffer))))
(defun parse-string (input)
(let ((output (make-adjustable-string)))
(labels ((outc (c)
(vector-push-extend c output))
(next ()
(read-char input))
(peek ()
(peek-char nil input)))
(next)
(loop
(cond
((eql (peek) #\")
(next)
(return-from parse-string output))
((eql (peek) #\\)
(next)
(ecase (next)
(#\" (outc #\"))
(#\\ (outc #\\))
(#\/ (outc #\/))
(#\b (outc #\Backspace))
(#\f (outc #\Page))
(#\n (outc #\Newline))
(#\r (outc #\Return))
(#\t (outc #\Tab))
(#\u (outc (code-char (let ((buffer (make-string 4)))
(read-sequence buffer input)
(parse-integer buffer :radix 16)))))))
(t
(outc (next))))))))
(defun whitespace-p (char)
(member char '(#\Space #\Newline #\Tab #\Linefeed)))
(defun skip-whitespace (input)
(loop
while (and (listen input)
(whitespace-p (peek-char nil input)))
do (read-char input)))
(defun peek-char-skipping-whitespace (input &optional (eof-error-p t))
(skip-whitespace input)
(peek-char nil input eof-error-p))
(defun parse-constant (input)
(destructuring-bind (expected-string return-value)
(find (peek-char nil input nil)
`(("true" ,(if *parse-json-booleans-as-symbols* 'true t))
("false" ,(if *parse-json-booleans-as-symbols* 'false nil))
("null" nil))
:key (lambda (entry) (aref (car entry) 0))
:test #'eql)
(loop
for char across expected-string
unless (eql (read-char input nil) char)
do (error "invalid constant"))
return-value))
(define-condition cannot-convert-key (error)
((key-string :initarg :key-string
:reader key-string))
(:report (lambda (c stream)
(format stream "cannot convert key ~S used in JSON object to hash table key"
(key-string c)))))
(defun parse-object (input)
(let ((return-value (make-hash-table :test #'equal)))
(read-char input)
(loop
(when (eql (peek-char-skipping-whitespace input)
#\})
(return))
(skip-whitespace input)
(setf (gethash (prog1
(let ((key-string (parse-string input)))
(or (funcall *parse-object-key-fn* key-string)
(error 'cannot-convert-key :key-string key-string)))
(skip-whitespace input)
(unless (eql #\: (read-char input))
(error 'expected-colon))
(skip-whitespace input))
return-value)
(parse input))
(ecase (peek-char-skipping-whitespace input)
(#\, (read-char input))
(#\} nil)))
(read-char input)
return-value))
(defconstant +initial-array-size+ 20
"Initial size of JSON arrays read, they will grow as needed.")
(defun %parse-array (input add-element-function)
"Parse JSON array from input, calling ADD-ELEMENT-FUNCTION for each array element parsed."
(read-char input)
(loop
(when (eql (peek-char-skipping-whitespace input)
#\])
(return))
(funcall add-element-function (parse input))
(ecase (peek-char-skipping-whitespace input)
(#\, (read-char input))
(#\] nil)))
(read-char input))
(defun parse-array (input)
(if *parse-json-arrays-as-vectors*
(let ((return-value (make-array +initial-array-size+ :adjustable t :fill-pointer 0)))
(%parse-array input
(lambda (element)
(vector-push-extend element return-value)))
return-value)
(let (return-value)
(%parse-array input
(lambda (element)
(push element return-value)))
(nreverse return-value))))
(defgeneric parse (input)
(:documentation "Parse INPUT, which needs to be a string or a
stream, as JSON. Returns the lisp representation of the JSON
structure parsed.")
(:method ((input stream))
(ecase (peek-char-skipping-whitespace input)
(#\"
(parse-string input))
((#\- #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9)
(parse-number input))
(#\{
(parse-object input))
(#\[
(parse-array input))
((#\t #\f #\n)
(parse-constant input))))
(:method ((input string))
(parse (make-string-input-stream input))))
| 6,098 | Common Lisp | .lisp | 157 | 29.847134 | 95 | 0.568051 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 10ea5e69a31e85557bfb1ed2eb8f41a70694dd99adea1d3429b85e52491d87b5 | 2,451 | [
-1
] |
2,452 | encode.lisp | hoytech_antiweb/bundled/yason/encode.lisp | ;; This file is part of yason, a Common Lisp JSON parser/encoder
;;
;; Copyright (c) 2008 Hans Hübner
;; All rights reserved.
;;
;; Please see the file LICENSE in the distribution.
(in-package :yason)
(defvar *json-output*)
(defmacro with-standard-output-to ((stream) &body body)
`(let ((*standard-output* ,stream))
,@body))
(defgeneric encode (object &optional stream)
(:documentation "Encode OBJECT to STREAM in JSON format. May be
specialized by applications to perform specific rendering. STREAM
defaults to *STANDARD-OUTPUT*.")
(:method ((object string) &optional (stream *standard-output*))
(with-standard-output-to (stream)
(princ #\")
(loop
for char across object
do (case char
((#\\ #\" #\/)
(princ #\\) (princ char))
(#\Backspace
(princ #\\) (princ #\b))
(#\Page
(princ #\\) (princ #\f))
(#\Newline
(princ #\\) (princ #\n))
(#\Return
(princ #\\) (princ #\r))
(#\Tab
(princ #\\) (princ #\t))
(t
(princ char))))
(princ #\"))
object)
(:method ((object rational) &optional (stream *standard-output*))
(encode (float object) stream)
object)
(:method ((object integer) &optional (stream *standard-output*))
(princ object stream))
(:method ((object hash-table) &optional (stream *standard-output*))
(with-standard-output-to (stream)
(princ #\{)
(let (printed)
(maphash (lambda (key value)
(if printed
(princ #\,)
(setf printed t))
(encode key stream)
(princ #\:)
(encode value stream))
object))
(princ #\}))
object)
(:method ((object vector) &optional (stream *standard-output*))
(with-standard-output-to (stream)
(princ #\[)
(let (printed)
(loop
for value across object
do
(when printed
(princ #\,))
(setf printed t)
(encode value stream)))
(princ #\]))
object)
(:method ((object list) &optional (stream *standard-output*))
(with-standard-output-to (stream)
(princ #\[)
(let (printed)
(dolist (value object)
(if printed
(princ #\,)
(setf printed t))
(encode value stream)))
(princ #\]))
object)
(:method ((object (eql 'true)) &optional (stream *standard-output*))
(princ "true" stream)
object)
(:method ((object (eql 'false)) &optional (stream *standard-output*))
(princ "false" stream)
object)
(:method ((object (eql 'null)) &optional (stream *standard-output*))
(princ "null" stream)
object)
(:method ((object (eql t)) &optional (stream *standard-output*))
(princ "true" stream)
object)
(:method ((object (eql nil)) &optional (stream *standard-output*))
(princ "null" stream)
object))
(defclass json-output-stream ()
((output-stream :reader output-stream
:initarg :output-stream)
(stack :accessor stack
:initform nil))
(:documentation "Objects of this class capture the state of a JSON stream encoder."))
(defun next-aggregate-element ()
(if (car (stack *json-output*))
(princ (car (stack *json-output*)) (output-stream *json-output*))
(setf (car (stack *json-output*)) #\,)))
(defmacro with-output ((stream) &body body)
"Set up a JSON streaming encoder context on STREAM, then evaluate BODY."
`(let ((*json-output* (make-instance 'json-output-stream :output-stream ,stream)))
,@body))
(defmacro with-output-to-string* (() &body body)
"Set up a JSON streaming encoder context, then evaluate BODY.
Return a string with the generated JSON output."
`(with-output-to-string (s)
(with-output (s)
,@body)))
(define-condition no-json-output-context (error)
()
(:report "No JSON output context is active")
(:documentation "This condition is signalled when one of the stream
encoding function is used outside the dynamic context of a
WITH-OUTPUT or WITH-OUTPUT-TO-STRING* body."))
(defmacro with-aggregate ((begin-char end-char) &body body)
`(progn
(unless (boundp '*json-output*)
(error 'no-json-output-context))
(when (stack *json-output*)
(next-aggregate-element))
(princ ,begin-char (output-stream *json-output*))
(push nil (stack *json-output*))
(prog1
(progn ,@body)
(pop (stack *json-output*))
(princ ,end-char (output-stream *json-output*)))))
(defmacro with-array (() &body body)
"Open a JSON array, then run BODY. Inside the body,
ENCODE-ARRAY-ELEMENT must be called to encode elements to the opened
array. Must be called within an existing JSON encoder context, see
WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate (#\[ #\]) ,@body))
(defmacro with-object (() &body body)
"Open a JSON object, then run BODY. Inside the body,
ENCODE-OBJECT-ELEMENT or WITH-OBJECT-ELEMENT must be called to encode
elements to the object. Must be called within an existing JSON
encoder context, see WITH-OUTPUT and WITH-OUTPUT-TO-STRING*."
`(with-aggregate (#\{ #\}) ,@body))
(defun encode-array-element (object)
"Encode OBJECT as next array element to the last JSON array opened
with WITH-ARRAY in the dynamic context. OBJECT is encoded using the
ENCODE generic function, so it must be of a type for which an ENCODE
method is defined."
(next-aggregate-element)
(encode object (output-stream *json-output*)))
(defun encode-object-element (key value)
"Encode KEY and VALUE as object element to the last JSON object
opened with WITH-OBJECT in the dynamic context. KEY and VALUE are
encoded using the ENCODE generic function, so they both must be of a
type for which an ENCODE method is defined."
(next-aggregate-element)
(encode key (output-stream *json-output*))
(princ #\: (output-stream *json-output*))
(encode value (output-stream *json-output*))
value)
(defmacro with-object-element ((key) &body body)
"Open a new encoding context to encode a JSON object element. KEY
is the key of the element. The value will be whatever BODY
serializes to the current JSON output context using one of the
stream encoding functions. This can be used to stream out nested
object structures."
`(progn
(next-aggregate-element)
(encode ,key (output-stream *json-output*))
(setf (car (stack *json-output*)) #\:)
(unwind-protect
(progn ,@body)
(setf (car (stack *json-output*)) #\,))))
| 6,726 | Common Lisp | .lisp | 175 | 32.005714 | 87 | 0.631458 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 7721d1fe77509ca2113a3acbc261163ea00c96b2f537659278c48ac6d6140f12 | 2,452 | [
-1
] |
2,453 | package.lisp | hoytech_antiweb/bundled/yason/package.lisp | ;; This file is part of yason, a Common Lisp JSON parser/encoder
;;
;; Copyright (c) 2008 Hans Hübner
;; All rights reserved.
;;
;; Please see the file LICENSE in the distribution.
(defpackage :yason
(:use :cl)
(:nicknames :json)
(:export
;; Parser
#:parse
#:*parse-object-key-fn*
#:*parse-json-arrays-as-vectors*
#:*parse-json-booleans-as-symbols*
#:true
#:false
;; Basic encoder interface
#:encode
;; Streaming encoder interface
#:with-output
#:with-output-to-string*
#:no-json-output-context
#:with-array
#:encode-array-element
#:with-object
#:encode-object-element
#:with-object-element
#:with-response))
| 680 | Common Lisp | .lisp | 29 | 20.034483 | 64 | 0.68323 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 5020c2b5f2fd0c1010a62ec803ce362d6b389c08237dc4609d1af42ea246796b | 2,453 | [
-1
] |
2,454 | load.lisp | hoytech_antiweb/bundled/yason/load.lisp | ;; Antiweb (C) Doug Hoyte
;; yason loader modeled after load.lisp from CL-PPCRE
(in-package :cl-user)
(let ((files '("package"
"parse"
"encode"))
(base-directory
(make-pathname :name nil :type nil :version nil
:defaults (parse-namestring *load-truename*)))
must-compile)
(with-compilation-unit ()
(dolist (file files)
(let ((pathname (make-pathname :name file :type "lisp" :version nil
:defaults base-directory)))
(let ((compiled-pathname (compile-file-pathname pathname)))
(unless (and (not must-compile)
(probe-file compiled-pathname)
(< (file-write-date pathname)
(file-write-date compiled-pathname)))
(setq must-compile t)
(compile-file pathname))
(setq pathname compiled-pathname))
(load pathname)))))
| 963 | Common Lisp | .lisp | 23 | 29.73913 | 73 | 0.552239 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 10ffdf3d2f83085ffb95935006c57a85e569437c3daea4ec5fd39d5e2d49f664 | 2,454 | [
-1
] |
2,455 | cffi-corman.lisp | hoytech_antiweb/bundled/cffi/cffi-corman.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-corman.lisp --- CFFI-SYS implementation for Corman Lisp.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:c-types #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%mem-ref
#:%mem-set
;#:make-shareable-byte-vector
;#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:defcfun-helper-forms
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; Backend mis-features.
cffi-features:no-long-long
cffi-features:no-foreign-funcall
;; OS/CPU features.
cffi-features:windows
cffi-features:x86
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Basic Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(cpointerp ptr))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(cpointer= ptr1 ptr2))
(defun null-pointer ()
"Return a null pointer."
(create-foreign-ptr))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(cpointer-null ptr))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(let ((new-ptr (create-foreign-ptr)))
(setf (cpointer-value new-ptr)
(+ (cpointer-value ptr) offset))
new-ptr))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(int-to-foreign-ptr address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(foreign-ptr-to-int ptr))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(malloc size))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(free ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (malloc ,size-var)))
(unwind-protect
(progn ,@body)
(free ,var))))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
;(defun make-shareable-byte-vector (size)
; "Create a Lisp vector of SIZE bytes can passed to
;WITH-POINTER-TO-VECTOR-DATA."
; (make-array size :element-type '(unsigned-byte 8)))
;
;(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
; "Bind PTR-VAR to a foreign pointer to the data in VECTOR."
; `(sb-sys:without-gcing
; (let ((,ptr-var (sb-sys:vector-sap ,vector)))
; ,@body)))
;;;# Dereferencing
;; According to the docs, Corman's C Function Definition Parser
;; converts int to long, so we'll assume that.
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to a CormanCL type."
(ecase type-keyword
(:char :char)
(:unsigned-char :unsigned-char)
(:short :short)
(:unsigned-short :unsigned-short)
(:int :long)
(:unsigned-int :unsigned-long)
(:long :long)
(:unsigned-long :unsigned-long)
(:float :single-float)
(:double :double-float)
(:pointer :handle)
(:void :void)))
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(unless (eql offset 0)
(setq ptr (inc-pointer ptr offset)))
(ecase type
(:char (cref (:char *) ptr 0))
(:unsigned-char (cref (:unsigned-char *) ptr 0))
(:short (cref (:short *) ptr 0))
(:unsigned-short (cref (:unsigned-short *) ptr 0))
(:int (cref (:long *) ptr 0))
(:unsigned-int (cref (:unsigned-long *) ptr 0))
(:long (cref (:long *) ptr 0))
(:unsigned-long (cref (:unsigned-long *) ptr 0))
(:float (cref (:single-float *) ptr 0))
(:double (cref (:double-float *) ptr 0))
(:pointer (cref (:handle *) ptr 0))))
;(define-compiler-macro %mem-ref (&whole form ptr type &optional (offset 0))
; (if (constantp type)
; `(cref (,(convert-foreign-type type) *) ,ptr ,offset)
; form))
(defun %mem-set (value ptr type &optional (offset 0))
"Set the object of TYPE at OFFSET bytes from PTR."
(unless (eql offset 0)
(setq ptr (inc-pointer ptr offset)))
(ecase type
(:char (setf (cref (:char *) ptr 0) value))
(:unsigned-char (setf (cref (:unsigned-char *) ptr 0) value))
(:short (setf (cref (:short *) ptr 0) value))
(:unsigned-short (setf (cref (:unsigned-short *) ptr 0) value))
(:int (setf (cref (:long *) ptr 0) value))
(:unsigned-int (setf (cref (:unsigned-long *) ptr 0) value))
(:long (setf (cref (:long *) ptr 0) value))
(:unsigned-long (setf (cref (:unsigned-long *) ptr 0) value))
(:float (setf (cref (:single-float *) ptr 0) value))
(:double (setf (cref (:double-float *) ptr 0) value))
(:pointer (setf (cref (:handle *) ptr 0) value))))
;;;# Calling Foreign Functions
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(sizeof (convert-foreign-type type-keyword)))
;; Couldn't find anything in sys/ffi.lisp and the C declaration parser
;; doesn't seem to care about alignment so we'll assume that it's the
;; same as its size.
(defun %foreign-type-alignment (type-keyword)
(sizeof (convert-foreign-type type-keyword)))
(defun find-dll-containing-function (name)
"Searches for NAME in the loaded DLLs. If found, returns
the DLL's name (a string), else returns NIL."
(dolist (dll ct::*dlls-loaded*)
(when (ignore-errors
(ct::get-dll-proc-address name (ct::dll-record-handle dll)))
(return (ct::dll-record-name dll)))))
;; This won't work at all...
;(defmacro %foreign-funcall (name &rest args)
; (let ((sym (gensym)))
; `(let (,sym)
; (ct::install-dll-function ,(find-dll-containing-function name)
; ,name ,sym)
; (funcall ,sym ,@(loop for (type arg) on args by #'cddr
; if arg collect arg)))))
;; It *might* be possible to implement by copying
;; most of the code from Corman's DEFUN-DLL.
(defmacro %foreign-funcall (name &rest args)
"Call a foreign function NAME passing arguments ARGS."
`(format t "~&;; Calling ~A with args ~S.~%" ,name ',args))
(defun defcfun-helper-forms (name lisp-name rettype args types)
"Return 2 values for DEFCFUN. A prelude form and a caller form."
(let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name)))
;; XXX This will only work if the dll is already loaded, fix this.
(dll (find-dll-containing-function name)))
(values
`(defun-dll ,ff-name
,(mapcar (lambda (type)
(list (gensym) (convert-foreign-type type)))
types)
:return-type ,(convert-foreign-type rettype)
:library-name ,dll
:entry-name ,name
;; we want also :pascal linkage type to access
;; the win32 api for instance..
:linkage-type :c)
`(,ff-name ,@args))))
;;;# Callbacks
;; defun-c-callback vs. defun-direct-c-callback?
;; same issue as Allegro, no return type declaration, should we coerce?
(defmacro %defcallback (name rettype arg-names arg-types body-form)
(declare (ignore rettype))
(with-unique-names (cb-sym)
`(progn
(defun-c-callback ,cb-sym
,(mapcar (lambda (sym type) (list sym (convert-foreign-type type)))
arg-names arg-types)
,body-form)
(setf (get ',name 'callback-ptr)
(get-callback-procinst ',cb-sym)))))
;;; Just continue to use the plist for now even though this really
;;; should use a *CALLBACKS* hash table and not define the callbacks
;;; as gensyms. Someone with access to Corman should update this.
(defun %callback (name)
(get name 'callback-ptr))
;;;# Loading Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library NAME."
(ct::get-dll-record name))
(defun %close-foreign-library (name)
"Close the foreign library NAME."
(error "Not implemented."))
;;;# Foreign Globals
;; FFI to GetProcAddress from the Win32 API.
;; "The GetProcAddress function retrieves the address of an exported
;; function or variable from the specified dynamic-link library (DLL)."
(defun-dll get-proc-address
((module HMODULE)
(name LPCSTR))
:return-type FARPROC
:library-name "Kernel32.dll"
:entry-name "GetProcAddress"
:linkage-type :pascal)
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(let ((str (lisp-string-to-c-string name)))
(unwind-protect
(dolist (dll ct::*dlls-loaded*)
(let ((ptr (get-proc-address
(int-to-foreign-ptr (ct::dll-record-handle dll))
str)))
(when (not (cpointer-null ptr))
(return ptr))))
(free str))))
;;;# Finalizers
(defvar *finalizers* '()
"Weak alist that holds registered finalizers.")
(defvar *finalizers-cs* (threads:allocate-critical-section))
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(flet ((get-finalizers (obj)
(assoc obj *finalizers* :test #'eq :key #'ccl:weak-pointer-obj)))
(threads:with-synchronization *finalizers-cs*
(let ((pair (get-finalizers object)))
(if (null pair)
(push (list (ccl:make-weak-pointer object) function) *finalizers*)
(push function (cdr pair)))))
(ccl:register-finalization
object (lambda (obj)
(threads:with-synchronization *finalizers-cs*
(mapc #'funcall (cdr (get-finalizers obj)))
(setq *finalizers*
(delete obj *finalizers*
:test #'eq :key #'ccl:weak-pointer-obj))))))
object)
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(threads:with-synchronization *finalizers-cs*
(setq *finalizers*
(delete object *finalizers* :test #'eq :key #'ccl:weak-pointer-obj))))
| 12,795 | Common Lisp | .lisp | 312 | 36.695513 | 80 | 0.656235 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 623d9379f698674617727d417104b56602e30cdaf890c96114c30e73dc80bd5e | 2,455 | [
-1
] |
2,456 | cffi-scl.lisp | hoytech_antiweb/bundled/cffi/cffi-scl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-scl.lisp --- CFFI-SYS implementation for the Scieneer Common Lisp.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2006, Scieneer Pty Ltd.
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;; For posterity, a few optimizations we might use in the future:
#-(and)
(defun lisp-string-to-foreign (string ptr size)
(c-call::deport-string-to-system-area string ptr size :iso-8859-1))
#-(and)
(defun foreign-string-to-lisp (ptr &optional (size most-positive-fixnum)
(null-terminated-p t))
(unless (null-pointer-p ptr)
(if null-terminated-p
(c-call::naturalize-c-string ptr :iso-8859-1)
(c-call::naturalize-c-string ptr :iso-8859-1 size))))
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:alien #:c-call #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; OS/CPU features.
#+unix cffi-features:unix
#+x86 cffi-features:x86
#+amd64 cffi-features:x86-64
#+(and ppc (not ppc64)) cffi-features:ppc32
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(if (eq ext:*case-mode* :upper)
(string-upcase name)
(string-downcase name)))
;;;# Basic Pointer Operations
(declaim (inline pointerp))
(defun pointerp (ptr)
"Return true if 'ptr is a foreign pointer."
(sys:system-area-pointer-p ptr))
(declaim (inline pointer-eq))
(defun pointer-eq (ptr1 ptr2)
"Return true if 'ptr1 and 'ptr2 point to the same address."
(sys:sap= ptr1 ptr2))
(declaim (inline null-pointer))
(defun null-pointer ()
"Construct and return a null pointer."
(sys:int-sap 0))
(declaim (inline null-pointer-p))
(defun null-pointer-p (ptr)
"Return true if 'ptr is a null pointer."
(zerop (sys:sap-int ptr)))
(declaim (inline inc-pointer))
(defun inc-pointer (ptr offset)
"Return a pointer pointing 'offset bytes past 'ptr."
(sys:sap+ ptr offset))
(declaim (inline make-pointer))
(defun make-pointer (address)
"Return a pointer pointing to 'address."
(sys:int-sap address))
(declaim (inline pointer-address))
(defun pointer-address (ptr)
"Return the address pointed to by 'ptr."
(sys:sap-int ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind 'var to 'size bytes of foreign memory during 'body. The
pointer in 'var is invalid beyond the dynamic extent of 'body, and
may be stack-allocated if supported by the implementation. If
'size-var is supplied, it will be bound to 'size during 'body."
(unless size-var
(setf size-var (gensym (symbol-name '#:size))))
;; If the size is constant we can stack-allocate.
(cond ((constantp size)
(let ((alien-var (gensym (symbol-name '#:alien))))
`(with-alien ((,alien-var (array (unsigned 8) ,(eval size))))
(let ((,size-var ,size)
(,var (alien-sap ,alien-var)))
(declare (ignorable ,size-var))
,@body))))
(t
`(let ((,size-var ,size))
(alien:with-bytes (,var ,size-var)
,@body)))))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack and on the
;;; heap. The main CFFI package defines macros that wrap 'foreign-alloc and
;;; 'foreign-free in 'unwind-protect for the common usage when the memory has
;;; dynamic extent.
(defun %foreign-alloc (size)
"Allocate 'size bytes on the heap and return a pointer."
(declare (type (unsigned-byte #-64bit 32 #+64bit 64) size))
(alien-funcall (extern-alien "malloc"
(function system-area-pointer unsigned))
size))
(defun foreign-free (ptr)
"Free a 'ptr allocated by 'foreign-alloc."
(declare (type system-area-pointer ptr))
(alien-funcall (extern-alien "free"
(function (values) system-area-pointer))
ptr))
;;;# Shareable Vectors
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of 'size bytes that can passed to
'with-pointer-to-vector-data."
(make-array size :element-type '(unsigned-byte 8)))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind 'ptr-var to a foreign pointer to the data in 'vector."
(let ((vector-var (gensym (symbol-name '#:vector))))
`(let ((,vector-var ,vector))
(ext:with-pinned-object (,vector-var)
(let ((,ptr-var (sys:vector-sap ,vector-var)))
,@body)))))
;;;# Dereferencing
;;; Define the %MEM-REF and %MEM-SET functions, as well as compiler
;;; macros that optimize the case where the type keyword is constant
;;; at compile-time.
(defmacro define-mem-accessors (&body pairs)
`(progn
(defun %mem-ref (ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (,fn ptr offset)))))
(defun %mem-set (value ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (setf (,fn ptr offset) value)))))
(define-compiler-macro %mem-ref
(&whole form ptr type &optional (offset 0))
(if (constantp type)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(,',fn ,ptr ,offset))))
form))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
(once-only (value)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(setf (,',fn ,ptr ,offset)
,value)))))
form))))
(define-mem-accessors
(:char sys:signed-sap-ref-8)
(:unsigned-char sys:sap-ref-8)
(:short sys:signed-sap-ref-16)
(:unsigned-short sys:sap-ref-16)
(:int sys:signed-sap-ref-32)
(:unsigned-int sys:sap-ref-32)
(:long #-64bit sys:signed-sap-ref-32 #+64bit sys:signed-sap-ref-64)
(:unsigned-long #-64bit sys:sap-ref-32 #+64bit sys:sap-ref-64)
(:long-long sys:signed-sap-ref-64)
(:unsigned-long-long sys:sap-ref-64)
(:float sys:sap-ref-single)
(:double sys:sap-ref-double)
#+long-float (:long-double sys:sap-ref-long)
(:pointer sys:sap-ref-sap))
;;;# Calling Foreign Functions
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an ALIEN type."
(ecase type-keyword
(:char 'char)
(:unsigned-char 'unsigned-char)
(:short 'short)
(:unsigned-short 'unsigned-short)
(:int 'int)
(:unsigned-int 'unsigned-int)
(:long 'long)
(:unsigned-long 'unsigned-long)
(:long-long '(signed 64))
(:unsigned-long-long '(unsigned 64))
(:float 'single-float)
(:double 'double-float)
#+long-float
(:long-double 'long-float)
(:pointer 'system-area-pointer)
(:void 'void)))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(values (truncate (alien-internals:alien-type-bits
(alien-internals:parse-alien-type
(convert-foreign-type type-keyword)))
8)))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(values (truncate (alien-internals:alien-type-alignment
(alien-internals:parse-alien-type
(convert-foreign-type type-keyword)))
8)))
(defun foreign-funcall-type-and-args (args)
"Return an 'alien function type for 'args."
(let ((return-type nil))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type))
finally (return (values types fargs return-type)))))
(defmacro %%foreign-funcall (name types fargs rettype)
"Internal guts of '%foreign-funcall."
`(alien-funcall (extern-alien ,name (function ,rettype ,@types))
,@fargs))
(defmacro %foreign-funcall (name &rest args)
"Perform a foreign function call, document it more later."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall ,name ,types ,fargs ,rettype)))
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Funcall a pointer to a foreign function."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (function)
`(with-alien ((,function (* (function ,rettype ,@types)) ,ptr))
(alien-funcall ,function ,@fargs)))))
;;; Callbacks
(defmacro %defcallback (name rettype arg-names arg-types &body body)
`(alien:defcallback ,name
(,(convert-foreign-type rettype)
,@(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types))
,@body))
(declaim (inline %callback))
(defun %callback (name)
(alien:callback-sap name))
;;;# Loading and Closing Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library 'name."
(ext:load-dynamic-object name))
(defun %close-foreign-library (name)
"Closes the foreign library 'name."
(ext:close-dynamic-object name))
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol 'name."
(let ((sap (sys:foreign-symbol-address name)))
(if (zerop (sys:sap-int sap)) nil sap)))
;;;# Finalizers
;;;
;;; TODO: confirm that SCL's finalizer API is the same as CMUCL's.
;;; -- LO 2006/04/24
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(ext:finalize object function))
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(ext:cancel-finalization object)) | 12,098 | Common Lisp | .lisp | 301 | 34.913621 | 78 | 0.657191 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 98788ead42256a42feac3fdfa262afae07229fb0ab0d0d488d4984c7d47f1d05 | 2,456 | [
-1
] |
2,457 | package.lisp | hoytech_antiweb/bundled/cffi/package.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; package.lisp --- Package definition for CFFI.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cl-user)
(defpackage #:cffi
(:use #:common-lisp #:cffi-sys #:cffi-utils)
(:export
;; Primitive pointer operations.
#:foreign-free
#:foreign-alloc
#:mem-aref
#:mem-ref
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:incf-pointer
#:with-foreign-pointer
#:make-pointer
#:pointer-address
;; Shareable vectors.
#:make-shareable-vector
#:with-pointer-to-vector-data
;; Foreign string operations.
#:foreign-string-alloc
#:foreign-string-free
#:foreign-string-to-lisp
#:lisp-string-to-foreign
#:with-foreign-string
#:with-foreign-pointer-as-string
;; Foreign function operations.
#:defcfun
#:foreign-funcall
;; Foreign library operations.
#:*foreign-library-directories*
#:*darwin-framework-directories*
#:define-foreign-library
#:load-foreign-library
#:load-foreign-library-error
#:use-foreign-library
;#:close-foreign-library
;; Callbacks.
#:callback
#:get-callback
#:defcallback
;; Foreign type operations.
#:defcstruct
#:defcunion
#:defctype
#:defcenum
#:defbitfield
#:define-foreign-type
#:foreign-enum-keyword
#:foreign-enum-value
#:foreign-bitfield-symbols
#:foreign-bitfield-value
#:foreign-slot-pointer
#:foreign-slot-value
#:foreign-slot-offset
#:foreign-slot-names
#:foreign-type-alignment
#:foreign-type-size
#:with-foreign-object
#:with-foreign-objects
#:with-foreign-slots
#:convert-to-foreign
#:convert-from-foreign
#:free-converted-object
;; Extensible foreign type operations.
#:translate-to-foreign
#:translate-from-foreign
#:free-translated-object
#:expand-to-foreign-dyn
#:expand-to-foreign
#:expand-from-foreign
;; Foreign globals.
#:defcvar
#:get-var-pointer
#:foreign-symbol-pointer
;; Finalizers.
#:finalize
#:cancel-finalization
))
| 3,214 | Common Lisp | .lisp | 107 | 26.700935 | 70 | 0.715163 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 168e1f2d2807346a9717412b6c883448a44af57acfe13e88243e2b5d06d21939 | 2,457 | [
-1
] |
2,458 | cffi-ecl.lisp | hoytech_antiweb/bundled/cffi/cffi-ecl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-ecl.lisp --- ECL backend for CFFI.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%mem-ref
#:%mem-set
#:%foreign-funcall
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:%defcallback
#:%callback
#:foreign-symbol-pointer
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; Backend mis-features.
cffi-features:no-long-long
cffi-features:no-finalizers
;; OS/CPU features.
#+:darwin cffi-features:darwin
#+:darwin cffi-features:unix
#+:unix cffi-features:unix
#+:win32 cffi-features:windows
;; XXX: figure out a way to get a X86 feature
;;#+:athlon cffi-features:x86
#+:powerpc7450 cffi-features:ppc32
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Allocation
(defun %foreign-alloc (size)
"Allocate SIZE bytes of foreign-addressable memory."
(si:allocate-foreign-data :void size))
(defun foreign-free (ptr)
"Free a pointer PTR allocated by FOREIGN-ALLOC."
(si:free-foreign-data ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var))))
;;;# Misc. Pointer Operations
(defun null-pointer ()
"Construct and return a null pointer."
(si:allocate-foreign-data :void 0))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(si:null-pointer-p ptr))
(defun inc-pointer (ptr offset)
"Return a pointer OFFSET bytes past PTR."
(ffi:make-pointer (+ (ffi:pointer-address ptr) offset) :void))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(typep ptr 'si:foreign-data))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(= (ffi:pointer-address ptr1) (ffi:pointer-address ptr2)))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(ffi:make-pointer address :void))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(ffi:pointer-address ptr))
;;;# Dereferencing
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(let* ((type (convert-foreign-type type))
(type-size (ffi:size-of-foreign-type type)))
(si:foreign-data-ref-elt
(si:foreign-data-recast ptr (+ offset type-size) :void) offset type)))
(defun %mem-set (value ptr type &optional (offset 0))
"Set an object of TYPE at OFFSET bytes from PTR."
(let* ((type (convert-foreign-type type))
(type-size (ffi:size-of-foreign-type type)))
(si:foreign-data-set-elt
(si:foreign-data-recast ptr (+ offset type-size) :void)
offset type value)))
;;;# Type Operations
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an ECL type keyword."
(ecase type-keyword
(:char :byte)
(:unsigned-char :unsigned-byte)
(:short :short)
(:unsigned-short :unsigned-short)
(:int :int)
(:unsigned-int :unsigned-int)
(:long :long)
(:unsigned-long :unsigned-long)
(:float :float)
(:double :double)
(:pointer :pointer-void)
(:void :void)))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(nth-value 0 (ffi:size-of-foreign-type
(convert-foreign-type type-keyword))))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(nth-value 1 (ffi:size-of-foreign-type
(convert-foreign-type type-keyword))))
;;;# Calling Foreign Functions
(defun produce-function-call (c-name nargs)
(format nil "~a(~a)" c-name
(subseq "#0,#1,#2,#3,#4,#5,#6,#7,#8,#9,#a,#b,#c,#d,#e,#f,#g,#h,#i,#j,#k,#l,#m,#n,#o,#p,#q,#r,#s,#t,#u,#v,#w,#x,#y,#z"
0 (max 0 (1- (* nargs 3))))))
#-dffi
(defun foreign-function-inline-form (name arg-types arg-values return-type)
"Generate a C-INLINE form for a foreign function call."
`(ffi:c-inline
,arg-values ,arg-types ,return-type
,(produce-function-call name (length arg-values))
:one-liner t :side-effects t))
#+dffi
(defun foreign-function-dynamic-form (name arg-types arg-values return-type)
"Generate a dynamic FFI form for a foreign function call."
`(si:call-cfun (si:find-foreign-symbol ,name :default :pointer-void 0)
,return-type (list ,@arg-types) (list ,@arg-values)))
(defun foreign-funcall-parse-args (args)
"Return three values, lists of arg types, values, and result type."
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type) into types
and collect arg into values
else do (setf return-type (convert-foreign-type type))
finally (return (values types values return-type)))))
(defmacro %foreign-funcall (name &rest args)
"Call a foreign function."
(multiple-value-bind (types values return-type)
(foreign-funcall-parse-args args)
#-dffi (foreign-function-inline-form name types values return-type)
#+dffi (foreign-function-dynamic-form name types values return-type)))
#+dffi
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Funcall a pointer to a foreign function."
(multiple-value-bind (types values return-type)
(foreign-funcall-parse-args args)
`(si:call-cfun ,ptr ,return-type (list ,@arg-types) (list ,@arg-values))))
;;;# Foreign Libraries
(defun %load-foreign-library (name)
"Load a foreign library from NAME."
#-dffi (error "LOAD-FOREIGN-LIBRARY requires ECL's DFFI support. Use ~
FFI:LOAD-FOREIGN-LIBRARY with a constant argument instead.")
#+dffi (si:load-foreign-module name))
;;;# Callbacks
;;; Create a package to contain the symbols for callback functions.
;;; We want to redefine callbacks with the same symbol so the internal
;;; data structures are reused.
(defpackage #:cffi-callbacks
(:use))
(defvar *callbacks* (make-hash-table))
;;; Intern a symbol in the CFFI-CALLBACKS package used to name the
;;; internal callback for NAME.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun intern-callback (name)
(intern (format nil "~A::~A" (package-name (symbol-package name))
(symbol-name name))
'#:cffi-callbacks)))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
(let ((cb-name (intern-callback name)))
`(progn
(ffi:defcallback (,cb-name :cdecl)
,(convert-foreign-type rettype)
,(mapcar #'list arg-names
(mapcar #'convert-foreign-type arg-types))
,@body)
(setf (gethash ',name *callbacks*) ',cb-name))))
(defun %callback (name)
(multiple-value-bind (symbol winp)
(gethash name *callbacks*)
(unless winp
(error "Undefined callback: ~S" name))
(ffi:callback name)))
;;;# Foreign Globals
(defun convert-external-name (name)
"Add an underscore to NAME if necessary for the ABI."
#+:darwin (concatenate 'string "_" name)
#-:darwin name)
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(si:find-foreign-symbol (convert-external-name name)
:default :pointer-void 0))
;;;# Finalizers
(defun finalize (object function)
(declare (ignore object function))
(error "ECL does not support finalizers."))
(defun cancel-finalization (object)
(declare (ignore object))
(error "ECL does not support finalizers.")) | 9,758 | Common Lisp | .lisp | 241 | 36.116183 | 127 | 0.67807 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | c2aeb98404f2cb3bfd769ce319716f73fa4ca997c65faa82d00e71d3fdccc9be | 2,458 | [
76400
] |
2,459 | foreign-vars.lisp | hoytech_antiweb/bundled/cffi/foreign-vars.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; foreign-vars.lisp --- High-level interface to foreign globals.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Accessing Foreign Globals
(defun lisp-var-name (name)
"Return the Lisp symbol for foreign var NAME."
(etypecase name
(list (second name))
(string (intern (format nil "*~A*" (canonicalize-symbol-name-case
(substitute #\- #\_ name)))))
(symbol name)))
(defun foreign-var-name (name)
"Return the foreign var name of NAME."
(etypecase name
(list (first name))
(string name)
(symbol (let ((dname (string-downcase (symbol-name name))))
(string-trim '(#\*) (substitute #\_ #\- dname))))))
(defun get-var-pointer (symbol)
"Return a pointer to the foreign global variable relative to SYMBOL."
(foreign-symbol-pointer (get symbol 'foreign-var-name)))
(defun foreign-symbol-pointer-or-lose (foreign-name)
"Like foreign-symbol-ptr but throws an error instead of
returning nil when foreign-name is not found."
(or (foreign-symbol-pointer foreign-name)
(error "Trying to access undefined foreign variable ~S." foreign-name)))
(defmacro defcvar (name type &key read-only)
"Define a foreign global variable."
(let* ((lisp-name (lisp-var-name name))
(foreign-name (foreign-var-name name))
(fn (symbolicate '#:%var-accessor- lisp-name)))
(when (aggregatep (parse-type type)) ; we can't really setf an aggregate
(setq read-only t)) ; type, at least not yet...
`(progn
;; Save foreign-name for posterior access by get-var-pointer
(setf (get ',lisp-name 'foreign-var-name) ,foreign-name)
;; Getter
(defun ,fn ()
(mem-ref (foreign-symbol-pointer-or-lose ,foreign-name) ',type))
;; Setter
(defun (setf ,fn) (value)
,(if read-only '(declare (ignore value)) (values))
,(if read-only
`(error ,(format nil "Trying to modify read-only foreign var: ~A."
lisp-name))
`(setf (mem-ref (foreign-symbol-pointer-or-lose ,foreign-name)
',type)
value)))
;; While most Lisps already expand DEFINE-SYMBOL-MACRO to an
;; EVAL-WHEN form like this, that is not required by the
;; standard so we do it ourselves.
(eval-when (:compile-toplevel :load-toplevel :execute)
(define-symbol-macro ,lisp-name (,fn))))))
| 3,670 | Common Lisp | .lisp | 77 | 41.987013 | 80 | 0.663692 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | cf004be22234f24135b83413e157a8995b66c82e9ea952cfea847ad421a9829e | 2,459 | [
-1
] |
2,460 | types.lisp | hoytech_antiweb/bundled/cffi/types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; types.lisp --- User-defined CFFI types.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Built-In Types
(define-built-in-foreign-type :char)
(define-built-in-foreign-type :unsigned-char)
(define-built-in-foreign-type :short)
(define-built-in-foreign-type :unsigned-short)
(define-built-in-foreign-type :int)
(define-built-in-foreign-type :unsigned-int)
(define-built-in-foreign-type :long)
(define-built-in-foreign-type :unsigned-long)
(define-built-in-foreign-type :float)
(define-built-in-foreign-type :double)
(define-built-in-foreign-type :void)
#-cffi-features:no-long-long
(progn
(define-built-in-foreign-type :long-long)
(define-built-in-foreign-type :unsigned-long-long))
;;; Define the type parser for the :POINTER type. If no type argument
;;; is provided, a void pointer will be created.
(define-type-spec-parser :pointer (&optional type)
(if type
(make-instance 'foreign-pointer-type :pointer-type (parse-type type))
(make-instance 'foreign-pointer-type :pointer-type nil)))
;;; When some lisp other than SCL supports :long-double we should
;;; use #-cffi-features:no-long-double here instead.
#+(and scl long-float) (define-built-in-foreign-type :long-double)
;;;# Foreign Pointers
(define-modify-macro incf-pointer (&optional (offset 1)) inc-pointer)
(defun mem-ref (ptr type &optional (offset 0))
"Return the value of TYPE at OFFSET bytes from PTR. If TYPE is aggregate,
we don't return its 'value' but a pointer to it, which is PTR itself."
(let ((ptype (parse-type type)))
(if (aggregatep ptype)
(inc-pointer ptr offset)
(let ((raw-value (%mem-ref ptr (canonicalize ptype) offset)))
(if (translate-p ptype)
(translate-type-from-foreign raw-value ptype)
raw-value)))))
(define-compiler-macro mem-ref (&whole form ptr type &optional (offset 0))
"Compiler macro to open-code MEM-REF when TYPE is constant."
(if (constantp type)
(let ((parsed-type (parse-type (eval type))))
(if (aggregatep parsed-type)
`(inc-pointer ,ptr ,offset)
(expand-type-from-foreign
`(%mem-ref ,ptr ,(canonicalize parsed-type) ,offset)
parsed-type)))
form))
(defun mem-set (value ptr type &optional (offset 0))
"Set the value of TYPE at OFFSET bytes from PTR to VALUE."
(let ((ptype (parse-type type)))
(%mem-set (if (translate-p ptype)
(translate-type-to-foreign value ptype)
value)
ptr (canonicalize ptype) offset)))
(define-setf-expander mem-ref (ptr type &optional (offset 0) &environment env)
"SETF expander for MEM-REF that doesn't rebind TYPE.
This is necessary for the compiler macro on MEM-SET to be able
to open-code (SETF MEM-REF) forms."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
;; if either TYPE or OFFSET are constant, we avoid rebinding them
;; so that the compiler macros on MEM-SET and %MEM-SET work.
(with-unique-names (store type-tmp offset-tmp)
(values
(append (unless (constantp type) (list type-tmp))
(unless (constantp offset) (list offset-tmp))
dummies)
(append (unless (constantp type) (list type))
(unless (constantp offset) (list offset))
vals)
(list store)
`(progn
(mem-set ,store ,getter
,@(if (constantp type) (list type) (list type-tmp))
,@(if (constantp offset) (list offset) (list offset-tmp)))
,store)
`(mem-ref ,getter
,@(if (constantp type) (list type) (list type-tmp))
,@(if (constantp offset) (list offset) (list offset-tmp)))))))
(define-compiler-macro mem-set
(&whole form value ptr type &optional (offset 0))
"Compiler macro to open-code (SETF MEM-REF) when type is constant."
(if (constantp type)
(let ((parsed-type (parse-type (eval type))))
`(%mem-set ,(expand-type-to-foreign value parsed-type) ,ptr
,(canonicalize parsed-type) ,offset))
form))
;;;# Dereferencing Foreign Arrays
(defun mem-aref (ptr type &optional (index 0))
"Like MEM-REF except for accessing 1d arrays."
(mem-ref ptr type (* index (foreign-type-size type))))
(define-compiler-macro mem-aref (&whole form ptr type &optional (index 0))
"Compiler macro to open-code MEM-AREF when TYPE (and eventually INDEX)."
(if (constantp type)
(if (constantp index)
`(mem-ref ,ptr ,type
,(* (eval index) (foreign-type-size (eval type))))
`(mem-ref ,ptr ,type (* ,index ,(foreign-type-size (eval type)))))
form))
(define-setf-expander mem-aref (ptr type &optional (index 0) &environment env)
"SETF expander for MEM-AREF."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
;; we avoid rebinding type and index, if possible (and if type is not
;; constant, we don't bother about the index), so that the compiler macros
;; on MEM-SET or %MEM-SET can work.
(with-unique-names (store type-tmp index-tmp)
(values
(append (unless (constantp type)
(list type-tmp))
(unless (and (constantp type) (constantp index))
(list index-tmp))
dummies)
(append (unless (constantp type)
(list type))
(unless (and (constantp type) (constantp index))
(list index))
vals)
(list store)
;; Here we'll try to calculate the offset from the type and index,
;; or if not possible at least get the type size early.
`(progn
,(if (constantp type)
(if (constantp index)
`(mem-set ,store ,getter ,type
,(* (eval index) (foreign-type-size (eval type))))
`(mem-set ,store ,getter ,type
(* ,index-tmp ,(foreign-type-size (eval type)))))
`(mem-set ,store ,getter ,type-tmp
(* ,index-tmp (foreign-type-size ,type-tmp))))
,store)
`(mem-aref ,getter
,@(if (constantp type)
(list type)
(list type-tmp))
,@(if (and (constantp type) (constantp index))
(list index)
(list index-tmp)))))))
;;;# Foreign Structures
;;;## Foreign Structure Slots
(defgeneric foreign-struct-slot-pointer (ptr slot)
(:documentation
"Get the address of SLOT relative to PTR."))
(defgeneric foreign-struct-slot-pointer-form (ptr slot)
(:documentation
"Return a form to get the address of SLOT in PTR."))
(defgeneric foreign-struct-slot-value (ptr slot)
(:documentation
"Return the value of SLOT in structure PTR."))
(defgeneric (setf foreign-struct-slot-value) (value ptr slot)
(:documentation
"Set the value of a SLOT in structure PTR."))
(defgeneric foreign-struct-slot-value-form (ptr slot)
(:documentation
"Return a form to get the value of SLOT in struct PTR."))
(defgeneric foreign-struct-slot-set-form (value ptr slot)
(:documentation
"Return a form to set the value of SLOT in struct PTR."))
(defclass foreign-struct-slot ()
((name :initarg :name :reader slot-name)
(offset :initarg :offset :accessor slot-offset)
(type :initarg :type :accessor slot-type))
(:documentation "Base class for simple and aggregate slots."))
(defmethod foreign-struct-slot-pointer (ptr (slot foreign-struct-slot))
"Return the address of SLOT relative to PTR."
(inc-pointer ptr (slot-offset slot)))
(defmethod foreign-struct-slot-pointer-form (ptr (slot foreign-struct-slot))
"Return a form to get the address of SLOT relative to PTR."
(let ((offset (slot-offset slot)))
(if (zerop offset)
ptr
`(inc-pointer ,ptr ,offset))))
(defun foreign-slot-names (type)
"Returns a list of TYPE's slot names in no particular order."
(loop for value being the hash-values
in (slots (follow-typedefs (parse-type type)))
collect (slot-name value)))
;;;### Simple Slots
(defclass simple-struct-slot (foreign-struct-slot)
()
(:documentation "Non-aggregate structure slots."))
(defmethod foreign-struct-slot-value (ptr (slot simple-struct-slot))
"Return the value of a simple SLOT from a struct at PTR."
(mem-ref ptr (slot-type slot) (slot-offset slot)))
(defmethod foreign-struct-slot-value-form (ptr (slot simple-struct-slot))
"Return a form to get the value of a slot from PTR."
`(mem-ref ,ptr ',(slot-type slot) ,(slot-offset slot)))
(defmethod (setf foreign-struct-slot-value) (value ptr (slot simple-struct-slot))
"Set the value of a simple SLOT to VALUE in PTR."
(setf (mem-ref ptr (slot-type slot) (slot-offset slot)) value))
(defmethod foreign-struct-slot-set-form (value ptr (slot simple-struct-slot))
"Return a form to set the value of a simple structure slot."
`(setf (mem-ref ,ptr ',(slot-type slot) ,(slot-offset slot)) ,value))
;;;### Aggregate Slots
(defclass aggregate-struct-slot (foreign-struct-slot)
((count :initarg :count :accessor slot-count))
(:documentation "Aggregate structure slots."))
;;; A case could be made for just returning an error here instead of
;;; this rather DWIM-ish behavior to return the address. It would
;;; complicate being able to chain together slot names when accessing
;;; slot values in nested structures though.
(defmethod foreign-struct-slot-value (ptr (slot aggregate-struct-slot))
"Return a pointer to SLOT relative to PTR."
(foreign-struct-slot-pointer ptr slot))
(defmethod foreign-struct-slot-value-form (ptr (slot aggregate-struct-slot))
"Return a form to get the value of SLOT relative to PTR."
(foreign-struct-slot-pointer-form ptr slot))
;;; This is definitely an error though. Eventually, we could define a
;;; new type of type translator that can convert certain aggregate
;;; types, notably C strings or arrays of integers. For now, just error.
(defmethod (setf foreign-struct-slot-value) (value ptr (slot aggregate-struct-slot))
"Signal an error; setting aggregate slot values is forbidden."
(declare (ignore value ptr))
(error "Cannot set value of aggregate slot ~A." slot))
(defmethod foreign-struct-slot-set-form (value ptr (slot aggregate-struct-slot))
"Signal an error; setting aggregate slot values is forbidden."
(declare (ignore value ptr))
(error "Cannot set value of aggregate slot ~A." slot))
;;;## Defining Foreign Structures
(defun make-struct-slot (name offset type count)
"Make the appropriate type of structure slot."
;; If TYPE is an aggregate type or COUNT is >1, create an
;; AGGREGATE-STRUCT-SLOT, otherwise a SIMPLE-STRUCT-SLOT.
(if (or (> count 1) (aggregatep (parse-type type)))
(make-instance 'aggregate-struct-slot :offset offset :type type
:name name :count count)
(make-instance 'simple-struct-slot :offset offset :type type
:name name)))
;;; Regarding structure alignment, the following ABIs were checked:
;;; - System-V ABI: x86, x86-64, ppc, arm, mips and itanium. (more?)
;;; - Mac OS X ABI Function Call Guide: ppc32, ppc64 and x86.
;;;
;;; Rules used here:
;;;
;;; 1. "An entire structure or union object is aligned on the same boundary
;;; as its most strictly aligned member."
;;; 2. "Each member is assigned to the lowest available offset with the
;;; appropriate alignment. This may require internal padding, depending
;;; on the previous member."
;;; 3. "A structure's size is increased, if necessary, to make it a multiple
;;; of the alignment. This may require tail padding, depending on the last
;;; member."
;;;
;;; Special case from darwin/ppc32's ABI:
;;; http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/index.html
;;;
;;; 1. "The embedding alignment of the first element in a data structure is
;;; equal to the element's natural alignment."
;;; 2. "For subsequent elements that have a natural alignment greater than 4
;;; bytes, the embedding alignment is 4, unless the element is a vector."
;;; (note: this applies for structures too)
;; FIXME: get a better name for this. --luis
(defun get-alignment (type alignment-type firstp)
"Return alignment for TYPE according to ALIGNMENT-TYPE."
(declare (ignorable firstp))
(ecase alignment-type
(:normal #-(and cffi-features:darwin cffi-features:ppc32)
(foreign-type-alignment type)
#+(and cffi-features:darwin cffi-features:ppc32)
(if firstp
(foreign-type-alignment type)
(min 4 (foreign-type-alignment type))))))
(defun adjust-for-alignment (type offset alignment-type firstp)
"Return OFFSET aligned properly for TYPE according to ALIGNMENT-TYPE."
(let* ((align (get-alignment type alignment-type firstp))
(rem (mod offset align)))
(if (zerop rem)
offset
(+ offset (- align rem)))))
(defun notice-foreign-struct-definition (name-and-options slots)
"Parse and install a foreign structure definition."
(destructuring-bind (name &key size #+nil alignment)
(mklist name-and-options)
(let ((struct (make-instance 'foreign-struct-type :name name))
(current-offset 0)
(max-align 1)
(firstp t))
;; determine offsets
(dolist (slotdef slots)
(destructuring-bind (slotname type &key (count 1) offset) slotdef
(when (eq (canonicalize-foreign-type type) :void)
(error "void type not allowed in structure definition: ~S" slotdef))
(setq current-offset
(or offset
(adjust-for-alignment type current-offset :normal firstp)))
(let* ((slot (make-struct-slot slotname current-offset type count))
(align (get-alignment (slot-type slot) :normal firstp)))
(setf (gethash slotname (slots struct)) slot)
(when (> align max-align)
(setq max-align align)))
(incf current-offset (* count (foreign-type-size type))))
(setq firstp nil))
;; calculate padding and alignment
(setf (alignment struct) max-align) ; See point 1 above.
(let ((tail-padding (- max-align (rem current-offset max-align))))
(unless (= tail-padding max-align) ; See point 3 above.
(incf current-offset tail-padding)))
(setf (size struct) (or size current-offset))
(notice-foreign-type struct))))
(defmacro defcstruct (name &body fields)
"Define the layout of a foreign structure."
(discard-docstring fields)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-struct-definition ',name ',fields)))
;;;## Accessing Foreign Structure Slots
(defun get-slot-info (type slot-name)
"Return the slot info for SLOT-NAME or raise an error."
(let* ((struct (follow-typedefs (parse-type type)))
(info (gethash slot-name (slots struct))))
(unless info
(error "Undefined slot ~A in foreign type ~A." slot-name type))
info))
(defun foreign-slot-pointer (ptr type slot-name)
"Return the address of SLOT-NAME in the structure at PTR."
(foreign-struct-slot-pointer ptr (get-slot-info type slot-name)))
(defun foreign-slot-offset (type slot-name)
"Return the offset of SLOT in a struct TYPE."
(slot-offset (get-slot-info type slot-name)))
(defun foreign-slot-value (ptr type slot-name)
"Return the value of SLOT-NAME in the foreign structure at PTR."
(foreign-struct-slot-value ptr (get-slot-info type slot-name)))
(define-compiler-macro foreign-slot-value (&whole form ptr type slot-name)
"Optimizer for FOREIGN-SLOT-VALUE when TYPE is constant."
(if (and (constantp type) (constantp slot-name))
(foreign-struct-slot-value-form
ptr (get-slot-info (eval type) (eval slot-name)))
form))
(define-setf-expander foreign-slot-value (ptr type slot-name &environment env)
"SETF expander for FOREIGN-SLOT-VALUE."
(multiple-value-bind (dummies vals newval setter getter)
(get-setf-expansion ptr env)
(declare (ignore setter newval))
(if (and (constantp type) (constantp slot-name))
;; if TYPE and SLOT-NAME are constant we avoid rebinding them
;; so that the compiler macro on FOREIGN-SLOT-SET works.
(with-unique-names (store)
(values
dummies
vals
(list store)
`(progn
(foreign-slot-set ,store ,getter ,type ,slot-name)
,store)
`(foreign-slot-value ,getter ,type ,slot-name)))
;; if not...
(with-unique-names (store slot-name-tmp type-tmp)
(values
(list* type-tmp slot-name-tmp dummies)
(list* type slot-name vals)
(list store)
`(progn
(foreign-slot-set ,store ,getter ,type-tmp ,slot-name-tmp)
,store)
`(foreign-slot-value ,getter ,type-tmp ,slot-name-tmp))))))
(defun foreign-slot-set (value ptr type slot-name)
"Set the value of SLOT-NAME in a foreign structure."
(setf (foreign-struct-slot-value ptr (get-slot-info type slot-name)) value))
(define-compiler-macro foreign-slot-set
(&whole form value ptr type slot-name)
"Optimizer when TYPE and SLOT-NAME are constant."
(if (and (constantp type) (constantp slot-name))
(foreign-struct-slot-set-form
value ptr (get-slot-info (eval type) (eval slot-name)))
form))
(defmacro with-foreign-slots ((vars ptr type) &body body)
"Create local symbol macros for each var in VARS to reference
foreign slots in PTR of TYPE. Similar to WITH-SLOTS."
(let ((ptr-var (gensym "PTR")))
`(let ((,ptr-var ,ptr))
(symbol-macrolet
,(loop for var in vars
collect `(,var (foreign-slot-value ,ptr-var ',type ',var)))
,@body))))
;;;# Foreign Unions
;;;
;;; A union is a FOREIGN-STRUCT-TYPE in which all slots have an offset
;;; of zero.
;;; See also the notes regarding ABI requirements in
;;; NOTICE-FOREIGN-STRUCT-DEFINITION
(defun notice-foreign-union-definition (name-and-options slots)
"Parse and install a foreign union definition."
(destructuring-bind (name &key size)
(mklist name-and-options)
(let ((struct (make-instance 'foreign-struct-type :name name))
(max-size 0)
(max-align 0))
(dolist (slotdef slots)
(destructuring-bind (slotname type &key (count 1)) slotdef
(when (eq (canonicalize-foreign-type type) :void)
(error "void type not allowed in union definition: ~S" slotdef))
(let* ((slot (make-struct-slot slotname 0 type count))
(size (* count (foreign-type-size type)))
(align (foreign-type-alignment (slot-type slot))))
(setf (gethash slotname (slots struct)) slot)
(when (> size max-size)
(setf max-size size))
(when (> align max-align)
(setf max-align align)))))
(setf (size struct) (or size max-size))
(setf (alignment struct) max-align)
(notice-foreign-type struct))))
(defmacro defcunion (name &body fields)
"Define the layout of a foreign union."
(discard-docstring fields)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-union-definition ',name ',fields)))
;;;# Operations on Types
(defmethod foreign-type-alignment (type)
"Return the alignment in bytes of a foreign type."
(foreign-type-alignment (parse-type type)))
(defun foreign-alloc (type &key (initial-element nil initial-element-p)
(initial-contents nil initial-contents-p)
(count 1 count-p) null-terminated-p)
"Allocate enough memory to hold COUNT objects of type TYPE. If
INITIAL-ELEMENT is supplied, each element of the newly allocated
memory is initialized with its value. If INITIAL-CONTENTS is supplied,
each of its elements will be used to initialize the contents of the
newly allocated memory."
(let (contents-length)
;; Some error checking, etc...
(when (and null-terminated-p
(not (eq (canonicalize-foreign-type type) :pointer)))
(error "Cannot use :NULL-TERMINATED-P with non-pointer types."))
(when (and initial-element-p initial-contents-p)
(error "Cannot specify both :INITIAL-ELEMENT and :INITIAL-CONTENTS"))
(when initial-contents-p
(setq contents-length (length initial-contents))
(if count-p
(assert (>= count contents-length))
(setq count contents-length)))
;; Everything looks good.
(let ((ptr (%foreign-alloc (* (foreign-type-size type)
(if null-terminated-p (1+ count) count)))))
(when initial-element-p
(dotimes (i count)
(setf (mem-aref ptr type i) initial-element)))
(when initial-contents-p
(dotimes (i contents-length)
(setf (mem-aref ptr type i) (elt initial-contents i))))
(when null-terminated-p
(setf (mem-aref ptr :pointer count) (null-pointer)))
ptr)))
;;; Stuff we could optimize here:
;;; 1. (and (constantp type) (constantp count)) => calculate size
;;; 2. (constantp type) => use the translators' expanders
#-(and)
(define-compiler-macro foreign-alloc
(&whole form type &key (initial-element nil initial-element-p)
(initial-contents nil initial-contents-p) (count 1 count-p))
)
(defmacro with-foreign-object ((var type &optional (count 1)) &body body)
"Bind VAR to a pointer to COUNT objects of TYPE during BODY.
The buffer has dynamic extent and may be stack allocated."
`(with-foreign-pointer
(,var ,(if (constantp type)
;; with-foreign-pointer may benefit from constant folding:
(if (constantp count)
(* (eval count) (foreign-type-size (eval type)))
`(* ,count ,(foreign-type-size (eval type))))
`(* ,count (foreign-type-size ,type))))
,@body))
(defmacro with-foreign-objects (bindings &rest body)
(if bindings
`(with-foreign-object ,(car bindings)
(with-foreign-objects ,(cdr bindings)
,@body))
`(progn ,@body)))
;;;# User-defined Types and Translations.
(defmacro define-foreign-type (type lambda-list &body body)
"Define a parameterized type."
(discard-docstring body)
`(progn
(define-type-spec-parser ,type ,lambda-list
(make-instance 'foreign-typedef :name ',type
:actual-type (parse-type (progn ,@body))))
',type))
(defmacro defctype (name base-type &key (translate-p t) documentation)
"Utility macro for simple C-like typedefs. A similar effect could be
obtained using define-foreign-type."
(declare (ignore documentation))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type
(make-instance 'foreign-typedef :name ',name
:actual-type (parse-type ',base-type)
:translate-p ,translate-p))))
;;;## Anonymous Type Translators
;;;
;;; (:wrapper :to-c some-function :from-c another-function)
;;;
;;; TODO: We will need to add a FREE function to this as well I think.
;;; --james
(defclass foreign-type-wrapper (foreign-typedef)
((to-c :initarg :to-c)
(from-c :initarg :from-c))
(:documentation "Class for the wrapper type."))
(define-type-spec-parser :wrapper (base-type &key to-c from-c)
(make-instance 'foreign-type-wrapper
:actual-type (parse-type base-type)
:to-c (or to-c 'identity)
:from-c (or from-c 'identity)))
(defmethod unparse (name (type foreign-type-wrapper))
(declare (ignore name))
`(:wrapper ,(name (actual-type type))
:to-c ,(slot-value type 'to-c)
:from-c ,(slot-value type 'from-c)))
(defmethod translate-type-to-foreign (value (type foreign-type-wrapper))
(let ((actual-type (actual-type type)))
(translate-type-to-foreign
(funcall (slot-value type 'to-c) value) actual-type)))
(defmethod translate-type-from-foreign (value (type foreign-type-wrapper))
(let ((actual-type (actual-type type)))
(funcall (slot-value type 'from-c)
(translate-type-from-foreign value actual-type))))
;;;# Other types
(define-foreign-type :boolean (&optional (base-type :int))
"Boolean type. Maps to an :int by default. Only accepts integer types."
(ecase (canonicalize-foreign-type base-type)
((:char
:unsigned-char
:int
:unsigned-int
:long
:unsigned-long) base-type)))
(defmethod unparse ((name (eql :boolean)) type)
"Unparser for the :BOOLEAN type."
`(:boolean ,(name (actual-type type))))
(defmethod translate-to-foreign (value (name (eql :boolean)))
(if value 1 0))
(defmethod translate-from-foreign (value (name (eql :boolean)))
(not (zerop value)))
(defmethod expand-to-foreign (value (name (eql :boolean)))
"Optimization for the :boolean type."
(if (constantp value)
(if (eval value) 1 0)
`(if ,value 1 0)))
(defmethod expand-from-foreign (value (name (eql :boolean)))
"Optimization for the :boolean type."
(if (constantp value) ; very unlikely, heh
(not (zerop (eval value)))
`(not (zerop ,value))))
;;;# Typedefs for built-in types.
(defctype :uchar :unsigned-char :translate-p nil)
(defctype :ushort :unsigned-short :translate-p nil)
(defctype :uint :unsigned-int :translate-p nil)
(defctype :ulong :unsigned-long :translate-p nil)
#-cffi-features:no-long-long
(progn
(defctype :llong :long-long :translate-p nil)
(defctype :ullong :unsigned-long-long :translate-p nil))
;;; We try to define the :[u]int{8,16,32,64} types by looking at
;;; the sizes of the built-in integer types and defining typedefs.
(eval-when (:compile-toplevel :load-toplevel :execute)
(labels ((find-matching-size (size types)
(car (member size types :key #'foreign-type-size)))
(notice-foreign-typedef (type actual-type)
(notice-foreign-type
(make-instance 'foreign-typedef :name type
:actual-type (find-type actual-type)
:translate-p nil)))
(match-types (sized-types builtin-types)
(loop for (type . size) in sized-types do
(let ((match (find-matching-size size builtin-types)))
(when match
(notice-foreign-typedef type match))))))
;; signed
(match-types '((:int8 . 1) (:int16 . 2) (:int32 . 4) (:int64 . 8))
'(:char :short :int :long
#-cffi-features:no-long-long :long-long))
;; unsigned
(match-types '((:uint8 . 1) (:uint16 . 2) (:uint32 . 4) (:uint64 . 8))
'(:unsigned-char :unsigned-short :unsigned-int :unsigned-long
#-cffi-features:no-long-long :unsigned-long-long)))) | 28,330 | Common Lisp | .lisp | 601 | 40.628952 | 93 | 0.660637 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b3a4ec0161ecb14e1633b3483ea9f0c9b3919ee3aa447a79904391a55c14291c | 2,460 | [
-1
] |
2,461 | cffi-clisp.lisp | hoytech_antiweb/bundled/cffi/cffi-clisp.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-clisp.lisp --- CFFI-SYS implementation for CLISP.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; (C) 2005-2006, Joerg Hoehle <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
#:foreign-symbol-pointer
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;; FIXME: long-long could be supported anyway on 64-bit machines. --luis
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; OS/CPU features.
#+:macos cffi-features:darwin
#+:unix cffi-features:unix
#+:win32 cffi-features:windows
))
(cond ((string-equal (machine-type) "X86_64")
(pushnew 'cffi-features:x86-64 *features*))
((member :pc386 *features*)
(pushnew 'cffi-features:x86 *features*))
;; FIXME: probably catches PPC64 as well
((string-equal (machine-type) "POWER MACINTOSH")
(pushnew 'cffi-features:ppc32 *features*))))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Built-In Foreign Types
(defun convert-foreign-type (type)
"Convert a CFFI built-in type keyword to a CLisp FFI type."
(ecase type
(:char 'ffi:char)
(:unsigned-char 'ffi:uchar)
(:short 'ffi:short)
(:unsigned-short 'ffi:ushort)
(:int 'ffi:int)
(:unsigned-int 'ffi:uint)
(:long 'ffi:long)
(:unsigned-long 'ffi:ulong)
(:long-long 'ffi:sint64)
(:unsigned-long-long 'ffi:uint64)
(:float 'ffi:single-float)
(:double 'ffi:double-float)
;; Clisp's FFI:C-POINTER converts NULL to NIL. For now
;; we have a workaround in the pointer operations...
(:pointer 'ffi:c-pointer)
(:void nil)))
(defun %foreign-type-size (type)
"Return the size in bytes of objects having foreign type TYPE."
(nth-value 0 (ffi:sizeof (convert-foreign-type type))))
;; Remind me to buy a beer for whoever made getting the alignment
;; of foreign types part of the public interface in CLisp. :-)
(defun %foreign-type-alignment (type)
"Return the structure alignment in bytes of foreign TYPE."
#+(and cffi-features:darwin cffi-features:ppc32)
(case type
((:double :long-long :unsigned-long-long)
(return-from %foreign-type-alignment 8)))
;; Override not necessary for the remaining types...
(nth-value 1 (ffi:sizeof (convert-foreign-type type))))
;;;# Basic Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(or (null ptr) (typep ptr 'ffi:foreign-address)))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(eql (ffi:foreign-address-unsigned ptr1)
(ffi:foreign-address-unsigned ptr2)))
(defun null-pointer ()
"Return a null foreign pointer."
(ffi:unsigned-foreign-address 0))
(defun null-pointer-p (ptr)
"Return true if PTR is a null foreign pointer."
(or (null ptr) (zerop (ffi:foreign-address-unsigned ptr))))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(ffi:unsigned-foreign-address
(+ offset (if (null ptr) 0 (ffi:foreign-address-unsigned ptr)))))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(ffi:unsigned-foreign-address address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(ffi:foreign-address-unsigned ptr))
;;;# Foreign Memory Allocation
(defun %foreign-alloc (size)
"Allocate SIZE bytes of foreign-addressable memory and return a
pointer to the allocated block. An implementation-specific error
is signalled if the memory cannot be allocated."
(ffi:foreign-address (ffi:allocate-shallow 'ffi:uint8 :count size)))
(defun foreign-free (ptr)
"Free a pointer PTR allocated by FOREIGN-ALLOC. The results
are undefined if PTR is used after being freed."
(ffi:foreign-free ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to a pointer to SIZE bytes of foreign-addressable
memory during BODY. Both PTR and the memory block pointed to
have dynamic extent and may be stack allocated if supported by
the implementation. If SIZE-VAR is supplied, it will be bound to
SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
(let ((obj-var (gensym)))
`(let ((,size-var ,size))
(ffi:with-foreign-object
(,obj-var `(ffi:c-array ffi:uint8 ,,size-var))
(let ((,var (ffi:foreign-address ,obj-var)))
,@body)))))
;;;# Memory Access
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference a pointer OFFSET bytes from PTR to an object of
built-in foreign TYPE. Returns the object as a foreign pointer
or Lisp number."
(ffi:memory-as ptr (convert-foreign-type type) offset))
(define-compiler-macro %mem-ref (&whole form ptr type &optional (offset 0))
"Compiler macro to open-code when TYPE is constant."
(if (constantp type)
`(ffi:memory-as ,ptr ',(convert-foreign-type (eval type)) ,offset)
form))
(defun %mem-set (value ptr type &optional (offset 0))
"Set a pointer OFFSET bytes from PTR to an object of built-in
foreign TYPE to VALUE."
(setf (ffi:memory-as ptr (convert-foreign-type type) offset) value))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
;; (setf (ffi:memory-as) value) is exported, but not so nice
;; w.r.t. the left to right evaluation rule
`(ffi::write-memory-as ,value ,ptr ',(convert-foreign-type (eval type)) ,offset)
form))
;;;# Foreign Function Calling
(defun parse-foreign-funcall-args (args)
"Return three values, a list of CLisp FFI types, a list of
values to pass to the function, and the CLisp FFI return type."
(let ((return-type nil))
(loop for (type arg) on args by #'cddr
if arg collect (list (gensym) (convert-foreign-type type)) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type))
finally (return (values types fargs return-type)))))
(defmacro %foreign-funcall (name &rest args)
"Invoke a foreign function called NAME, taking pairs of
foreign-type/value pairs from ARGS. If a single element is left
over at the end of ARGS, it specifies the foreign return type of
the function call."
(multiple-value-bind (types fargs rettype)
(parse-foreign-funcall-args args)
(let ((ctype `(ffi:c-function (:arguments ,@types)
(:return-type ,rettype)
(:language :stdc))))
`(funcall
(load-time-value
(multiple-value-bind (ff error)
(ignore-errors
(ffi::foreign-library-function
,name (ffi::foreign-library :default)
nil
;; As of version 2.40 (CVS 2006-09-03, to be more precise),
;; FFI::FOREIGN-LIBRARY-FUNCTION takes an additional
;; 'PROPERTIES' argument.
#+#.(cl:if (cl:= (cl:length (ext:arglist
'ffi::foreign-library-function)) 5)
'(and) '(or))
nil
(ffi:parse-c-type ',ctype)))
(or ff
(warn (format nil "~?"
(simple-condition-format-control error)
(simple-condition-format-arguments error))))))
,@fargs))))
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Similar to %foreign-funcall but takes a pointer instead of a string."
(multiple-value-bind (types fargs rettype)
(parse-foreign-funcall-args args)
`(funcall (ffi:foreign-function ,ptr
(load-time-value
(ffi:parse-c-type
'(ffi:c-function
(:arguments ,@types)
(:return-type ,rettype)
(:language :stdc)))))
,@fargs)))
;;;# Callbacks
;;; *CALLBACKS* contains the callbacks defined by the CFFI DEFCALLBACK
;;; macro. The symbol naming the callback is the key, and the value
;;; is a list containing a Lisp function, the parsed CLISP FFI type of
;;; the callback, and a saved pointer that should not persist across
;;; saved images.
(defvar *callbacks* (make-hash-table))
;;; Return a CLISP FFI function type for a CFFI callback function
;;; given a return type and list of argument names and types.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun callback-type (rettype arg-names arg-types)
(ffi:parse-c-type
`(ffi:c-function
(:arguments ,@(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types))
(:return-type ,(convert-foreign-type rettype))
(:language :stdc)))))
;;; Register and create a callback function.
(defun register-callback (name function parsed-type)
(setf (gethash name *callbacks*)
(list function parsed-type
(ffi:with-foreign-object (ptr 'ffi:c-pointer)
;; Create callback by converting Lisp function to foreign
(setf (ffi:memory-as ptr parsed-type) function)
(ffi:foreign-value ptr)))))
;;; Restore all saved callback pointers when restarting the Lisp
;;; image. This is pushed onto CUSTOM:*INIT-HOOKS*.
;;; Needs clisp > 2.35, bugfix 2005-09-29
(defun restore-callback-pointers ()
(maphash
(lambda (name list)
(register-callback name (first list) (second list)))
*callbacks*))
;;; Add RESTORE-CALLBACK-POINTERS to the lists of functions to run
;;; when an image is restarted.
(eval-when (:load-toplevel :execute)
(pushnew 'restore-callback-pointers custom:*init-hooks*))
;;; Define a callback function NAME to run BODY with arguments
;;; ARG-NAMES translated according to ARG-TYPES and the return type
;;; translated according to RETTYPE. Obtain a pointer that can be
;;; passed to C code for this callback by calling %CALLBACK.
(defmacro %defcallback (name rettype arg-names arg-types &body body)
`(register-callback ',name (lambda ,arg-names ,@body)
,(callback-type rettype arg-names arg-types)))
;;; Look up the name of a callback and return a pointer that can be
;;; passed to a C function. Signals an error if no callback is
;;; defined called NAME.
(defun %callback (name)
(multiple-value-bind (list winp) (gethash name *callbacks*)
(unless winp
(error "Undefined callback: ~S" name))
(third list)))
;;;# Loading and Closing Foreign Libraries
(defun %load-foreign-library (name)
"Load a foreign library from NAME."
(ffi::foreign-library name))
(defun %close-foreign-library (name)
"Close a foreign library NAME."
(ffi:close-foreign-library name))
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(prog1 (ignore-errors
(ffi:foreign-address
(ffi::foreign-library-variable
name (ffi::foreign-library :default) nil nil)))))
;;;# Finalizers
(defvar *finalizers* (make-hash-table :test 'eq :weak :key)
"Weak hashtable that holds registered finalizers.")
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(push function (gethash object *finalizers*))
(ext:finalize object
(lambda (obj)
(mapc #'funcall (gethash obj *finalizers*))))
object)
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(remhash object *finalizers*))
| 13,695 | Common Lisp | .lisp | 316 | 37.512658 | 86 | 0.673019 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a8463dabd01fd96e146b4c24482649d9e6577fcc55c3c05d9423610edce6d421 | 2,461 | [
-1
] |
2,462 | enum.lisp | hoytech_antiweb/bundled/cffi/enum.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; enum.lisp --- Defining foreign constants as Lisp keywords.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Foreign Constants as Lisp Keywords
;;;
;;; This module defines the DEFCENUM macro, which provides an
;;; interface for defining a type and associating a set of integer
;;; constants with keyword symbols for that type.
;;;
;;; The keywords are automatically translated to the appropriate
;;; constant for the type by a type translator when passed as
;;; arguments or a return value to a foreign function.
(defclass foreign-enum (foreign-type-alias)
((keyword-values
:initform (make-hash-table :test 'eq)
:reader keyword-values)
(value-keywords
:initform (make-hash-table)
:reader value-keywords))
(:documentation "Describes a foreign enumerated type."))
(defun make-foreign-enum (type-name base-type values)
"Makes a new instance of the foreign-enum class."
(let ((type (make-instance 'foreign-enum :name type-name
:actual-type (parse-type base-type)))
(default-value 0))
(dolist (pair values)
(destructuring-bind (keyword &optional (value default-value))
(mklist pair)
(check-type keyword keyword)
(check-type value integer)
(if (gethash keyword (keyword-values type))
(error "A foreign enum cannot contain duplicate keywords: ~S."
keyword)
(setf (gethash keyword (keyword-values type)) value))
;; This completely arbitrary behaviour: we keep the last we
;; value->keyword mapping. I suppose the opposite would be just as
;; good (keeping the first). Returning a list with all the keywords
;; might be a solution too? Suggestions welcome. --luis
(setf (gethash value (value-keywords type)) keyword)
(setq default-value (1+ value))))
type))
(defmacro defcenum (name-and-options &body enum-list)
"Define an foreign enumerated type."
(discard-docstring enum-list)
(destructuring-bind (name &optional (base-type :int))
(mklist name-and-options)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type
(make-foreign-enum ',name ',base-type ',enum-list)))))
;;; These [four] functions could be good canditates for compiler macros
;;; when the value or keyword is constant. I am not going to bother
;;; until someone has a serious performance need to do so though. --jamesjb
(defun %foreign-enum-value (type keyword &key errorp)
(check-type keyword keyword)
(or (gethash keyword (keyword-values type))
(when errorp
(error "~S is not defined as a keyword for enum type ~S."
keyword type))))
(defun foreign-enum-value (type keyword &key (errorp t))
"Convert a KEYWORD into an integer according to the enum TYPE."
(let ((type-obj (parse-type type)))
(if (not (typep type-obj 'foreign-enum))
(error "~S is not a foreign enum type." type)
(%foreign-enum-value type-obj keyword :errorp errorp))))
(defun %foreign-enum-keyword (type value &key errorp)
(check-type value integer)
(or (gethash value (value-keywords type))
(when errorp
(error "~S is not defined as a value for enum type ~S."
value type))))
(defun foreign-enum-keyword (type value &key (errorp t))
"Convert an integer VALUE into a keyword according to the enum TYPE."
(let ((type-obj (parse-type type)))
(if (not (typep type-obj 'foreign-enum))
(error "~S is not a foreign enum type." type)
(%foreign-enum-keyword type-obj value :errorp errorp))))
(defmethod translate-type-to-foreign (value (type foreign-enum))
(if (keywordp value)
(%foreign-enum-value type value)
value))
(defmethod translate-type-from-foreign (value (type foreign-enum))
(%foreign-enum-keyword type value))
;;;# Foreign Bitfields as Lisp keywords
;;;
;;; DEFBITFIELD is an abstraction similar to the one provided by DEFCENUM.
;;; With some changes to DEFCENUM, this could certainly be implemented on
;;; top of it.
(defclass foreign-bitfield (foreign-type-alias)
((symbol-values
:initform (make-hash-table :test 'eq)
:reader symbol-values)
(value-symbols
:initform (make-hash-table)
:reader value-symbols))
(:documentation "Describes a foreign bitfield type."))
(defun make-foreign-bitfield (type-name base-type values)
"Makes a new instance of the foreign-bitfield class."
(let ((type (make-instance 'foreign-bitfield :name type-name
:actual-type (parse-type base-type)))
(bit-floor 1))
(dolist (pair values)
;; bit-floor rule: find the greatest single-bit int used so far,
;; and store its left-shift
(destructuring-bind (symbol &optional
(value (prog1 bit-floor
(setf bit-floor (ash bit-floor 1)))
value-p))
(mklist pair)
(check-type symbol symbol)
(when value-p
(check-type value integer)
(when (and (>= value bit-floor) (single-bit-p value))
(setf bit-floor (ash value 1))))
(if (gethash symbol (symbol-values type))
(error "A foreign bitfield cannot contain duplicate symbols: ~S."
symbol)
(setf (gethash symbol (symbol-values type)) value))
(push symbol (gethash value (value-symbols type)))))
type))
(defmacro defbitfield (name-and-options &body masks)
"Define an foreign enumerated type."
(discard-docstring masks)
(destructuring-bind (name &optional (base-type :int))
(mklist name-and-options)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type
(make-foreign-bitfield ',name ',base-type ',masks)))))
(defun %foreign-bitfield-value (type symbols)
(reduce #'logior symbols
:key (lambda (symbol)
(check-type symbol symbol)
(or (gethash symbol (symbol-values type))
(error "~S is not a valid symbol for bitfield type ~S."
symbol type)))))
(defun foreign-bitfield-value (type symbols)
"Convert a list of symbols into an integer according to the TYPE bitfield."
(let ((type-obj (parse-type type)))
(if (not (typep type-obj 'foreign-bitfield))
(error "~S is not a foreign bitfield type." type)
(%foreign-bitfield-value type-obj symbols))))
(defun %foreign-bitfield-symbols (type value)
(check-type value integer)
(loop for mask being the hash-keys in (value-symbols type)
using (hash-value symbols)
when (= (logand value mask) mask)
append symbols))
(defun foreign-bitfield-symbols (type value)
"Convert an integer VALUE into a list of matching symbols according to
the bitfield TYPE."
(let ((type-obj (parse-type type)))
(if (not (typep type-obj 'foreign-bitfield))
(error "~S is not a foreign bitfield type." type)
(%foreign-bitfield-symbols type-obj value))))
(defmethod translate-type-to-foreign (value (type foreign-bitfield))
(if (integerp value)
value
(%foreign-bitfield-value type (mklist value))))
(defmethod translate-type-from-foreign (value (type foreign-bitfield))
(%foreign-bitfield-symbols type value))
| 8,508 | Common Lisp | .lisp | 183 | 40.557377 | 77 | 0.679793 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | c69b4ab00443e98da5e9989f80934600293590526531bf306a75b6ae37f21425 | 2,462 | [
-1
] |
2,463 | strings.lisp | hoytech_antiweb/bundled/cffi/strings.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; strings.lisp --- Operations on foreign strings.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Foreign String Conversion
;;;
;;; Functions for converting NULL-terminated C-strings to Lisp strings
;;; and vice versa. Currently this is blithely ignorant of encoding
;;; and assumes characters can fit in 8 bits.
(defun lisp-string-to-foreign (string ptr size)
"Copy at most SIZE-1 characters from a Lisp STRING to PTR.
The foreign string will be null-terminated."
(decf size)
(etypecase string
(string
(loop with i = 0 for char across string
while (< i size)
do (%mem-set (char-code char) ptr :unsigned-char (post-incf i))
finally (%mem-set 0 ptr :unsigned-char i)))
((array (unsigned-byte 8))
(loop with i = 0 for elt across string
while (< i size)
do (%mem-set elt ptr :unsigned-char (post-incf i))
finally (%mem-set 0 ptr :unsigned-char i)))))
(defun foreign-string-to-lisp (ptr &optional (size array-total-size-limit)
(null-terminated-p t))
"Copy at most SIZE characters from PTR into a Lisp string.
If PTR is a null pointer, returns nil."
(unless (null-pointer-p ptr)
(with-output-to-string (s)
(loop for i fixnum from 0 below size
for code = (mem-ref ptr :unsigned-char i)
until (and null-terminated-p (zerop code))
do (write-char (code-char code) s)))))
;;;# Using Foreign Strings
(defun foreign-string-alloc (string)
"Allocate a foreign string containing Lisp string STRING.
The string must be freed with FOREIGN-STRING-FREE."
(check-type string (or string (array (unsigned-byte 8))))
(let* ((length (1+ (length string)))
(ptr (foreign-alloc :char :count length)))
(lisp-string-to-foreign string ptr length)
ptr))
(defun foreign-string-free (ptr)
"Free a foreign string allocated by FOREIGN-STRING-ALLOC."
(foreign-free ptr))
(defmacro with-foreign-string ((var lisp-string) &body body)
"Bind VAR to a foreign string containing LISP-STRING in BODY."
(with-unique-names (str length)
`(let* ((,str ,lisp-string)
(,length (progn
(check-type ,str (or string (array (unsigned-byte 8))))
(1+ (length ,str)))))
(with-foreign-pointer (,var ,length)
(lisp-string-to-foreign ,str ,var ,length)
,@body))))
(defmacro with-foreign-pointer-as-string
((var size &optional size-var) &body body)
"Like WITH-FOREIGN-POINTER except VAR as a Lisp string is used as
the return value of an implicit PROGN around BODY."
`(with-foreign-pointer (,var ,size ,size-var)
(progn
,@body
(foreign-string-to-lisp ,var))))
;;;# Automatic Conversion of Foreign Strings
(defctype :string :pointer)
(defmethod translate-to-foreign ((s string) (name (eql :string)))
(values (foreign-string-alloc s) t))
(defmethod translate-to-foreign (obj (name (eql :string)))
(cond
((pointerp obj)
(values obj nil))
((typep obj '(array (unsigned-byte 8)))
(values (foreign-string-alloc obj) t))
(t (error "~A is not a Lisp string, (array (unsigned-byte 8) or pointer."
obj))))
(defmethod translate-from-foreign (ptr (name (eql :string)))
(foreign-string-to-lisp ptr))
(defmethod free-translated-object (ptr (name (eql :string)) free-p)
(when free-p
(foreign-string-free ptr)))
;;; It'd be pretty nice if returning multiple values from translators
;;; worked as expected:
;;;
;;; (define-type-translator :string :from-c (type value)
;;; "Type translator for string arguments."
;;; (once-only (value)
;;; `(values (foreign-string-to-lisp ,value) ,value)))
;;;
;;; For now we'll just define a new type.
;;;
;;; Also as this examples shows, it'd be nice to specify
;;; that we don't want to inherit the from-c translators.
;;; So we could use (defctype :string+ptr :string) and
;;; just add the new :from-c translator.
(defctype :string+ptr :pointer)
(defmethod translate-to-foreign ((s string) (name (eql :string+ptr)))
(values (foreign-string-alloc s) t))
(defmethod translate-to-foreign (obj (name (eql :string+ptr)))
(cond
((pointerp obj)
(values obj nil))
((typep obj '(array (unsigned-byte 8)))
(values (foreign-string-alloc obj) t))
(t (error "~A is not a Lisp string, (array (unsigned-byte 8) or pointer."
obj))))
(defmethod translate-from-foreign (value (name (eql :string+ptr)))
(list (foreign-string-to-lisp value) value))
(defmethod free-translated-object (value (name (eql :string+ptr)) free-p)
(when free-p
(foreign-string-free value)))
| 5,850 | Common Lisp | .lisp | 134 | 39.425373 | 78 | 0.683933 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | f169a88a07d5deb9628ac3de3f1f0ad52570b3665ef99edfcca532185c662f51 | 2,463 | [
-1
] |
2,464 | utils.lisp | hoytech_antiweb/bundled/cffi/utils.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; utils.lisp --- Various utilities.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cl-user)
(defpackage #:cffi-utils
(:use #:common-lisp)
(:export #:discard-docstring
#:parse-body
#:with-unique-names
#:once-only
#:mklist
#:make-gensym-list
#:symbolicate
#:let-when
#:bif
#:post-incf
#:single-bit-p))
(in-package #:cffi-utils)
;;;# General Utilities
;;; frodef's, see: http://paste.lisp.org/display/2771#1
(defmacro post-incf (place &optional (delta 1) &environment env)
"Increment PLACE by DELTA and return its previous value."
(multiple-value-bind (dummies vals new setter getter)
(get-setf-expansion place env)
`(let* (,@(mapcar #'list dummies vals) (,(car new) ,getter))
(prog1 ,(car new)
(setq ,(car new) (+ ,(car new) ,delta))
,setter))))
;;; On Lisp, IIRC.
(defun mklist (x)
"Make into list if atom."
(if (listp x) x (list x)))
;;; My own, hah!
(defmacro discard-docstring (body-var)
"Discards the first element of the list in body-var if it's a
string and the only element."
`(when (and (stringp (car ,body-var)) (cdr ,body-var))
(pop ,body-var)))
;;; Parse a body of code, removing an optional documentation string
;;; and declaration forms. Returns the actual body, docstring, and
;;; declarations as three multiple values.
(defun parse-body (body)
(let ((docstring nil)
(declarations nil))
(when (and (stringp (car body)) (cdr body))
(setf docstring (pop body)))
(loop while (and (consp (car body)) (eql (caar body) 'cl:declare))
do (push (pop body) declarations))
(values body docstring (nreverse declarations))))
;;; LET-IF (renamed to BIF) and LET-WHEN taken from KMRCL
(defmacro let-when ((var test-form) &body body)
`(let ((,var ,test-form))
(when ,var ,@body)))
(defmacro bif ((var test-form) if-true &optional if-false)
`(let ((,var ,test-form))
(if ,var ,if-true ,if-false)))
;;; ONCE-ONLY macro taken from PAIP
(defun starts-with (list x)
"Is x a list whose first element is x?"
(and (consp list) (eql (first list) x)))
(defun side-effect-free? (exp)
"Is exp a constant, variable, or function,
or of the form (THE type x) where x is side-effect-free?"
(or (atom exp) (constantp exp)
(starts-with exp 'function)
(and (starts-with exp 'the)
(side-effect-free? (third exp)))))
(defmacro once-only (variables &rest body)
"Returns the code built by BODY. If any of VARIABLES
might have side effects, they are evaluated once and stored
in temporary variables that are then passed to BODY."
(assert (every #'symbolp variables))
(let ((temps nil))
(dotimes (i (length variables)) (push (gensym "ONCE") temps))
`(if (every #'side-effect-free? (list .,variables))
(progn .,body)
(list 'let
,`(list ,@(mapcar #'(lambda (tmp var)
`(list ',tmp ,var))
temps variables))
(let ,(mapcar #'(lambda (var tmp) `(,var ',tmp))
variables temps)
.,body)))))
;;;; The following utils were taken from SBCL's
;;;; src/code/*-extensions.lisp
;;; Automate an idiom often found in macros:
;;; (LET ((FOO (GENSYM "FOO"))
;;; (MAX-INDEX (GENSYM "MAX-INDEX-")))
;;; ...)
;;;
;;; "Good notation eliminates thought." -- Eric Siggia
;;;
;;; Incidentally, this is essentially the same operator which
;;; _On Lisp_ calls WITH-GENSYMS.
(defmacro with-unique-names (symbols &body body)
`(let ,(mapcar (lambda (symbol)
(let* ((symbol-name (symbol-name symbol))
(stem (if (every #'alpha-char-p symbol-name)
symbol-name
(concatenate 'string symbol-name "-"))))
`(,symbol (gensym ,stem))))
symbols)
,@body))
(defun make-gensym-list (n)
"Return a list of N gensyms."
(loop repeat n collect (gensym)))
(defun symbolicate (&rest things)
"Concatenate together the names of some strings and symbols,
producing a symbol in the current package."
(let* ((length (reduce #'+ things
:key (lambda (x) (length (string x)))))
(name (make-array length :element-type 'character)))
(let ((index 0))
(dolist (thing things (values (intern name)))
(let* ((x (string thing))
(len (length x)))
(replace name x :start1 index)
(incf index len))))))
(defun single-bit-p (integer)
"Answer whether INTEGER, which must be an integer, is a single
set twos-complement bit."
(if (<= integer 0)
nil ;infinite set bits for negatives
(loop until (logbitp 0 integer)
do (setf integer (ash integer -1))
finally (return (zerop (ash integer -1))))))
;(defun deprecation-warning (bad-name &optional good-name)
; (warn "using deprecated ~S~@[, should use ~S instead~]"
; bad-name
; good-name))
;;; Anaphoric macros
;(defmacro awhen (test &body body)
; `(let ((it ,test))
; (when it ,@body)))
;(defmacro acond (&rest clauses)
; (if (null clauses)
; `()
; (destructuring-bind ((test &body body) &rest rest) clauses
; (once-only (test)
; `(if ,test
; (let ((it ,test)) (declare (ignorable it)),@body)
; (acond ,@rest))))))
| 6,716 | Common Lisp | .lisp | 165 | 35.2 | 76 | 0.622818 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | beae3cc8ded74ec344a34e0db8607e3cc3e9703096064f3383bdb45009f50aca | 2,464 | [
356079
] |
2,465 | cffi-sbcl.lisp | hoytech_antiweb/bundled/cffi/cffi-sbcl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-sbcl.lisp --- CFFI-SYS implementation for SBCL.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:sb-alien #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; OS/CPU features.
#+darwin cffi-features:darwin
#+(and unix (not win32)) cffi-features:unix
#+win32 cffi-features:windows
#+x86 cffi-features:x86
#+x86-64 cffi-features:x86-64
#+(and ppc (not ppc64)) cffi-features:ppc32
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Basic Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(sb-sys:system-area-pointer-p ptr))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(sb-sys:sap= ptr1 ptr2))
(defun null-pointer ()
"Construct and return a null pointer."
(sb-sys:int-sap 0))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(zerop (sb-sys:sap-int ptr)))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(sb-sys:sap+ ptr offset))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(sb-sys:int-sap address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(sb-sys:sap-int ptr))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(alien-sap (make-alien (unsigned 8) size)))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(free-alien (sap-alien ptr (* (unsigned 8)))))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
;; If the size is constant we can stack-allocate.
(if (constantp size)
(let ((alien-var (gensym "ALIEN")))
`(with-alien ((,alien-var (array (unsigned 8) ,(eval size))))
(let ((,size-var ,(eval size))
(,var (alien-sap ,alien-var)))
(declare (ignorable ,size-var))
,@body)))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var)))))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
(let ((vector-var (gensym "VECTOR")))
`(let ((,vector-var ,vector))
(sb-sys:with-pinned-objects (,vector-var)
(let ((,ptr-var (sb-sys:vector-sap ,vector-var)))
,@body)))))
;;;# Dereferencing
;;; Define the %MEM-REF and %MEM-SET functions, as well as compiler
;;; macros that optimize the case where the type keyword is constant
;;; at compile-time.
(defmacro define-mem-accessors (&body pairs)
`(progn
(defun %mem-ref (ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (,fn ptr offset)))))
(defun %mem-set (value ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (setf (,fn ptr offset) value)))))
(define-compiler-macro %mem-ref
(&whole form ptr type &optional (offset 0))
(if (constantp type)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(,',fn ,ptr ,offset))))
form))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
(once-only (value)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(setf (,',fn ,ptr ,offset)
,value)))))
form))))
(define-mem-accessors
(:char sb-sys:signed-sap-ref-8)
(:unsigned-char sb-sys:sap-ref-8)
(:short sb-sys:signed-sap-ref-16)
(:unsigned-short sb-sys:sap-ref-16)
(:int sb-sys:signed-sap-ref-32)
(:unsigned-int sb-sys:sap-ref-32)
(:long sb-sys:signed-sap-ref-word)
(:unsigned-long sb-sys:sap-ref-word)
(:long-long sb-sys:signed-sap-ref-64)
(:unsigned-long-long sb-sys:sap-ref-64)
(:float sb-sys:sap-ref-single)
(:double sb-sys:sap-ref-double)
(:pointer sb-sys:sap-ref-sap))
;;;# Calling Foreign Functions
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an SB-ALIEN type."
(ecase type-keyword
(:char 'char)
(:unsigned-char 'unsigned-char)
(:short 'short)
(:unsigned-short 'unsigned-short)
(:int 'int)
(:unsigned-int 'unsigned-int)
(:long 'long)
(:unsigned-long 'unsigned-long)
(:long-long 'long-long)
(:unsigned-long-long 'unsigned-long-long)
(:float 'single-float)
(:double 'double-float)
(:pointer 'system-area-pointer)
(:void 'void)))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(/ (sb-alien-internals:alien-type-bits
(sb-alien-internals:parse-alien-type
(convert-foreign-type type-keyword) nil)) 8))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
#+(and darwin ppc (not ppc64))
(case type-keyword
((:double :long-long :unsigned-long-long)
(return-from %foreign-type-alignment 8)))
;; No override necessary for other types...
(/ (sb-alien-internals:alien-type-alignment
(sb-alien-internals:parse-alien-type
(convert-foreign-type type-keyword) nil)) 8))
(defun foreign-funcall-type-and-args (args)
"Return an SB-ALIEN function type for ARGS."
(let ((return-type 'void))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type))
finally (return (values types fargs return-type)))))
(defmacro %%foreign-funcall (name types fargs rettype)
"Internal guts of %FOREIGN-FUNCALL."
`(alien-funcall
(extern-alien ,name (function ,rettype ,@types))
,@fargs))
(defmacro %foreign-funcall (name &rest args)
"Perform a foreign function call, document it more later."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall ,name ,types ,fargs ,rettype)))
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Funcall a pointer to a foreign function."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (function)
`(with-alien ((,function (* (function ,rettype ,@types)) ,ptr))
(alien-funcall ,function ,@fargs)))))
;;;# Callbacks
;;; The *CALLBACKS* hash table contains a direct mapping of CFFI
;;; callback names to SYSTEM-AREA-POINTERs obtained by ALIEN-LAMBDA.
;;; SBCL will maintain the addresses of the callbacks across saved
;;; images, so it is safe to store the pointers directly.
(defvar *callbacks* (make-hash-table))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
`(setf (gethash ',name *callbacks*)
(alien-sap
(sb-alien::alien-lambda ,(convert-foreign-type rettype)
,(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types)
,@body))))
(defun %callback (name)
(or (gethash name *callbacks*)
(error "Undefined callback: ~S" name)))
;;;# Loading and Closing Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library NAME."
(load-shared-object name))
(defun %close-foreign-library (name)
"Closes the foreign library NAME."
(error "%close-foreign-library not implemented on SBCL")
#+nil
(sb-alien::dlclose-or-lose
(find name sb-alien::*shared-objects*
:key #'sb-alien::shared-object-file
:test #'string=)))
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(let-when (address (sb-sys:find-foreign-symbol-address name))
(sb-sys:int-sap address)))
;;;# Finalizers
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(sb-ext:finalize object function))
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(sb-ext:cancel-finalization object))
| 11,663 | Common Lisp | .lisp | 290 | 35.393103 | 73 | 0.66858 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 58d40085503aac6eb2160297265c2bb1178fc8a810cccc9f2edda17617d1bb78 | 2,465 | [
-1
] |
2,466 | cffi-openmcl.lisp | hoytech_antiweb/bundled/cffi/cffi-openmcl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-openmcl.lisp --- CFFI-SYS implementation for OpenMCL.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:ccl #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp ; ccl:pointerp
#:pointer-eq
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%mem-ref
#:%mem-set
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; OS/CPU features.
#+darwinppc-target cffi-features:darwin
#+unix cffi-features:unix
#+ppc32-target cffi-features:ppc32
#+x8664-target cffi-features:x86-64
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common
;;; usage when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(ccl::malloc size))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
;; TODO: Should we make this a dead macptr?
(ccl::free ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let ((,size-var ,size))
(%stack-block ((,var ,size-var))
,@body)))
;;;# Misc. Pointer Operations
(defun null-pointer ()
"Construct and return a null pointer."
(ccl:%null-ptr))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(ccl:%null-ptr-p ptr))
(defun inc-pointer (ptr offset)
"Return a pointer OFFSET bytes past PTR."
(ccl:%inc-ptr ptr offset))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(ccl:%ptr-eql ptr1 ptr2))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(ccl:%int-to-ptr address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(ccl:%ptr-to-int ptr))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes that can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
`(ccl:with-pointer-to-ivector (,ptr-var ,vector)
,@body))
;;;# Dereferencing
;;; Define the %MEM-REF and %MEM-SET functions, as well as compiler
;;; macros that optimize the case where the type keyword is constant
;;; at compile-time.
(defmacro define-mem-accessors (&body pairs)
`(progn
(defun %mem-ref (ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (,fn ptr offset)))))
(defun %mem-set (value ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (setf (,fn ptr offset) value)))))
(define-compiler-macro %mem-ref
(&whole form ptr type &optional (offset 0))
(if (constantp type)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(,',fn ,ptr ,offset))))
form))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
(once-only (value)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(setf (,',fn ,ptr ,offset)
,value)))))
form))))
(define-mem-accessors
(:char %get-signed-byte)
(:unsigned-char %get-unsigned-byte)
(:short %get-signed-word)
(:unsigned-short %get-unsigned-word)
(:int %get-signed-long)
(:unsigned-int %get-unsigned-long)
#+32-bit-target (:long %get-signed-long)
#+64-bit-target (:long ccl::%%get-signed-longlong)
#+32-bit-target (:unsigned-long %get-unsigned-long)
#+64-bit-target (:unsigned-long ccl::%%get-unsigned-longlong)
(:long-long ccl::%get-signed-long-long)
(:unsigned-long-long ccl::%get-unsigned-long-long)
(:float %get-single-float)
(:double %get-double-float)
(:pointer %get-ptr))
;;;# Calling Foreign Functions
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an OpenMCL type."
(ecase type-keyword
(:char :signed-byte)
(:unsigned-char :unsigned-byte)
(:short :signed-short)
(:unsigned-short :unsigned-short)
(:int :signed-int)
(:unsigned-int :unsigned-int)
(:long :signed-long)
(:unsigned-long :unsigned-long)
(:long-long :signed-doubleword)
(:unsigned-long-long :unsigned-doubleword)
(:float :single-float)
(:double :double-float)
(:pointer :address)
(:void :void)))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(/ (ccl::foreign-type-bits
(ccl::parse-foreign-type
(convert-foreign-type type-keyword))) 8))
;; There be dragons here. See the following thread for details:
;; http://clozure.com/pipermail/openmcl-devel/2005-June/002777.html
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(/ (ccl::foreign-type-alignment
(ccl::parse-foreign-type
(convert-foreign-type type-keyword))) 8))
(defun convert-foreign-funcall-types (args)
"Convert foreign types for a call to FOREIGN-FUNCALL."
(loop for (type arg) on args by #'cddr
collect (convert-foreign-type type)
if arg collect arg))
(defun convert-external-name (name)
"Add an underscore to NAME if necessary for the ABI."
#+darwinppc-target (concatenate 'string "_" name)
#-darwinppc-target name)
(defmacro %foreign-funcall (function-name &rest args)
"Perform a foreign function call, document it more later."
`(external-call
,(convert-external-name function-name)
,@(convert-foreign-funcall-types args)))
(defmacro %foreign-funcall-pointer (ptr &rest args)
`(ff-call ,ptr ,@(convert-foreign-funcall-types args)))
;;;# Callbacks
;;; The *CALLBACKS* hash table maps CFFI callback names to OpenMCL "macptr"
;;; entry points. It is safe to store the pointers directly because
;;; OpenMCL will update the address of these pointers when a saved image
;;; is loaded (see CCL::RESTORE-PASCAL-FUNCTIONS).
(defvar *callbacks* (make-hash-table))
;;; Create a package to contain the symbols for callback functions. We
;;; want to redefine callbacks with the same symbol so the internal data
;;; structures are reused.
(defpackage #:cffi-callbacks
(:use))
;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal
;;; callback for NAME.
(defun intern-callback (name)
(intern (format nil "~A::~A" (package-name (symbol-package name))
(symbol-name name))
'#:cffi-callbacks))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
(let ((cb-name (intern-callback name)))
`(progn
(defcallback ,cb-name
(,@(mapcan (lambda (sym type)
(list (convert-foreign-type type) sym))
arg-names arg-types)
,(convert-foreign-type rettype))
,@body)
(setf (gethash ',name *callbacks*) (symbol-value ',cb-name)))))
(defun %callback (name)
(or (gethash name *callbacks*)
(error "Undefined callback: ~S" name)))
;;;# Loading Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library NAME."
(open-shared-library name))
(defun %close-foreign-library (name)
"Close the foreign library NAME."
(close-shared-library name)) ; :completely t ?
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(foreign-symbol-address (convert-external-name name)))
;;;# Finalizers
(defvar *finalizers* (make-hash-table :test 'eq :weak :key)
"Weak hashtable that holds registered finalizers.")
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(ccl:terminate-when-unreachable
object (lambda (obj) (declare (ignore obj)) (funcall function)))
;; store number of finalizers
(if (gethash object *finalizers*)
(incf (gethash object *finalizers*))
(setf (gethash object *finalizers*) 1))
object)
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(let ((count (gethash object *finalizers*)))
(unless (null count)
(dotimes (i count)
(ccl:cancel-terminate-when-unreachable object)))))
| 11,296 | Common Lisp | .lisp | 281 | 35.989324 | 75 | 0.6822 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | ac8d78068605988cccc5d2ca71eb7ab3696c48f84d6fd8f13d5615ca4bd60447 | 2,466 | [
-1
] |
2,467 | early-types.lisp | hoytech_antiweb/bundled/cffi/early-types.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; early-types.lisp --- Low-level foreign type operations.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Early Type Definitions
;;;
;;; This module contains basic operations on foreign types. These
;;; definitions are in a separate file because they may be used in
;;; compiler macros defined later on.
(in-package #:cffi)
;;;# Foreign Types
(defvar *foreign-types* (make-hash-table)
"Hash table of all user-defined foreign types.")
(defun find-type (name)
"Return the foreign type instance for NAME or nil."
(gethash name *foreign-types*))
(defun find-type-or-lose (name)
"Return the foreign type instance for NAME or signal an error."
(or (find-type name)
(error "Undefined foreign type: ~S" name)))
(defun notice-foreign-type (type)
"Inserts TYPE in the *FOREIGN-TYPES* hashtable."
(setf (gethash (name type) *foreign-types*) type)
(name type))
;;;# Parsing Type Specifications
;;;
;;; Type specifications are of the form (type {args}*). The
;;; type parser can specify how its arguments should look like
;;; through a lambda list.
;;;
;;; "type" is a shortcut for "(type)", ie, no args were specified.
;;;
;;; Examples of such types: boolean, (boolean), (boolean :int)
;;; If the boolean type parser specifies the lambda list:
;;; &optional (base-type :int), then all of the above three
;;; type specs would be parsed to an identical type.
;;;
;;; Type parsers, defined with DEFINE-TYPE-SPEC-PARSER should
;;; return a subtype of the foreign-type class.
(defvar *type-parsers* (make-hash-table)
"Hash table of defined type parsers.")
(defun find-type-parser (symbol)
"Return the type parser for SYMBOL."
(gethash symbol *type-parsers*))
(defun (setf find-type-parser) (func symbol)
"Set the type parser for SYMBOL."
(setf (gethash symbol *type-parsers*) func))
(defmacro define-type-spec-parser (symbol lambda-list &body body)
"Define a type parser on SYMBOL and lists whose CAR is SYMBOL."
(when (stringp (car body)) ; discard-docstring
(setq body (cdr body)))
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (find-type-parser ',symbol)
(lambda ,lambda-list ,@body))))
(defun parse-type (type-spec-or-name)
(or (find-type type-spec-or-name)
(let* ((type-spec (mklist type-spec-or-name))
(parser (find-type-parser (car type-spec))))
(if parser
(apply parser (cdr type-spec))
(error "Unknown CFFI type: ~S." type-spec-or-name)))))
;;;# Generic Functions on Types
(defgeneric canonicalize (foreign-type)
(:documentation
"Return the built-in foreign type for FOREIGN-TYPE.
Signals an error if FOREIGN-TYPE is undefined."))
(defgeneric aggregatep (foreign-type)
(:documentation
"Return true if FOREIGN-TYPE is an aggregate type."))
(defgeneric foreign-type-alignment (foreign-type)
(:documentation
"Return the structure alignment in bytes of a foreign type."))
(defgeneric foreign-type-size (foreign-type)
(:documentation
"Return the size in bytes of a foreign type."))
(defgeneric unparse (type-name type-class)
(:documentation
"Unparse FOREIGN-TYPE to a type specification (symbol or list)."))
(defgeneric translate-p (foreign-type)
(:documentation
"Return true if type translators should run on FOREIGN-TYPE."))
;;;# Foreign Types
(defclass foreign-type ()
((name
;; Name of this foreign type, a symbol.
:initform (gensym "ANONYMOUS-CFFI-TYPE")
:initarg :name
:accessor name))
(:documentation "Contains information about a basic foreign type."))
(defmethod print-object ((type foreign-type) stream)
"Print a FOREIGN-TYPE instance to STREAM unreadably."
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S" (name type))))
(defmethod make-load-form ((type foreign-type) &optional env)
"Return the form used to dump types to a FASL file."
(declare (ignore env))
`(parse-type ',(unparse-type type)))
(defun canonicalize-foreign-type (type)
"Convert TYPE to a built-in type by following aliases.
Signals an error if the type cannot be resolved."
(canonicalize (parse-type type)))
(defmethod unparse (name (type foreign-type))
"Default method to unparse TYPE to its name."
(declare (ignore name))
(name type))
(defun unparse-type (type)
"Unparse a foreign type to a symbol or list type spec."
(unparse (name type) type))
(defmethod foreign-type-size (type)
"Return the size in bytes of a foreign type."
(foreign-type-size (parse-type type)))
(defmethod translate-p ((type foreign-type))
"By default, types will be translated."
t)
;;;# Built-In Foreign Types
(defclass foreign-built-in-type (foreign-type)
((type-keyword
;; Keyword in CFFI-SYS representing this type.
:initform (error "A type keyword is required.")
:initarg :type-keyword
:accessor type-keyword))
(:documentation "A built-in foreign type."))
(defmethod canonicalize ((type foreign-built-in-type))
"Return the built-in type keyword for TYPE."
(type-keyword type))
(defmethod aggregatep ((type foreign-built-in-type))
"Returns false, built-in types are never aggregate types."
nil)
(defmethod foreign-type-alignment ((type foreign-built-in-type))
"Return the alignment of a built-in type."
(%foreign-type-alignment (type-keyword type)))
(defmethod foreign-type-size ((type foreign-built-in-type))
"Return the size of a built-in type."
(%foreign-type-size (type-keyword type)))
(defmethod translate-p ((type foreign-built-in-type))
"Built-in types are never translated."
nil)
(defmacro define-built-in-foreign-type (keyword)
"Defines a built-in foreign-type."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(notice-foreign-type
(make-instance 'foreign-built-in-type :name ,keyword
:type-keyword ,keyword))))
;;;# Foreign Pointer Types
(defclass foreign-pointer-type (foreign-type)
((pointer-type
;; Type of object pointed at by this pointer, or nil for an
;; untyped (void) pointer.
:initform nil
:initarg :pointer-type
:accessor pointer-type))
(:default-initargs :name :pointer))
;;; Canonicalize foreign pointers to the primitive :POINTER type.
(defmethod canonicalize ((type foreign-pointer-type))
:pointer)
;;; Pointers are never aggregate types.
(defmethod aggregatep ((type foreign-pointer-type))
nil)
;;; Return the alignment of any foreign pointer type.
(defmethod foreign-type-alignment ((type foreign-pointer-type))
(%foreign-type-alignment :pointer))
;;; Return the size of any foreign pointer type.
(defmethod foreign-type-size ((type foreign-pointer-type))
(%foreign-type-size :pointer))
;;; Foreign pointer types are never translated.
(defmethod translate-p ((type foreign-pointer-type))
nil)
;;; Unparse a foreign pointer type when dumping to a fasl.
(defmethod unparse (name (type foreign-pointer-type))
(declare (ignore name))
(with-slots (pointer-type) type
(if pointer-type
`(:pointer ,(unparse-type pointer-type))
:pointer)))
;;; Print a foreign pointer type unreadably in unparsed form.
(defmethod print-object ((type foreign-pointer-type) stream)
(print-unreadable-object (type stream :type t :identity nil)
(format stream "~S" (unparse-type type))))
;;;# Foreign Typedefs
;;;
;;; We have two classes: foreign-type-alias and foreign-typedef.
;;; The former is a direct super-class of the latter. The only
;;; difference between the two is that foreign-typedef has different
;;; behaviour wrt type translations. (see types.lisp)
(defclass foreign-type-alias (foreign-type)
((actual-type
;; The FOREIGN-TYPE instance this type is an alias for.
:initarg :actual-type
:accessor actual-type)
(translate-p
;; If true, this type should be translated (the default).
:initform t
:initarg :translate-p
:accessor translate-p))
(:documentation "A type that aliases another type."))
(defmethod canonicalize ((type foreign-type-alias))
"Return the built-in type keyword for TYPE."
(canonicalize (actual-type type)))
(defmethod aggregatep ((type foreign-type-alias))
"Return true if TYPE's actual type is aggregate."
(aggregatep (actual-type type)))
(defmethod foreign-type-alignment ((type foreign-type-alias))
"Return the alignment of a foreign typedef."
(foreign-type-alignment (actual-type type)))
(defmethod foreign-type-size ((type foreign-type-alias))
"Return the size in bytes of a foreign typedef."
(foreign-type-size (actual-type type)))
(defclass foreign-typedef (foreign-type-alias)
())
;;; This should probably be an argument to parse-type.
;;; So we'd have: (parse-type foo :follow-typedefs t)
;;; instead of (follow-typedefs (parse-type foo)) ? --luis
(defun follow-typedefs (type)
(if (eq (type-of type) 'foreign-typedef)
(follow-typedefs (actual-type type))
type))
;;;# Structure Type
(defclass foreign-struct-type (foreign-type)
((slots
;; Hash table of slots in this structure, keyed by name.
:initform (make-hash-table)
:initarg :slots
:accessor slots)
(size
;; Cached size in bytes of this structure.
:initarg :size
:accessor size)
(alignment
;; This struct's alignment requirements
:initarg :alignment
:accessor alignment))
(:documentation "Hash table of plists containing slot information."))
(defmethod canonicalize ((type foreign-struct-type))
"Returns :POINTER, since structures can not be passed by value."
:pointer)
(defmethod aggregatep ((type foreign-struct-type))
"Returns true, structure types are aggregate."
t)
(defmethod foreign-type-size ((type foreign-struct-type))
"Return the size in bytes of a foreign structure type."
(size type))
(defmethod foreign-type-alignment ((type foreign-struct-type))
"Return the alignment requirements for this struct."
(alignment type))
;;;# Type Translators
;;;
;;; Type translation is now done with generic functions at runtime.
;;;
;;; The main internal interface to type translation is through the
;;; generic functions TRANSLATE-TYPE-{TO,FROM}-FOREIGN and
;;; FREE-TYPE-TRANSLATED-OBJECT. These should be specialized for
;;; subclasses of FOREIGN-TYPE requiring translation.
;;;
;;; User-defined type translators are defined by specializing
;;; additional methods that are called by the internal methods
;;; specialized on FOREIGN-TYPEDEF. These methods dispatch on the
;;; name of the type.
;;; Translate VALUE to a foreign object of the type represented by
;;; TYPE, which will be a subclass of FOREIGN-TYPE. Returns the
;;; foreign value and an optional second value which will be passed to
;;; FREE-TYPE-TRANSLATED-OBJECT as the PARAM argument.
(defgeneric translate-type-to-foreign (value type)
(:method (value type)
(declare (ignore type))
value))
;;; Translate the foreign object VALUE from the type repsented by
;;; TYPE, which will be a subclass of FOREIGN-TYPE. Returns the
;;; converted Lisp value.
(defgeneric translate-type-from-foreign (value type)
(:method (value type)
(declare (ignore type))
value))
;;; Free an object allocated by TRANSLATE-TYPE-TO-FOREIGN. VALUE is a
;;; foreign object of the type represented by TYPE, which will be a
;;; FOREIGN-TYPE subclass. PARAM, if present, contains the second
;;; value returned by TRANSLATE-TYPE-TO-FOREIGN, and is used to
;;; communicate between the two functions.
(defgeneric free-type-translated-object (value type param)
(:method (value type param)
(declare (ignore value type param))))
;;;## Translations for Typedefs
;;;
;;; By default, the translation methods for type definitions delegate
;;; to the translation methods for the ACTUAL-TYPE of the typedef.
;;;
;;; The user is allowed to intervene in this process by specializing
;;; TRANSLATE-TO-FOREIGN, TRANSLATE-FROM-FOREIGN, and
;;; FREE-TRANSLATED-OBJECT on the name of the typedef.
;;; Exported hook method allowing specific typedefs to define custom
;;; translators to convert VALUE to the foreign type named by NAME.
(defgeneric translate-to-foreign (value name)
(:method (value name)
(declare (ignore name))
value))
;;; Exported hook method allowing specific typedefs to define custom
;;; translators to convert VALUE from the foreign type named by NAME.
(defgeneric translate-from-foreign (value name)
(:method (value name)
(declare (ignore name))
value))
;;; Exported hook method allowing specific typedefs to free objects of
;;; type NAME allocated by TRANSLATE-TO-FOREIGN.
(defgeneric free-translated-object (value name param)
(:method (value name param)
(declare (ignore value name param))))
;;; Default translator to foreign for typedefs. We build a list out
;;; of the second value returned from each translator so we can pass
;;; each parameter to the appropriate free method when freeing the
;;; object.
(defmethod translate-type-to-foreign (value (type foreign-typedef))
(multiple-value-bind (value param)
(translate-to-foreign value (name type))
(multiple-value-bind (new-value new-param)
(translate-type-to-foreign value (actual-type type))
(values new-value (cons param new-param)))))
;;; Default translator from foreign for typedefs.
(defmethod translate-type-from-foreign (value (type foreign-typedef))
(translate-from-foreign
(translate-type-from-foreign value (actual-type type))
(name type)))
;;; Default method for freeing translated foreign typedefs. PARAM
;;; will actually be a list of parameters to pass to each translator
;;; method as returned by TRANSLATE-TYPE-TO-FOREIGN.
(defmethod free-type-translated-object (value (type foreign-typedef) param)
(free-translated-object value (name type) (car param))
(free-type-translated-object value (actual-type type) (cdr param)))
;;;## Macroexpansion Time Translation
;;;
;;; The following expand-* generic functions are similar to their
;;; translate-* counterparts but are usually called at macroexpansion
;;; time. They offer a way to optimize the runtime translators.
;;;
;;; The default methods expand to forms calling the runtime translators
;;; unless TRANSLATE-P returns NIL for the type.
(defun %expand-type-to-foreign-dyn (value var body type)
(with-unique-names (param)
(if (translate-p type)
`(multiple-value-bind (,var ,param)
(translate-type-to-foreign ,value ,type)
(unwind-protect
(progn ,@body)
(free-type-translated-object ,var ,type ,param)))
`(let ((,var ,value))
,@body))))
(defun %expand-type-to-foreign (value type)
(if (translate-p type)
`(values (translate-type-to-foreign ,value ,type))
value))
(defun %expand-type-from-foreign (value type)
(if (translate-p type)
`(translate-type-from-foreign ,value ,type)
`(values ,value)))
;;; This special variable is bound by the various :around methods
;;; below to the respective form generated by the above %EXPAND-*
;;; functions. This way, an expander can "bail out" by calling the
;;; next method. All 6 of the below-defined GFs have a default method
;;; that simply answers the rtf bound by the default :around method.
(defvar *runtime-translator-form*)
(defun specializedp (gf &rest args)
"Answer whether GF has more than one applicable method for ARGS."
(typep (compute-applicable-methods gf args) '(cons t cons)))
(defgeneric expand-type-to-foreign-dyn (value var body type)
(:method :around (value var body type)
(let ((*runtime-translator-form*
(%expand-type-to-foreign-dyn value var body type)))
(call-next-method)))
(:method (value var body type)
;; If COMPUTE-APPLICABLE-METHODS only finds one method it's
;; the default one meaning that there is no to-foreign expander
;; therefore we return *RUNTIME-TRANSLATOR-FORM* instead.
(if (specializedp #'expand-type-to-foreign value type)
`(let ((,var ,(expand-type-to-foreign value type)))
,@body)
*runtime-translator-form*)))
(defgeneric expand-type-to-foreign (value type)
(:method :around (value type)
(let ((*runtime-translator-form* (%expand-type-to-foreign value type)))
(call-next-method)))
(:method (value type)
(declare (ignore value type))
*runtime-translator-form*))
(defgeneric expand-type-from-foreign (value type)
(:method :around (value type)
(let ((*runtime-translator-form* (%expand-type-from-foreign value type)))
(call-next-method)))
(:method (value type)
(declare (ignore value type))
*runtime-translator-form*))
(defgeneric expand-to-foreign-dyn (value var body type)
(:method (value var body type)
(declare (ignore value var body type))
*runtime-translator-form*))
(defgeneric expand-to-foreign (value type)
(:method (value type)
(declare (ignore value type))
*runtime-translator-form*))
(defgeneric expand-from-foreign (value type)
(:method (value type)
(declare (ignore value type))
*runtime-translator-form*))
(defmethod expand-type-to-foreign-dyn (value var body (type foreign-typedef))
(if (or (specializedp #'expand-to-foreign-dyn
value var body (name type))
(not (specializedp #'expand-to-foreign value (name type))))
(expand-to-foreign-dyn value var body (name type))
;; If there is to-foreign _expansion_, but not to-foreign-dyn
;; expansion, we use that.
`(let ((,var ,(expand-type-to-foreign value type)))
,@body)))
(defmethod expand-type-to-foreign (value (type foreign-typedef))
(expand-to-foreign value (name type)))
(defmethod expand-type-from-foreign (value (type foreign-typedef))
(expand-from-foreign value (name type)))
;;; User interface for converting values from/to foreign using the
;;; type translators. Something doesn't feel right about this, makes
;;; me want to just export PARSE-TYPE...
(defun convert-to-foreign (value type)
(translate-type-to-foreign value (parse-type type)))
(define-compiler-macro convert-to-foreign (value type)
(if (constantp type)
(expand-type-to-foreign value (parse-type (eval type)))
`(translate-type-to-foreign ,value (parse-type ,type))))
(defun convert-from-foreign (value type)
(translate-type-from-foreign value (parse-type type)))
(define-compiler-macro convert-from-foreign (value type)
(if (constantp type)
(expand-type-from-foreign value (parse-type (eval type)))
`(translate-type-from-foreign ,value (parse-type ,type))))
(defun free-converted-object (value type param)
(free-type-translated-object value type param))
| 19,738 | Common Lisp | .lisp | 452 | 40.411504 | 77 | 0.72778 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 0695e6750f51a848b97d2463b6cd7fbe9c6e1b0ca1aa9b1427ce486229d99c0a | 2,467 | [
-1
] |
2,468 | load.lisp | hoytech_antiweb/bundled/cffi/load.lisp | ;; Antiweb (C) Doug Hoyte
;; CFFI loader modeled after load.lisp from CL-PPCRE
(in-package :cl-user)
(let ((files '("utils"
"features"
#+sbcl "cffi-sbcl"
#+cmu "cffi-cmucl"
#+clisp "cffi-clisp"
#+ccl "cffi-openmcl"
"package"
"libraries"
"early-types"
"types"
"enum"
"strings"
"functions"
"foreign-vars"))
(base-directory
(make-pathname :name nil :type nil :version nil
:defaults (parse-namestring *load-truename*)))
must-compile)
(with-compilation-unit ()
(dolist (file files)
(let ((pathname (make-pathname :name file :type "lisp" :version nil
:defaults base-directory)))
(let ((compiled-pathname (compile-file-pathname pathname)))
(unless (and (not must-compile)
(probe-file compiled-pathname)
(< (file-write-date pathname)
(file-write-date compiled-pathname)))
(setq must-compile t)
(compile-file pathname))
(setq pathname compiled-pathname))
(load pathname)))))
| 1,287 | Common Lisp | .lisp | 34 | 24.470588 | 73 | 0.5004 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 82bd5fa02446ca7903e8bc3d439d630bcabb2536a17db9688c286ae4138570c2 | 2,468 | [
-1
] |
2,469 | cffi-cmucl.lisp | hoytech_antiweb/bundled/cffi/cffi-cmucl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-sbcl.lisp --- CFFI-SYS implementation for CMU CL.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:alien #:c-call #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; OS/CPU features.
#+darwin cffi-features:darwin
#+unix cffi-features:unix
#+x86 cffi-features:x86
#+(and ppc (not ppc64)) cffi-features:ppc32
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Basic Pointer Operations
(declaim (inline pointerp))
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(sys:system-area-pointer-p ptr))
(declaim (inline pointer-eq))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(sys:sap= ptr1 ptr2))
(declaim (inline null-pointer))
(defun null-pointer ()
"Construct and return a null pointer."
(sys:int-sap 0))
(declaim (inline null-pointer-p))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(zerop (sys:sap-int ptr)))
(declaim (inline inc-pointer))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(sys:sap+ ptr offset))
(declaim (inline make-pointer))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(sys:int-sap address))
(declaim (inline pointer-address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(sys:sap-int ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
;; If the size is constant we can stack-allocate.
(if (constantp size)
(let ((alien-var (gensym "ALIEN")))
`(with-alien ((,alien-var (array (unsigned 8) ,(eval size))))
(let ((,size-var ,(eval size))
(,var (alien-sap ,alien-var)))
(declare (ignorable ,size-var))
,@body)))
`(let* ((,size-var ,size)
(,var (%foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var)))))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(declare (type (unsigned-byte 32) size))
(alien-funcall
(extern-alien
"malloc"
(function system-area-pointer unsigned))
size))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(declare (type system-area-pointer ptr))
(alien-funcall
(extern-alien
"free"
(function (values) system-area-pointer))
ptr))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
(defun make-shareable-byte-vector (size)
"Create a Lisp vector of SIZE bytes that can passed to
WITH-POINTER-TO-VECTOR-DATA."
(make-array size :element-type '(unsigned-byte 8)))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a foreign pointer to the data in VECTOR."
`(sys:without-gcing
(let ((,ptr-var (sys:vector-sap ,vector)))
,@body)))
;;;# Dereferencing
;;; Define the %MEM-REF and %MEM-SET functions, as well as compiler
;;; macros that optimize the case where the type keyword is constant
;;; at compile-time.
(defmacro define-mem-accessors (&body pairs)
`(progn
(defun %mem-ref (ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (,fn ptr offset)))))
(defun %mem-set (value ptr type &optional (offset 0))
(ecase type
,@(loop for (keyword fn) in pairs
collect `(,keyword (setf (,fn ptr offset) value)))))
(define-compiler-macro %mem-ref
(&whole form ptr type &optional (offset 0))
(if (constantp type)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(,',fn ,ptr ,offset))))
form))
(define-compiler-macro %mem-set
(&whole form value ptr type &optional (offset 0))
(if (constantp type)
(once-only (value)
(ecase (eval type)
,@(loop for (keyword fn) in pairs
collect `(,keyword `(setf (,',fn ,ptr ,offset)
,value)))))
form))))
(define-mem-accessors
(:char sys:signed-sap-ref-8)
(:unsigned-char sys:sap-ref-8)
(:short sys:signed-sap-ref-16)
(:unsigned-short sys:sap-ref-16)
(:int sys:signed-sap-ref-32)
(:unsigned-int sys:sap-ref-32)
(:long sys:signed-sap-ref-32)
(:unsigned-long sys:sap-ref-32)
(:long-long sys:signed-sap-ref-64)
(:unsigned-long-long sys:sap-ref-64)
(:float sys:sap-ref-single)
(:double sys:sap-ref-double)
(:pointer sys:sap-ref-sap))
;;;# Calling Foreign Functions
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to an ALIEN type."
(ecase type-keyword
(:char 'char)
(:unsigned-char 'unsigned-char)
(:short 'short)
(:unsigned-short 'unsigned-short)
(:int 'int)
(:unsigned-int 'unsigned-int)
(:long 'long)
(:unsigned-long 'unsigned-long)
(:long-long '(signed 64))
(:unsigned-long-long '(unsigned 64))
(:float 'single-float)
(:double 'double-float)
(:pointer 'system-area-pointer)
(:void 'void)))
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(/ (alien-internals:alien-type-bits
(alien-internals:parse-alien-type
(convert-foreign-type type-keyword))) 8))
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(/ (alien-internals:alien-type-alignment
(alien-internals:parse-alien-type
(convert-foreign-type type-keyword))) 8))
(defun foreign-funcall-type-and-args (args)
"Return an ALIEN function type for ARGS."
(let ((return-type nil))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type))
finally (return (values types fargs return-type)))))
(defmacro %%foreign-funcall (name types fargs rettype)
"Internal guts of %FOREIGN-FUNCALL."
`(alien-funcall
(extern-alien ,name (function ,rettype ,@types))
,@fargs))
(defmacro %foreign-funcall (name &rest args)
"Perform a foreign function call, document it more later."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(%%foreign-funcall ,name ,types ,fargs ,rettype)))
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Funcall a pointer to a foreign function."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (function)
`(with-alien ((,function (* (function ,rettype ,@types)) ,ptr))
(alien-funcall ,function ,@fargs)))))
;;;# Callbacks
(defvar *callbacks* (make-hash-table))
;;; Create a package to contain the symbols for callback functions. We
;;; want to redefine callbacks with the same symbol so the internal data
;;; structures are reused.
(defpackage #:cffi-callbacks
(:use))
;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal
;;; callback for NAME.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun intern-callback (name)
(intern (format nil "~A::~A" (package-name (symbol-package name))
(symbol-name name))
'#:cffi-callbacks)))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
(let ((cb-name (intern-callback name)))
`(progn
(def-callback ,cb-name
(,(convert-foreign-type rettype)
,@(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types))
,@body)
(setf (gethash ',name *callbacks*) (callback ,cb-name)))))
(defun %callback (name)
(multiple-value-bind (pointer winp)
(gethash name *callbacks*)
(unless winp
(error "Undefined callback: ~S" name))
pointer))
;;;# Loading and Closing Foreign Libraries
;;; Work-around for compiling ffi code without loading the
;;; respective library at compile-time.
(setf c::top-level-lambda-max 0)
(defun %load-foreign-library (name)
"Load the foreign library NAME."
(sys::load-object-file name))
;;; XXX: doesn't work on Darwin; does not check for errors. I suppose we'd
;;; want something like SBCL's dlclose-or-lose in foreign-load.lisp:66
(defun %close-foreign-library (name)
"Closes the foreign library NAME."
(let ((lib (find name sys::*global-table* :key #'cdr :test #'string=)))
(sys::dlclose (car lib))
(setf (car lib) (sys:int-sap 0))))
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(let ((address (sys:alternate-get-global-address
(vm:extern-alien-name name))))
(if (zerop address)
nil
(sys:int-sap address))))
;;;# Finalizers
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(ext:finalize object function))
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(ext:cancel-finalization object))
| 12,261 | Common Lisp | .lisp | 316 | 34.18038 | 75 | 0.671402 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 44a54a0f6efde53977fa125469535768adb8fdb020196c7ecc5d6fec9d92303a | 2,469 | [
-1
] |
2,470 | features.lisp | hoytech_antiweb/bundled/cffi/features.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; features.lisp --- CFFI-specific features.
;;;
;;; Copyright (C) 2006, Luis Oliveira <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cl-user)
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :cffi *features*))
(defpackage #:cffi-features
(:export
;; Features related to the CFFI-SYS backend.
;; Why no-*? This reflects the hope that these symbols will
;; go away completely and all lisps support long-long's and
;; the foreign-funcall primitive.
#:no-long-long
#:no-foreign-funcall
#:no-finalizers
;; Only SCL support long-double...
;;#:no-long-double
;; Features related to the operating system.
;; Currently only these are pushed to *features*, more should be added.
#:darwin
#:unix
#:windows
;; Features related to the processor.
;; Currently only these are pushed to *features*, more should be added.
#:ppc32
#:x86
#:x86-64
))
| 2,074 | Common Lisp | .lisp | 51 | 38.235294 | 74 | 0.725422 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | e77534c328157584739358945e27ca0102fba602faac24011ea7a5a5ba9ef681 | 2,470 | [
-1
] |
2,471 | cffi-gcl.lisp | hoytech_antiweb/bundled/cffi/cffi-gcl.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-gcl.lisp --- CFFI-SYS implementation for GNU Common Lisp.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;; GCL specific notes:
;;;
;;; On ELF systems, a library can be loaded with the help of this:
;;; http://www.copyleft.de/lisp/gcl-elf-loader.html
;;;
;;; Another way is to link the library when creating a new image:
;;; (compiler::link nil "new_image" "" "-lfoo")
;;;
;;; As GCL's FFI is not dynamic, CFFI declarations will only work
;;; after compiled and loaded.
;;; *** this port is broken ***
;;; gcl doesn't compile the rest of CFFI anyway..
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:%foreign-alloc
#:foreign-free
#:with-foreign-ptr
#:null-ptr
#:null-ptr-p
#:inc-ptr
#:%mem-ref
#:%mem-set
#:%foreign-funcall
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
;#:make-shareable-byte-vector
;#:with-pointer-to-vector-data
#:foreign-var-ptr
#:make-callback))
(in-package #:cffi-sys)
;;;# Mis-*features*
(eval-when (:compile-toplevel :load-toplevel :execute)
(pushnew :cffi/no-foreign-funcall *features*))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common
;;; usage when the memory has dynamic extent.
(defentry %foreign-alloc (int) (int "malloc"))
;(defun foreign-alloc (size)
; "Allocate SIZE bytes on the heap and return a pointer."
; (%foreign-alloc size))
(defentry foreign-free (int) (void "free"))
;(defun foreign-free (ptr)
; "Free a PTR allocated by FOREIGN-ALLOC."
; (%free ptr))
(defmacro with-foreign-ptr ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let* ((,size-var ,size)
(,var (foreign-alloc ,size-var)))
(unwind-protect
(progn ,@body)
(foreign-free ,var))))
;;;# Misc. Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(integerp ptr))
(defun null-ptr ()
"Construct and return a null pointer."
0)
(defun null-ptr-p (ptr)
"Return true if PTR is a null pointer."
(= ptr 0))
(defun inc-ptr (ptr offset)
"Return a pointer OFFSET bytes past PTR."
(+ ptr offset))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
;(defun make-shareable-byte-vector (size)
; "Create a Lisp vector of SIZE bytes that can passed to
;WITH-POINTER-TO-VECTOR-DATA."
; (make-array size :element-type '(unsigned-byte 8)))
;(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
; "Bind PTR-VAR to a foreign pointer to the data in VECTOR."
; `(ccl:with-pointer-to-ivector (,ptr-var ,vector)
; ,@body))
;;;# Dereferencing
(defmacro define-mem-ref/set (type gcl-type &optional c-name)
(unless c-name
(setq c-name (substitute #\_ #\Space type)))
(let ((ref-fn (concatenate 'string "ref_" c-name))
(set-fn (concatenate 'string "set_" c-name)))
`(progn
;; ref
(defcfun ,(format nil "~A ~A(~A *ptr)" type ref-fn type)
0 "return *ptr;")
(defentry ,(intern (string-upcase (substitute #\- #\_ ref-fn)))
(int) (,gcl-type ,ref-fn))
;; set
(defcfun ,(format nil "void ~A(~A *ptr, ~A value)" set-fn type type)
0 "*ptr = value;")
(defentry ,(intern (string-upcase (substitute #\- #\_ set-fn)))
(int ,gcl-type) (void ,set-fn)))))
(define-mem-ref/set "char" char)
(define-mem-ref/set "unsigned char" char)
(define-mem-ref/set "short" int)
(define-mem-ref/set "unsigned short" int)
(define-mem-ref/set "int" int)
(define-mem-ref/set "unsigned int" int)
(define-mem-ref/set "long" int)
(define-mem-ref/set "unsigned long" int)
(define-mem-ref/set "float" float)
(define-mem-ref/set "double" double)
(define-mem-ref/set "void *" int "ptr")
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(incf ptr offset))
(ecase type
(:char (ref-char ptr))
(:unsigned-char (ref-unsigned-char ptr))
(:short (ref-short ptr))
(:unsigned-short (ref-unsigned-short ptr))
(:int (ref-int ptr))
(:unsigned-int (ref-unsigned-int ptr))
(:long (ref-long ptr))
(:unsigned-long (ref-unsigned-long ptr))
(:float (ref-float ptr))
(:double (ref-double ptr))
(:pointer (ref-ptr ptr))))
(defun %mem-set (value ptr type &optional (offset 0))
(unless (zerop offset)
(incf ptr offset))
(ecase type
(:char (set-char ptr value))
(:unsigned-char (set-unsigned-char ptr value))
(:short (set-short ptr value))
(:unsigned-short (set-unsigned-short ptr value))
(:int (set-int ptr value))
(:unsigned-int (set-unsigned-int ptr value))
(:long (set-long ptr value))
(:unsigned-long (set-unsigned-long ptr value))
(:float (set-float ptr value))
(:double (set-double ptr value))
(:pointer (set-ptr ptr value)))
value)
;;;# Calling Foreign Functions
;; TODO: figure out if these type conversions make any sense...
(defun convert-foreign-type (type-keyword)
"Convert a CFFI type keyword to a GCL type."
(ecase type-keyword
(:char 'char)
(:unsigned-char 'char)
(:short 'int)
(:unsigned-short 'int)
(:int 'int)
(:unsigned-int 'int)
(:long 'int)
(:unsigned-long 'int)
(:float 'float)
(:double 'double)
(:pointer 'int)
(:void 'void)))
(defparameter +cffi-types+
'(:char :unsigned-char :short :unsigned-short :int :unsigned-int
:long :unsigned-long :float :double :pointer))
(defcfun "int size_of(int type)" 0
"switch (type) {
case 0: return sizeof(char);
case 1: return sizeof(unsigned char);
case 2: return sizeof(short);
case 3: return sizeof(unsigned short);
case 4: return sizeof(int);
case 5: return sizeof(unsigned int);
case 6: return sizeof(long);
case 7: return sizeof(unsigned long);
case 8: return sizeof(float);
case 9: return sizeof(double);
case 10: return sizeof(void *);
default: return -1;
}")
(defentry size-of (int) (int "size_of"))
;; TODO: all this is doable inside the defcfun; figure that out..
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(size-of (position type-keyword +cffi-types+)))
(defcfun "int align_of(int type)" 0
"switch (type) {
case 0: return __alignof__(char);
case 1: return __alignof__(unsigned char);
case 2: return __alignof__(short);
case 3: return __alignof__(unsigned short);
case 4: return __alignof__(int);
case 5: return __alignof__(unsigned int);
case 6: return __alignof__(long);
case 7: return __alignof__(unsigned long);
case 8: return __alignof__(float);
case 9: return __alignof__(double);
case 10: return __alignof__(void *);
default: return -1;
}")
(defentry align-of (int) (int "align_of"))
;; TODO: like %foreign-type-size
(defun %foreign-type-alignment (type-keyword)
"Return the alignment in bytes of a foreign type."
(align-of (position type-keyword +cffi-types+)))
#+ignore
(defun convert-external-name (name)
"Add an underscore to NAME if necessary for the ABI."
#+darwinppc-target (concatenate 'string "_" name)
#-darwinppc-target name)
(defmacro %foreign-funcall (function-name &rest args)
"Perform a foreign function all, document it more later."
`(format t "~&;; Calling ~A with args ~S.~%" ,name ',args))
(defun defcfun-helper-forms (name rettype args types)
"Return 2 values for DEFCFUN. A prelude form and a caller form."
(let ((ff-name (intern (format nil "%foreign-function/TildeA:~A" name))))
(values
`(defentry ,ff-name ,(mapcar #'convert-foreign-type types)
(,(convert-foreign-type rettype) ,name))
`(,ff-name ,@args))))
;;;# Callbacks
;;; XXX unimplemented
(defmacro make-callback (name rettype arg-names arg-types body-form)
0)
;;;# Loading Foreign Libraries
(defun %load-foreign-library (name)
"_Won't_ load the foreign library NAME."
(declare (ignore name)))
;;;# Foreign Globals
;;; XXX unimplemented
(defmacro foreign-var-ptr (name)
"Return a pointer pointing to the foreign symbol NAME."
0)
| 10,289 | Common Lisp | .lisp | 268 | 35.048507 | 75 | 0.663725 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 978afc7d03b527764d74f92e16d840293bd6b7811f057e4763309a4a4dd63f57 | 2,471 | [
-1
] |
2,472 | functions.lisp | hoytech_antiweb/bundled/cffi/functions.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; functions.lisp --- High-level interface to foreign functions.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Calling Foreign Functions
;;;
;;; FOREIGN-FUNCALL is the main primitive for calling foreign
;;; functions. It converts each argument based on the installed
;;; translators for its type, then passes the resulting list to
;;; CFFI-SYS:%FOREIGN-FUNCALL.
;;;
;;; For implementation-specific reasons, DEFCFUN doesn't use
;;; FOREIGN-FUNCALL directly and might use something else
;;; (passed to TRANSLATE-OBJECTS as the CALL argument) instead
;;; of CFFI-SYS:%FOREIGN-FUNCALL to call the foreign-function.
(defun translate-objects (syms args types rettype call-form)
"Helper function for FOREIGN-FUNCALL and DEFCFUN."
(if (null args)
(expand-type-from-foreign call-form (parse-type rettype))
(expand-type-to-foreign-dyn
(car args) (car syms)
(list (translate-objects (cdr syms) (cdr args)
(cdr types) rettype call-form))
(parse-type (car types)))))
(defun parse-args-and-types (args)
"Returns 4 values. Types, canonicalized types, args and return type."
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect type into types
and collect (canonicalize-foreign-type type) into ctypes
and collect arg into fargs
else do (setf return-type type)
finally (return (values types ctypes fargs return-type)))))
(defmacro foreign-funcall (name-or-pointer &rest args)
"Wrapper around %FOREIGN-FUNCALL(-POINTER) that translates its arguments."
(multiple-value-bind (types ctypes fargs rettype)
(parse-args-and-types args)
(let ((syms (make-gensym-list (length fargs))))
(translate-objects
syms fargs types rettype
`(,(if (stringp name-or-pointer)
'%foreign-funcall
'%foreign-funcall-pointer)
,name-or-pointer ,@(mapcan #'list ctypes syms)
,(canonicalize-foreign-type rettype))))))
(defun promote-varargs-type (builtin-type)
"Default argument promotions."
(case builtin-type
(:float :double)
((:char :short) :int)
((:unsigned-char :unsigned-short) :unsigned-int)
(t builtin-type)))
;;; ATM, the only difference between this macro and FOREIGN-FUNCALL is that
;;; it does argument promotion for that variadic argument. This could be useful
;;; to call an hypothetical %foreign-funcall-varargs on some hypothetical lisp
;;; on an hypothetical platform that has different calling conventions for
;;; varargs functions. :-)
(defmacro foreign-funcall-varargs (name-or-pointer fixed-args &rest varargs)
"Wrapper around %FOREIGN-FUNCALL(-POINTER) that translates its arguments
and does type promotion for the variadic arguments."
(multiple-value-bind (fixed-types fixed-ctypes fixed-fargs)
(parse-args-and-types fixed-args)
(multiple-value-bind (varargs-types varargs-ctypes varargs-fargs rettype)
(parse-args-and-types varargs)
(let ((fixed-syms (make-gensym-list (length fixed-fargs)))
(varargs-syms (make-gensym-list (length varargs-fargs))))
(translate-objects
(append fixed-syms varargs-syms) (append fixed-fargs varargs-fargs)
(append fixed-types varargs-types) rettype
`(,(if (stringp name-or-pointer)
'%foreign-funcall
'%foreign-funcall-pointer)
,name-or-pointer
,@(mapcan #'list
(nconc fixed-ctypes
(mapcar #'promote-varargs-type varargs-ctypes))
(append fixed-syms
(loop for sym in varargs-syms
and type in varargs-ctypes
if (eq type :float)
collect `(float ,sym 1.0d0)
else collect sym)))
,(canonicalize-foreign-type rettype)))))))
;;;# Defining Foreign Functions
;;;
;;; The DEFCFUN macro provides a declarative interface for defining
;;; Lisp functions that call foreign functions.
(defun lisp-function-name (name)
"Return the Lisp function name for foreign function NAME."
(etypecase name
(list (second name))
(string (intern (canonicalize-symbol-name-case (substitute #\- #\_ name))))
(symbol name)))
(defun foreign-function-name (name)
"Return the foreign function name of NAME."
(etypecase name
(list (first name))
(string name)
(symbol (substitute #\_ #\- (string-downcase (symbol-name name))))))
;; If cffi-sys doesn't provide a defcfun-helper-forms,
;; we define one that uses %foreign-funcall.
(eval-when (:compile-toplevel :load-toplevel :execute)
(unless (fboundp 'defcfun-helper-forms)
(defun defcfun-helper-forms (name lisp-name rettype args types)
(declare (ignore lisp-name))
(values
'()
`(%foreign-funcall ,name ,@(mapcan #'list types args) ,rettype)))))
(defun %defcfun (lisp-name foreign-name return-type args)
(let ((arg-names (mapcar #'car args))
(arg-types (mapcar #'cadr args))
(syms (make-gensym-list (length args))))
(multiple-value-bind (prelude caller)
(defcfun-helper-forms
foreign-name lisp-name (canonicalize-foreign-type return-type)
syms (mapcar #'canonicalize-foreign-type arg-types))
`(progn
,prelude
(defun ,lisp-name ,arg-names
,(translate-objects
syms arg-names arg-types return-type caller))))))
(defun %defcfun-varargs (lisp-name foreign-name return-type args)
(with-unique-names (varargs)
(let ((arg-names (mapcar #'car args)))
`(defmacro ,lisp-name (,@arg-names &rest ,varargs)
`(foreign-funcall-varargs
,',foreign-name
,,`(list ,@(loop for (name type) in args
collect `',type collect name))
,@,varargs
,',return-type)))))
;;; If we find a &REST token at the end of ARGS, it's a varargs function
;;; therefore we define a lisp macro using %DEFCFUN-VARARGS instead of a
;;; lisp macro with %DEFCFUN as we would otherwise do.
(defmacro defcfun (name return-type &body args)
"Defines a Lisp function that calls a foreign function."
(discard-docstring args)
(let ((lisp-name (lisp-function-name name))
(foreign-name (foreign-function-name name)))
(if (eq (car (last args)) '&rest) ; probably should use STRING=
(%defcfun-varargs lisp-name foreign-name return-type (butlast args))
(%defcfun lisp-name foreign-name return-type args))))
;;;# Defining Callbacks
(defun inverse-translate-objects (args types declarations rettype call)
`(let (,@(loop for arg in args and type in types
collect (list arg (expand-type-from-foreign
arg (parse-type type)))))
,@declarations
,(expand-type-to-foreign call (parse-type rettype))))
(defmacro defcallback (name return-type args &body body)
(multiple-value-bind (body docstring declarations)
(parse-body body)
(declare (ignore docstring))
(let ((arg-names (mapcar #'car args))
(arg-types (mapcar #'cadr args)))
`(progn
(%defcallback ,name ,(canonicalize-foreign-type return-type)
,arg-names ,(mapcar #'canonicalize-foreign-type arg-types)
,(inverse-translate-objects
arg-names arg-types declarations return-type
`(block ,name ,@body)))
',name))))
(declaim (inline get-callback))
(defun get-callback (symbol)
(%callback symbol))
(defmacro callback (name)
`(%callback ',name))
| 8,878 | Common Lisp | .lisp | 190 | 39.926316 | 79 | 0.66732 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 940fdc0337bc6a2cdbe78721b6f3fe5c8dad09e8bc0b9c58de40ffb0e265687c | 2,472 | [
-1
] |
2,473 | libraries.lisp | hoytech_antiweb/bundled/cffi/libraries.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; libraries.lisp --- Finding and loading foreign libraries.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;; Copyright (C) 2006, Luis Oliveira <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
(in-package #:cffi)
;;;# Finding Foreign Libraries
;;;
;;; We offer two ways for the user of a CFFI library to define
;;; his/her own library directories: *FOREIGN-LIBRARY-DIRECTORIES*
;;; for regular libraries and *DARWIN-FRAMEWORK-DIRECTORIES* for
;;; Darwin frameworks.
;;;
;;; These two special variables behave similarly to
;;; ASDF:*CENTRAL-REGISTRY* as its arguments are evaluated before
;;; being used. We used our MINI-EVAL instead of the full-blown EVAL
;;; though.
;;;
;;; Only after failing to find a library through the normal ways
;;; (eg: on Linux LD_LIBRARY_PATH, /etc/ld.so.cache, /usr/lib/, /lib)
;;; do we try to find the library ourselves.
(defvar *foreign-library-directories* '()
"List onto which user-defined library paths can be pushed.")
(defvar *darwin-framework-directories*
'((merge-pathnames #p"Library/Frameworks/" (user-homedir-pathname))
#p"/Library/Frameworks/"
#p"/System/Library/Frameworks/")
"List of directories where Frameworks are searched for.")
(defun mini-eval (form)
"Simple EVAL-like function to evaluate the elements of
*FOREIGN-LIBRARY-DIRECTORIES* and *DARWIN-FRAMEWORK-DIRECTORIES*."
(typecase form
(cons (apply (car form) (mapcar #'mini-eval (cdr form))))
(symbol (symbol-value form))
(t form)))
(defun find-file (path directories)
"Searches for PATH in a list of DIRECTORIES and returns the first it finds."
(some (lambda (directory) (probe-file (merge-pathnames path directory)))
directories))
(defun find-darwin-framework (framework-name)
"Searches for FRAMEWORK-NAME in *DARWIN-FRAMEWORK-DIRECTORIES*."
(dolist (framework-directory *darwin-framework-directories*)
(let ((path (make-pathname
:name framework-name
:directory
(append (pathname-directory (mini-eval framework-directory))
(list (format nil "~A.framework" framework-name))))))
(when (probe-file path)
(return-from find-darwin-framework path)))))
;;;# Defining Foreign Libraries
;;;
;;; Foreign libraries can be defined using the
;;; DEFINE-FOREIGN-LIBRARY macro. Example usage:
;;;
;;; (define-foreign-library opengl
;;; (:darwin (:framework "OpenGL"))
;;; (:unix (:alternatives "libGL.so" "libGL.so.1"
;;; #p"/myhome/mylibGL.so"))
;;; (:windows "opengl32.dll")
;;; ;; a hypothetical example of a particular platform
;;; ;; where the OpenGL library is split in two.
;;; ((:and :some-system :some-cpu) "libGL-support.lib" "libGL-main.lib")
;;; ;; if no other clauses apply, this one will and a type will be
;;; ;; automagically appended to the name passed to :default
;;; (t (:default "libGL")))
;;;
;;; This information is stored in the *FOREIGN-LIBRARIES* hashtable
;;; and when the library is loaded through LOAD-FOREIGN-LIBRARY (usually
;;; indirectly through the USE-FOREIGN-LIBRARY macro) the first clause
;;; that returns true when passed to CFFI-FEATURE-P is processed.
(defvar *foreign-libraries* (make-hash-table :test 'eq)
"Hashtable of defined libraries.")
(defun get-foreign-library (name)
"Look up a library by NAME, signalling an error if not found."
(or (gethash name *foreign-libraries*)
(error "Undefined foreign library: ~S" name)))
(defun (setf get-foreign-library) (value name)
(setf (gethash name *foreign-libraries*) value))
(defmacro define-foreign-library (name &body pairs)
"Defines a foreign library NAME that can be posteriorly used with
the USE-FOREIGN-LIBRARY macro."
`(progn (setf (get-foreign-library ',name) ',pairs)
',name))
(defun cffi-feature-p (feature-expression)
"Matches a FEATURE-EXPRESSION against the symbols in *FEATURES*
that belong to the CFFI-FEATURES package only."
(when (eql feature-expression t)
(return-from cffi-feature-p t))
(let ((features-package (find-package '#:cffi-features)))
(flet ((cffi-feature-eq (name feature-symbol)
(and (eq (symbol-package feature-symbol) features-package)
(string= name (symbol-name feature-symbol)))))
(etypecase feature-expression
(symbol
(not (null (member (symbol-name feature-expression) *features*
:test #'cffi-feature-eq))))
(cons
(ecase (first feature-expression)
(:and (every #'cffi-feature-p (rest feature-expression)))
(:or (some #'cffi-feature-p (rest feature-expression)))
(:not (not (cffi-feature-p (cadr feature-expression))))))))))
;;;# LOAD-FOREIGN-LIBRARY-ERROR condition
;;;
;;; The various helper functions that load foreign libraries
;;; can signal this error when something goes wrong. We ignore
;;; the host's error. We should probably reuse its error message
;;; but they're usually meaningless.
(define-condition load-foreign-library-error (error)
((text :initarg :text :reader text))
(:report (lambda (condition stream)
(write-string (text condition) stream))))
(defun read-new-value ()
(format t "~&Enter a new value (unevaluated): ")
(force-output)
(read))
;;; The helper library loading functions will use this function
;;; to signal a LOAD-FOREIGN-LIBRARY-ERROR and offer the user a
;;; couple of restarts.
(defun handle-load-foreign-library-error (argument control &rest arguments)
(restart-case (error 'load-foreign-library-error
:text (format nil "~?" control arguments))
(retry ()
:report "Try loading the foreign library again."
(load-foreign-library argument))
(use-value (new-library)
:report "Use another library instead."
:interactive read-new-value
(load-foreign-library new-library))))
;;;# Loading Foreign Libraries
(defun load-darwin-framework (framework-name)
"Tries to find and load a darwin framework in one of the directories
in *DARWIN-FRAMEWORK-DIRECTORIES*. If unable to find FRAMEWORK-NAME,
it signals a LOAD-FOREIGN-LIBRARY-ERROR."
(let ((framework (find-darwin-framework framework-name)))
(if framework
(load-foreign-library framework)
(handle-load-foreign-library-error
(cons :framework framework-name)
"Unable to find framework: ~A" framework-name))))
(defun load-foreign-library-name (name)
"Tries to load NAME using %LOAD-FOREIGN-LIBRARY which should try and
find it using the OS's usual methods. If that fails we try to find it
ourselves."
(or (ignore-errors (%load-foreign-library name))
(let ((file (find-file name *foreign-library-directories*)))
(when file
(%load-foreign-library (namestring file))))
;; couldn't load it directly or find it...
(handle-load-foreign-library-error
name "Unable to load foreign library: ~A" name)))
(defun try-foreign-library-alternatives (library-list)
"Goes through a list of alternatives and only signals an error when
none of alternatives were successfully loaded."
(or (some (lambda (lib) (ignore-errors (load-foreign-library lib)))
library-list)
(handle-load-foreign-library-error
(cons :or library-list)
"Unable to load any of the alternatives:~% ~S" library-list)))
(defparameter *cffi-feature-suffix-map*
'((cffi-features:windows . ".dll")
(cffi-features:darwin . ".dylib")
(cffi-features:unix . ".so"))
"Mapping of OS feature keywords to shared library suffixes.")
(defun default-library-suffix ()
"Return a string to use as default library suffix based on the
operating system. This is used to implement the :DEFAULT option.
This will need to be extended as we test on more OSes."
(or (cdr (assoc-if #'cffi-feature-p *cffi-feature-suffix-map*))
(error "Unable to determine the default library suffix on this OS.")))
(defun load-foreign-library (library)
"Loads a foreign LIBRARY which can be a symbol denoting a library defined
through DEFINE-FOREIGN-LIBRARY; a pathname or string in which case we try to
load it directly first then search for it in *FOREIGN-LIBRARY-DIRECTORIES*;
or finally list: either (:or lib1 lib2) or (:framework <framework-name>)."
(etypecase library
(symbol
(dolist (library-description (get-foreign-library library))
(when (cffi-feature-p (first library-description))
(dolist (lib (rest library-description))
(load-foreign-library lib))
(return-from load-foreign-library t))))
(string
(load-foreign-library-name library))
(pathname
(load-foreign-library-name (namestring library)))
(cons
(ecase (first library)
(:framework (load-darwin-framework (second library)))
(:default
(unless (stringp (second library))
(error "Argument to :DEFAULT must be a string."))
(load-foreign-library
(concatenate 'string (second library) (default-library-suffix))))
(:or (try-foreign-library-alternatives (rest library)))))))
(defmacro use-foreign-library (name)
`(load-foreign-library ',name))
;;;# Closing Foreign Libraries
;;;
;;; FIXME: LOAD-FOREIGN-LIBRARY should probably keep track of what
;;; libraries it managed to open and CLOSE-FOREIGN-LIBRARY would then
;;; take a look at that. So, for now, this function is unexported.
(defun close-foreign-library (name)
"Closes a foreign library NAME."
(%close-foreign-library (etypecase name
(pathname (namestring name))
(string name)))) | 10,777 | Common Lisp | .lisp | 228 | 42.894737 | 78 | 0.70345 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | f1d6facc004362d0bf02cc5f1affcb76cac946541c89169fa0730b01310b72d0 | 2,473 | [
-1
] |
2,474 | cffi-allegro.lisp | hoytech_antiweb/bundled/cffi/cffi-allegro.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-allegro.lisp --- CFFI-SYS implementation for Allegro CL.
;;;
;;; Copyright (C) 2005-2006, Luis Oliveira <loliveira(@)common-lisp.net>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:common-lisp #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
;#:make-shareable-byte-vector
;#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:defcfun-helper-forms
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; Backend mis-features.
cffi-features:no-long-long
;; OS/CPU features.
#+macosx cffi-features:darwin
#+unix cffi-features:unix
#+mswindows cffi-features:windows
#+powerpc cffi-features:ppc32
#+x86 cffi-features:x86
#+x86-64 cffi-features:x86-64
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(if (eq excl:*current-case-mode* :case-sensitive-lower)
(string-downcase name)
(string-upcase name)))
;;;# Basic Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(integerp ptr))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(eql ptr1 ptr2))
(defun null-pointer ()
"Return a null pointer."
0)
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(zerop ptr))
(defun inc-pointer (ptr offset)
"Return a pointer pointing OFFSET bytes past PTR."
(+ ptr offset))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
address)
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
ptr)
;;;# Allocation
;;;
;;; Functions and macros for allocating foreign memory on the stack
;;; and on the heap. The main CFFI package defines macros that wrap
;;; FOREIGN-ALLOC and FOREIGN-FREE in UNWIND-PROTECT for the common usage
;;; when the memory has dynamic extent.
(defun %foreign-alloc (size)
"Allocate SIZE bytes on the heap and return a pointer."
(ff:allocate-fobject :char :c size))
(defun foreign-free (ptr)
"Free a PTR allocated by FOREIGN-ALLOC."
(ff:free-fobject ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. The
pointer in VAR is invalid beyond the dynamic extent of BODY, and
may be stack-allocated if supported by the implementation. If
SIZE-VAR is supplied, it will be bound to SIZE during BODY."
(unless size-var
(setf size-var (gensym "SIZE")))
`(let ((,size-var ,size))
(declare (ignorable ,size-var))
(ff:with-stack-fobject (,var :char :c ,size-var)
,@body)))
;;;# Shareable Vectors
;;;
;;; This interface is very experimental. WITH-POINTER-TO-VECTOR-DATA
;;; should be defined to perform a copy-in/copy-out if the Lisp
;;; implementation can't do this.
;(defun make-shareable-byte-vector (size)
; "Create a Lisp vector of SIZE bytes can passed to
;WITH-POINTER-TO-VECTOR-DATA."
; (make-array size :element-type '(unsigned-byte 8)))
;
;(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
; "Bind PTR-VAR to a foreign pointer to the data in VECTOR."
; `(sb-sys:without-gcing
; (let ((,ptr-var (sb-sys:vector-sap ,vector)))
; ,@body)))
;;;# Dereferencing
(defun convert-foreign-type (type-keyword &optional (context :normal))
"Convert a CFFI type keyword to an Allegro type."
(ecase type-keyword
(:char :char)
(:unsigned-char :unsigned-char)
(:short :short)
(:unsigned-short :unsigned-short)
(:int :int)
(:unsigned-int :unsigned-int)
(:long :long)
(:unsigned-long :unsigned-long)
(:float :float)
(:double :double)
(:pointer (ecase context
(:normal '(* :void))
(:funcall :foreign-address)))
(:void :void)))
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(ff:fslot-value-typed (convert-foreign-type type) :c ptr))
;;; Compiler macro to open-code the call to FSLOT-VALUE-TYPED when the
;;; CFFI type is constant. Allegro does its own transformation on the
;;; call that results in efficient code.
(define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
(if (constantp type)
(let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off))))
`(ff:fslot-value-typed ',(convert-foreign-type (eval type))
:c ,ptr-form))
form))
(defun %mem-set (value ptr type &optional (offset 0))
"Set the object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(setf (ff:fslot-value-typed (convert-foreign-type type) :c ptr) value))
;;; Compiler macro to open-code the call to (SETF FSLOT-VALUE-TYPED)
;;; when the CFFI type is constant. Allegro does its own
;;; transformation on the call that results in efficient code.
(define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
(if (constantp type)
(once-only (val)
(let ((ptr-form (if (eql off 0) ptr `(+ ,ptr ,off))))
`(setf (ff:fslot-value-typed ',(convert-foreign-type (eval type))
:c ,ptr-form) ,val)))
form))
;;;# Calling Foreign Functions
(defun %foreign-type-size (type-keyword)
"Return the size in bytes of a foreign type."
(ff:sizeof-fobject (convert-foreign-type type-keyword)))
(defun %foreign-type-alignment (type-keyword)
"Returns the alignment in bytes of a foreign type."
#+(and powerpc macosx32)
(when (eq type-keyword :double)
(return-from %foreign-type-alignment 8))
;; No override necessary for the remaining types....
(ff::sized-ftype-prim-align
(ff::iforeign-type-sftype
(ff:get-foreign-type
(convert-foreign-type type-keyword)))))
(defun foreign-funcall-type-and-args (args)
"Returns a list of types, list of args and return type."
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type :funcall) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type :funcall))
finally (return (values types fargs return-type)))))
(defun convert-to-lisp-type (type)
(if (equal '(* :void) type)
'integer
(ecase type
(:char 'signed-byte)
(:unsigned-char 'integer) ;'unsigned-byte)
((:short
:unsigned-short
:int
:unsigned-int
:long
:unsigned-long) 'integer)
(:float 'single-float)
(:double 'double-float)
(:foreign-address :foreign-address)
(:void 'null))))
(defun foreign-allegro-type (type)
(if (eq type :foreign-address)
nil
type))
(defun allegro-type-pair (type)
(list (foreign-allegro-type type)
(convert-to-lisp-type type)))
#+ignore
(defun note-named-foreign-function (symbol name types rettype)
"Give Allegro's compiler a hint to perform a direct call."
`(eval-when (:compile-toplevel :load-toplevel :execute)
(setf (get ',symbol 'system::direct-ff-call)
(list '(,name :language :c)
t ; callback
:c ; convention
;; return type '(:c-type lisp-type)
',(allegro-type-pair (convert-foreign-type rettype :funcall))
;; arg types '({(:c-type lisp-type)}*)
'(,@(loop for type in types
collect (allegro-type-pair
(convert-foreign-type type :funcall))))
nil ; arg-checking
ff::ep-flag-never-release))))
(defmacro %foreign-funcall (name &rest args)
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(system::ff-funcall
(load-time-value (excl::determine-foreign-address
'(,name :language :c)
ff::ep-flag-never-release
nil ; method-index
))
;; arg types {'(:c-type lisp-type) argN}*
,@(mapcan (lambda (type arg)
`(',(allegro-type-pair type) ,arg))
types fargs)
;; return type '(:c-type lisp-type)
',(allegro-type-pair rettype))))
(defun defcfun-helper-forms (name lisp-name rettype args types)
"Return 2 values for DEFCFUN. A prelude form and a caller form."
(let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name))))
(values
`(ff:def-foreign-call (,ff-name ,name)
,(mapcar (lambda (ty)
(let ((allegro-type (convert-foreign-type ty)))
(list (gensym) allegro-type
(convert-to-lisp-type allegro-type))))
types)
:returning ,(allegro-type-pair
(convert-foreign-type rettype :funcall))
;; Don't use call-direct when there are no arguments.
,@(unless (null args) '(:call-direct t))
:arg-checking nil
:strings-convert nil)
`(,ff-name ,@args))))
;;; See doc/allegro-internals.txt for a clue about entry-vec.
(defmacro %foreign-funcall-pointer (ptr &rest args)
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
(with-unique-names (entry-vec)
`(let ((,entry-vec (excl::make-entry-vec-boa)))
(setf (aref ,entry-vec 1) ,ptr) ; set jump address
(system::ff-funcall
,entry-vec
;; arg types {'(:c-type lisp-type) argN}*
,@(mapcan (lambda (type arg)
`(',(allegro-type-pair type) ,arg))
types fargs)
;; return type '(:c-type lisp-type)
',(allegro-type-pair rettype))))))
;;;# Callbacks
;;; The *CALLBACKS* hash table contains information about a callback
;;; for the Allegro FFI. The key is the name of the CFFI callback,
;;; and the value is a cons, the car containing the symbol the
;;; callback was defined on in the CFFI-CALLBACKS package, the cdr
;;; being an Allegro FFI pointer (a fixnum) that can be passed to C
;;; functions.
;;;
;;; These pointers must be restored when a saved Lisp image is loaded.
;;; The RESTORE-CALLBACKS function is added to *RESTART-ACTIONS* to
;;; re-register the callbacks during Lisp startup.
(defvar *callbacks* (make-hash-table))
;;; Register a callback in the *CALLBACKS* hash table.
(defun register-callback (cffi-name callback-name)
(setf (gethash cffi-name *callbacks*)
(cons callback-name (ff:register-foreign-callable
callback-name :reuse t))))
;;; Restore the saved pointers in *CALLBACKS* when loading an image.
(defun restore-callbacks ()
(maphash (lambda (key value)
(register-callback key (car value)))
*callbacks*))
;;; Arrange for RESTORE-CALLBACKS to run when a saved image containing
;;; CFFI is restarted.
(eval-when (:load-toplevel :execute)
(pushnew 'restore-callbacks excl:*restart-actions*))
;;; Create a package to contain the symbols for callback functions.
(defpackage #:cffi-callbacks
(:use))
(defun intern-callback (name)
(intern (format nil "~A::~A" (package-name (symbol-package name))
(symbol-name name))
'#:cffi-callbacks))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
(declare (ignore rettype))
(let ((cb-name (intern-callback name)))
`(progn
(ff:defun-foreign-callable ,cb-name
,(mapcar (lambda (sym type) (list sym (convert-foreign-type type)))
arg-names arg-types)
(declare (:convention :c))
,@body)
(register-callback ',name ',cb-name))))
;;; Return the saved Lisp callback pointer from *CALLBACKS* for the
;;; CFFI callback named NAME.
(defun %callback (name)
(or (cdr (gethash name *callbacks*))
(error "Undefined callback: ~S" name)))
;;;# Loading and Closing Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library NAME."
;; ACL 8.0 honors the :FOREIGN option and always tries to foreign load
;; the argument. However, previous versions do not and will only
;; foreign load the argument if its type is a member of the
;; EXCL::*LOAD-FOREIGN-TYPES* list. Therefore, we bind that special
;; to a list containing whatever type NAME has.
(let ((excl::*load-foreign-types*
(list (pathname-type (parse-namestring name)))))
(ignore-errors #+(version>= 7) (load name :foreign t)
#-(version>= 7) (load name))))
(defun %close-foreign-library (name)
"Close the foreign library NAME."
(ff:unload-foreign-library name))
;;;# Foreign Globals
(defun convert-external-name (name)
"Add an underscore to NAME if necessary for the ABI."
#+macosx (concatenate 'string "_" name)
#-macosx name)
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(prog1 (ff:get-entry-point (convert-external-name name))))
;;;# Finalizers
(defvar *finalizers* (make-hash-table :test 'eq :weak-keys t)
"Weak hashtable that holds registered finalizers.")
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(push (excl:schedule-finalization
object (lambda (obj) (declare (ignore obj)) (funcall function)))
(gethash object *finalizers*))
object)
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(mapc #'excl:unschedule-finalization
(gethash object *finalizers*))
(remhash object *finalizers*)) | 15,767 | Common Lisp | .lisp | 382 | 35.628272 | 78 | 0.657333 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 6208d61610f8a39b97365ede15b3ed28186ed14cb562c12b9041507e471f5e45 | 2,474 | [
-1
] |
2,475 | cffi-lispworks.lisp | hoytech_antiweb/bundled/cffi/cffi-lispworks.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; cffi-lispworks.lisp --- Lispworks CFFI-SYS implementation.
;;;
;;; Copyright (C) 2005-2006, James Bielman <[email protected]>
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
;;; files (the "Software"), to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
;;; of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
;;; included in all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE.
;;;
;;;# Administrivia
(defpackage #:cffi-sys
(:use #:cl #:cffi-utils)
(:export
#:canonicalize-symbol-name-case
#:pointerp
#:pointer-eq
#:null-pointer
#:null-pointer-p
#:inc-pointer
#:make-pointer
#:pointer-address
#:%foreign-alloc
#:foreign-free
#:with-foreign-pointer
#:%foreign-funcall
#:%foreign-funcall-pointer
#:%foreign-type-alignment
#:%foreign-type-size
#:%load-foreign-library
#:%close-foreign-library
#:%mem-ref
#:%mem-set
#:make-shareable-byte-vector
#:with-pointer-to-vector-data
#:foreign-symbol-pointer
#:defcfun-helper-forms
#:%defcallback
#:%callback
#:finalize
#:cancel-finalization))
(in-package #:cffi-sys)
;;;# Features
(eval-when (:compile-toplevel :load-toplevel :execute)
(mapc (lambda (feature) (pushnew feature *features*))
'(;; Backend mis-features.
cffi-features:no-long-long
;; OS/CPU features.
#+darwin cffi-features:darwin
#+unix cffi-features:unix
#+win32 cffi-features:windows
#+harp::pc386 cffi-features:x86
#+harp::powerpc cffi-features:ppc32
)))
;;; Symbol case.
(defun canonicalize-symbol-name-case (name)
(declare (string name))
(string-upcase name))
;;;# Basic Pointer Operations
(defun pointerp (ptr)
"Return true if PTR is a foreign pointer."
(fli:pointerp ptr))
(defun pointer-eq (ptr1 ptr2)
"Return true if PTR1 and PTR2 point to the same address."
(fli:pointer-eq ptr1 ptr2))
;; We use FLI:MAKE-POINTER here instead of FLI:*NULL-POINTER* since old
;; versions of Lispworks don't seem to have it.
(defun null-pointer ()
"Return a null foreign pointer."
(fli:make-pointer :address 0 :type :void))
(defun null-pointer-p (ptr)
"Return true if PTR is a null pointer."
(fli:null-pointer-p ptr))
;; FLI:INCF-POINTER won't work on FLI pointers to :void so we
;; increment "manually."
(defun inc-pointer (ptr offset)
"Return a pointer OFFSET bytes past PTR."
(fli:make-pointer :type :void :address (+ (fli:pointer-address ptr) offset)))
(defun make-pointer (address)
"Return a pointer pointing to ADDRESS."
(fli:make-pointer :type :void :address address))
(defun pointer-address (ptr)
"Return the address pointed to by PTR."
(fli:pointer-address ptr))
;;;# Allocation
(defun %foreign-alloc (size)
"Allocate SIZE bytes of memory and return a pointer."
(fli:allocate-foreign-object :type :byte :nelems size))
(defun foreign-free (ptr)
"Free a pointer PTR allocated by FOREIGN-ALLOC."
(fli:free-foreign-object ptr))
(defmacro with-foreign-pointer ((var size &optional size-var) &body body)
"Bind VAR to SIZE bytes of foreign memory during BODY. Both the
pointer in VAR and the memory it points to have dynamic extent and may
be stack allocated if supported by the implementation."
(unless size-var
(setf size-var (gensym "SIZE")))
`(fli:with-dynamic-foreign-objects ()
(let* ((,size-var ,size)
(,var (fli:alloca :type :byte :nelems ,size-var)))
,@body)))
;;;# Shareable Vectors
(defun make-shareable-byte-vector (size)
"Create a shareable byte vector."
(sys:in-static-area
(make-array size :element-type '(unsigned-byte 8))))
(defmacro with-pointer-to-vector-data ((ptr-var vector) &body body)
"Bind PTR-VAR to a pointer at the data in VECTOR."
`(fli:with-dynamic-lisp-array-pointer (,ptr-var ,vector)
,@body))
;;;# Dereferencing
(defun convert-foreign-type (cffi-type)
"Convert a CFFI type keyword to an FLI type."
(ecase cffi-type
(:char :byte)
(:unsigned-char '(:unsigned :byte))
(:short :short)
(:unsigned-short '(:unsigned :short))
(:int :int)
(:unsigned-int '(:unsigned :int))
(:long :long)
(:unsigned-long '(:unsigned :long))
(:float :float)
(:double :double)
(:pointer :pointer)
(:void :void)))
;;; Convert a CFFI type keyword to a symbol suitable for passing to
;;; FLI:FOREIGN-TYPED-AREF.
#+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
(defun convert-foreign-typed-aref-type (cffi-type)
(ecase cffi-type
((:char :short :int :long)
`(signed-byte ,(* 8 (%foreign-type-size cffi-type))))
((:unsigned-char :unsigned-short :unsigned-int :unsigned-long)
`(unsigned-byte ,(* 8 (%foreign-type-size cffi-type))))
(:float 'single-float)
(:double 'double-float)))
(defun %mem-ref (ptr type &optional (offset 0))
"Dereference an object of type TYPE OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(fli:dereference ptr :type (convert-foreign-type type)))
;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-REF.
#+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
(define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
(if (constantp type)
(let ((type (eval type)))
(if (eql type :pointer)
(let ((fli-type (convert-foreign-type type))
(ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
`(fli:dereference ,ptr-form :type ',fli-type))
(let ((lisp-type (convert-foreign-typed-aref-type type)))
`(locally
(declare (optimize (speed 3) (safety 0)))
(fli:foreign-typed-aref ',lisp-type ,ptr (the fixnum ,off))))))
form))
;;; Open-code the call to FLI:DEREFERENCE when TYPE is constant at
;;; macroexpansion time, when FLI:FOREIGN-TYPED-AREF is not available.
#-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
(define-compiler-macro %mem-ref (&whole form ptr type &optional (off 0))
(if (constantp type)
(let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
(type (convert-foreign-type (eval type))))
`(fli:dereference ,ptr-form :type ',type))
form))
(defun %mem-set (value ptr type &optional (offset 0))
"Set the object of TYPE at OFFSET bytes from PTR."
(unless (zerop offset)
(setf ptr (inc-pointer ptr offset)))
(setf (fli:dereference ptr :type (convert-foreign-type type)) value))
;;; In LispWorks versions where FLI:FOREIGN-TYPED-AREF is fbound, use
;;; it instead of FLI:DEREFERENCE in the optimizer for %MEM-SET.
#+#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
(define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
(if (constantp type)
(once-only (val)
(let ((type (eval type)))
(if (eql type :pointer)
(let ((fli-type (convert-foreign-type type))
(ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off))))
`(setf (fli:dereference ,ptr-form :type ',fli-type) ,val))
(let ((lisp-type (convert-foreign-typed-aref-type type)))
`(locally
(declare (optimize (speed 3) (safety 0)))
(setf (fli:foreign-typed-aref ',lisp-type ,ptr
(the fixnum ,off))
,val))))))
form))
;;; Open-code the call to (SETF FLI:DEREFERENCE) when TYPE is constant
;;; at macroexpansion time.
#-#.(cl:if (cl:find-symbol "FOREIGN-TYPED-AREF" "FLI") '(and) '(or))
(define-compiler-macro %mem-set (&whole form val ptr type &optional (off 0))
(if (constantp type)
(once-only (val)
(let ((ptr-form (if (eql off 0) ptr `(inc-pointer ,ptr ,off)))
(type (convert-foreign-type (eval type))))
`(setf (fli:dereference ,ptr-form :type ',type) ,val)))
form))
;;;# Foreign Type Operations
(defun %foreign-type-size (type)
"Return the size in bytes of a foreign type."
(fli:size-of (convert-foreign-type type)))
(defun %foreign-type-alignment (type)
"Return the structure alignment in bytes of foreign type."
#+(and darwin harp::powerpc)
(when (eq type :double)
(return-from %foreign-type-alignment 8))
;; Override not necessary for the remaining types...
(fli:align-of (convert-foreign-type type)))
;;;# Calling Foreign Functions
(defvar *foreign-funcallable-cache* (make-hash-table :test 'equal)
"Caches foreign funcallables created by %FOREIGN-FUNCALL or
%FOREIGN-FUNCALL-POINTER. We only need to have one per each
signature.")
(defun foreign-funcall-type-and-args (args)
"Returns a list of types, list of args and return type."
(let ((return-type :void))
(loop for (type arg) on args by #'cddr
if arg collect (convert-foreign-type type) into types
and collect arg into fargs
else do (setf return-type (convert-foreign-type type))
finally (return (values types fargs return-type)))))
(defun create-foreign-funcallable (types rettype)
"Creates a foreign funcallable for the signature TYPES -> RETTYPE."
(format t "~&Creating foreign funcallable for signature ~S -> ~S~%"
types rettype)
;; yes, ugly, this most likely wants to be a top-level form...
(let ((internal-name (gensym)))
(funcall
(compile nil
`(lambda ()
(fli:define-foreign-funcallable ,internal-name
,(loop for type in types
collect (list (gensym) type))
:result-type ,rettype
:language :ansi-c
;; avoid warning about cdecl not being supported on mac
#-mac ,@'(:calling-convention :cdecl)))))
internal-name))
(defun get-foreign-funcallable (types rettype)
"Returns a foreign funcallable for the signature TYPES -> RETTYPE -
either from the cache or newly created."
(let ((signature (cons rettype types)))
(or (gethash signature *foreign-funcallable-cache*)
;; (SETF GETHASH) is supposed to be thread-safe
(setf (gethash signature *foreign-funcallable-cache*)
(create-foreign-funcallable types rettype)))))
(defmacro %%foreign-funcall (foreign-function &rest args)
"Does the actual work for %FOREIGN-FUNCALL-POINTER and %FOREIGN-FUNCALL.
Checks if a foreign funcallable which fits ARGS already exists and creates
and caches it if necessary. Finally calls it."
(multiple-value-bind (types fargs rettype)
(foreign-funcall-type-and-args args)
`(funcall (load-time-value (get-foreign-funcallable ',types ',rettype))
,foreign-function ,@fargs)))
(defmacro %foreign-funcall (name &rest args)
"Calls a foreign function named NAME passing arguments ARGS."
`(%%foreign-funcall (fli:make-pointer :symbol-name ,name) ,@args))
(defmacro %foreign-funcall-pointer (ptr &rest args)
"Calls a foreign function pointed at by PTR passing arguments ARGS."
`(%%foreign-funcall ,ptr ,@args))
(defun defcfun-helper-forms (name lisp-name rettype args types)
"Return 2 values for DEFCFUN. A prelude form and a caller form."
(let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name))))
(values
`(fli:define-foreign-function (,ff-name ,name :source)
,(mapcar (lambda (ty) (list (gensym) (convert-foreign-type ty)))
types)
:result-type ,(convert-foreign-type rettype)
:language :ansi-c
;; avoid warning about cdecl not being supported on mac platforms
#-mac ,@'(:calling-convention :cdecl))
`(,ff-name ,@args))))
;;;# Callbacks
(defvar *callbacks* (make-hash-table))
;;; Create a package to contain the symbols for callback functions. We
;;; want to redefine callbacks with the same symbol so the internal data
;;; structures are reused.
(defpackage #:cffi-callbacks
(:use))
;;; Intern a symbol in the CFFI-CALLBACKS package used to name the internal
;;; callback for NAME.
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun intern-callback (name)
(intern (format nil "~A::~A" (package-name (symbol-package name))
(symbol-name name))
'#:cffi-callbacks)))
(defmacro %defcallback (name rettype arg-names arg-types &body body)
(let ((cb-name (intern-callback name)))
`(progn
(fli:define-foreign-callable
(,cb-name :encode :lisp
:result-type ,(convert-foreign-type rettype)
:calling-convention :cdecl
:language :ansi-c
:no-check nil)
,(mapcar (lambda (sym type)
(list sym (convert-foreign-type type)))
arg-names arg-types)
,@body)
(setf (gethash ',name *callbacks*) ',cb-name))))
(defun %callback (name)
(multiple-value-bind (symbol winp)
(gethash name *callbacks*)
(unless winp
(error "Undefined callback: ~S" name))
(fli:make-pointer :symbol-name symbol :module :callbacks)))
;;;# Loading Foreign Libraries
(defun %load-foreign-library (name)
"Load the foreign library NAME."
(fli:register-module name :connection-style :immediate))
(defun %close-foreign-library (name)
"Close the foreign library NAME."
(fli:disconnect-module name :remove t))
;;;# Foreign Globals
(defun foreign-symbol-pointer (name)
"Returns a pointer to a foreign symbol NAME."
(prog1 (ignore-errors (fli:make-pointer :symbol-name name :type :void))))
;;;# Finalizers
(defvar *finalizers* (make-hash-table :test 'eq :weak-kind :key)
"Weak hashtable that holds registered finalizers.")
(hcl:add-special-free-action 'free-action)
(defun free-action (object)
(let ((finalizers (gethash object *finalizers*)))
(unless (null finalizers)
(mapc #'funcall finalizers))))
(defun finalize (object function)
"Pushes a new FUNCTION to the OBJECT's list of
finalizers. FUNCTION should take no arguments. Returns OBJECT.
For portability reasons, FUNCTION should not attempt to look at
OBJECT by closing over it because, in some lisps, OBJECT will
already have been garbage collected and is therefore not
accessible when FUNCTION is invoked."
(push function (gethash object *finalizers*))
(hcl:flag-special-free-action object)
object)
(defun cancel-finalization (object)
"Cancels all of OBJECT's finalizers, if any."
(remhash object *finalizers*)
(hcl:flag-not-special-free-action object))
| 15,571 | Common Lisp | .lisp | 357 | 38.280112 | 80 | 0.66847 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | e1ddc1d06f3f369e52fcad641c7a6c59e1416c638e81cd5de3638733c050e35d | 2,475 | [
-1
] |
2,487 | make-debian-package.pl | hoytech_antiweb/packager/make-debian-package.pl | #!/usr/bin/env perl
use strict;
my $prefix = '/usr/local/antiweb';
my $antiweb_bin_dir = '/usr/bin';
my $antiweb_lib_dir = '/usr/lib';
sub usage {
print STDERR <<END;
Antiweb (C) Doug Hoyte
Debian package creation script
usage:
$0 <lisp> <architecture> <operating system>
$0 ccl amd64 linux
$0 cmu i386 linux
$0 cmu i386 freebsd ## FIXME: not implemented
$0 cmu amd64 linux ## FIXME: not implemented
$0 clean ## removes build/ and *.deb
END
exit 1;
}
## SCRIPT PARAMETERS
my $lisp = shift || usage();
if ($lisp eq 'clean') {
sys("rm -rf build/ *.deb");
exit;
}
my $arch = shift || usage();
my $os = shift || usage();
## SOME BASIC SANITY CHECKS
my $bits = length pack("l!")==8 ? 64 : 32;
die "This packager script must be run as root" if $<;
die "Unable to find DEBIAN/ directory. Not in packager directory" unless -d 'DEBIAN';
die "This antiweb repo has a ../local.lisp. Please back it up and remove it." if -e '../local.lisp';
die "This machine already has an antiweb launch script at $antiweb_bin_dir/antiweb" if -e "$antiweb_bin_dir/antiweb";
die "This machine already has an antiweb library at $antiweb_lib_dir/libantiweb$bits.so" if -e "$antiweb_lib_dir/libantiweb$bits.so";
die "This machine already has an antiweb install in its prefix: $prefix" if -e $prefix;
## VERIFY SCRIPT PARAMETERS
if ($lisp eq 'cmu') {
die "packaging cmucl for non-i386 platforms is not supported by this script (but is possible)" unless $arch eq 'i386';
} elsif ($lisp eq 'ccl') {
die "clozurecl is only stable on 64 bit platforms" unless $bits == 64;
} else {
print STDERR "Invalid lisp parameter: $lisp\n\n";
usage();
}
if ($arch eq 'amd64') {
die "this machine isn't an amd64" unless $bits == 64;
} elsif ($arch eq 'i386') {
die "this machine isn't an i386" unless $bits == 32;
} else {
print STDERR "Invalid architecture parameter: $arch\n\n";
usage();
}
if ($os eq 'linux') {
die "this machine isn't running linux" unless `uname -a` =~ /linux/i;
} elsif ($os eq 'freebsd') {
die "this machine isn't running freebsd" unless `uname -a` =~ /freebsd/i;
} else {
print STDERR "Invalid operating system parameter: $os\n\n";
usage();
}
## FIND ANTIWEB VERSION
my $aw_version = `git describe --tags --match antiweb-\*`;
chomp $aw_version;
$aw_version =~ s/^antiweb-//;
if ($aw_version =~ /^(.*-)(g[a-f]+)$/) {
# Work around dpkg lameness where it won't install a package unless the hashtag contains a digit
$aw_version = $1 . '0' . $2;
}
print <<END;
OK, so far your setup looks good:
Antiweb version: $aw_version
Lisp: $lisp
Architecture: $arch
Operating System: $os
END
## COPY LISP SYSTEMS INTO PREFIX
if ($lisp eq 'cmu') {
print "\n*** Please enter a path to a CMUCL directory then press enter:\n";
my $path = <>;
chomp $path;
die "path is not a directory: $path" unless -d $path;
die "unable to find binary at $path/bin/lisp" unless -x "$path/bin/lisp";
die "unable to find lib directory at $path/lib/" unless -d "$path/lib/";
sys("mkdir -p $prefix/cmucl/");
sys("cp -r $path/bin $path/lib $prefix/cmucl/");
} elsif ($lisp eq 'ccl') {
print "\n*** Please enter a path to a ClozureCL directory then press enter:\n";
my $path = <>;
chomp $path;
die "path is not a directory: $path" unless -d $path;
die "unable to find binary at $path/lx86cl64" unless -x "$path/lx86cl64";
die "unable to find lisp image at $path/lx86cl64.image" unless -e "$path/lx86cl64.image";
die "unable to find launcher script at $path/scripts/ccl64" unless -x "$path/scripts/ccl64";
die "unable to find x86-headers64/ dir at $path/x86-headers64/" unless -d "$path/x86-headers64/";
sys("mkdir -p $prefix/ccl/");
sys("cp $path/lx86cl64 $prefix/ccl/");
sys("cp $path/lx86cl64.image $prefix/ccl/");
sys("cp $path/scripts/ccl64 $prefix/ccl/");
sys("cp -r $path/x86-headers64/ $prefix/ccl/");
# rewrite the ccl64 script to refer to our custom prefix
sys(qq{ /usr/bin/env perl -pi -e 's|\\s*CCL_DEFAULT_DIRECTORY=.*| CCL_DEFAULT_DIRECTORY=$prefix/ccl|' $prefix/ccl/ccl64 });
}
## COPY BERKELEYDB LIBRARY INTO PREFIX
{
print "\n*** Please enter a path to a compiled BerkeleyDB installation:\n";
my $path = <>;
chomp $path;
die "path is not a directory: $path" unless -d $path;
die "unable to find db_recover utility at $path/bin/db_recover" unless -x "$path/bin/db_recover";
die "unable to find lib/ directory at $path/lib/" unless -d "$path/lib";
die "unable to find $path/lib/libdb.a" unless -e "$path/lib/libdb.a";
die "unable to find include/ directory at $path/include/" unless -d "$path/include";
sys("mkdir -p $prefix/bdb$bits/");
sys("cp -r $path/bin/ $prefix/bdb$bits/");
sys("cp -r $path/lib/ $prefix/bdb$bits/");
sys("cp -r $path/include/ $prefix/bdb$bits/");
}
## CREATE ../local.lisp BUILD CONFIG AND BUILD ANTIWEB
if ($lisp eq 'cmu') {
open(FH, "> ../local.lisp");
print FH <<END;
#+cmu
(progn
(setq aw-bin-dir "$antiweb_bin_dir")
(setq aw-lib-dir "$antiweb_lib_dir")
(setq aw-cmu-executable "$prefix/cmucl/bin/lisp")
(setq aw-use-bdb t)
(setq aw-extra-cflags "-L$prefix/bdb$bits/lib -I$prefix/bdb$bits/include/ -Wl,-rpath=$prefix/bdb$bits/lib")
)
#-cmu
(error "this package was configured for CMUCL")
END
close(FH);
sys("cd .. ; $prefix/cmucl/bin/lisp -quiet -load build.lisp");
} elsif ($lisp eq 'ccl') {
open(FH, "> ../local.lisp");
print FH <<END;
#+ccl
(progn
(setq aw-bin-dir "$antiweb_bin_dir")
(setq aw-lib-dir "$antiweb_lib_dir")
(setq aw-ccl-executable "$prefix/ccl/ccl64")
(setq aw-use-bdb t)
(setq aw-extra-cflags "-L$prefix/bdb$bits/lib -I$prefix/bdb$bits/include/ -Wl,-rpath=$prefix/bdb$bits/lib")
)
#-ccl
(error "this package was configured for ClozureCL")
END
close(FH);
sys("cd .. ; $prefix/ccl/ccl64 -Q -l build.lisp");
}
## VERIFY BUILD
die "unable to find ../bin/antiweb - build failure?" unless -x "../bin/antiweb";
die "unable to find ../bin/libantiweb$bits.so - build failure?" unless -e "../bin/libantiweb$bits.so";
die "unable to find ../bin/antiweb.$lisp.image - build failure?" unless -e "../bin/antiweb.$lisp.image";
## SETUP PACKAGE build/ DIRECTORY
sys("rm -rf build");
sys("mkdir build");
sys("cp -r DEBIAN/ build");
sys(qq{ /usr/bin/env perl -pi -e 's|{{VERSION}}|$aw_version|' build/DEBIAN/control });
sys(qq{ /usr/bin/env perl -pi -e 's|{{ARCH}}|$arch|' build/DEBIAN/control });
sys("mkdir -p build$prefix");
sys("cp -r $prefix/* build$prefix");
sys("mkdir -p build$antiweb_bin_dir");
sys("cp ../bin/antiweb build$antiweb_bin_dir");
sys("mkdir -p build$antiweb_lib_dir");
sys("cp ../bin/libantiweb$bits.so build$antiweb_lib_dir");
sys("cp ../bin/antiweb.$lisp.image build$antiweb_lib_dir");
## REMOVE VIRGIN LISP IMAGE - ONLY THE NEW ANTIWEB IMAGE IS REQUIRED
if ($lisp eq 'cmu') {
sys("rm build$prefix/cmucl/lib/cmucl/lib/*.core");
} elsif ($lisp eq 'ccl') {
sys("rm build$prefix/ccl/lx86cl64.image");
}
## REMOVE TEMPORARY FILES
sys("rm -rf $prefix");
sys("rm ../local.lisp");
## ACTUALLY BUILD PACKAGE
my $deb_package_filename = "antiweb" . "_" . $aw_version . "_" . "$lisp-$arch-$os" . ".deb";
sys("dpkg -b build/ $deb_package_filename");
print "\n\nCongratulations, your debian package was created:\n\n$deb_package_filename\n\n";
exit;
## UTILITIES
sub sys {
my $cmd = shift;
print "SYSTEM: $cmd\n";
my $ret = system($cmd);
die "** system() failed with non-zero exit code ($ret)" if $ret;
}
| 7,468 | Common Lisp | .l | 189 | 37.063492 | 133 | 0.679272 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3fcb01eafe729dd99b8d9deb36bbd08fd04281f9b8ac86be53b7a1c727541e39 | 2,487 | [
-1
] |
2,488 | control | hoytech_antiweb/packager/DEBIAN/control | Package: antiweb
Version: {{VERSION}}
Architecture: {{ARCH}}
Maintainer: Doug Hoyte
Description: Common Lisp web application server
Depends: perl,
zlib1g
| 163 | Common Lisp | .l | 7 | 21 | 47 | 0.775641 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 775eec8929a3d3bff07bcc3a87296012b9e7cd8bde013775e3fe8be4efa4cd9b | 2,488 | [
-1
] |
2,489 | manual.awp | hoytech_antiweb/src/manual.awp | ;; Antiweb (C) Doug Hoyte
(defglue sections (&rest sects)
(with-output-to-string (s)
(format s #"<ol>"#)
(dolist (sect sects)
(format s "<li><a href=\"#~a\">~a</a>" (car sect) (cadr sect)))
(format s #"</ol><hr>"#)
(dolist (sect sects)
(format s #"<fieldset><legend id="~a">~a</legend>~a</fieldset>"# (car sect) (cadr sect)
(awp-super-glue (cons 'p (cddr sect)))))))
(defglue tip (text)
(format nil #"<span class=tip><b><u>Antiweb Tip</u></b><br>~a</span>"# (awp-super-glue text)))
(defglue awp-guiding-principles ()
(awp-super-glue
'(fieldset "The Guiding Principles for Anti Webpages" (ul
#"Anti Webpages: When you just gotta git 'er done dammit."#
#"If you want to write straight HTML or Javascript or CSS, go ahead and do it. Anti Webpages don't judge, they glue."#
#"If you can't solve it with a regular expression, you aren't trying hard enough."#
#"There's Even More Ways To Do It Than In Perl (TEMWTDITIP)."#
#"It doesn't matter how deep you go. There's <b>no bottom</b>."#
#"Why duct-tape when you can super-glue?"#
))))
(page "index.html"
:title "Antiweb Manual"
:header #"<h1><u>Antiweb Manual</u></h1>"#
:slogan #"<i>For admins, by admins.</i>"#
:layout #"
logo@r | | header@l | slogan |
nav@rt | | content@tl |
footer |
"#
:layout-width 800
:css #"
body {
font-family: Verdana, Arial, sans-serif;
}
h1 {
font-size:40px;
}
a:link,a:visited {
color:#00F;
}
hr {
margin-top: 3%;
margin-bottom: 2%;
border:0px;
color: black;
background-color: black;
height: 3px;
width: 5%;
}
fieldset {
border:1px solid #000;
padding:1em 1em 1em 1.5em;
}
legend {
font-size:18px;
}
pre {
background: #eeeeee;
border: 1px solid #888888;
color: black;
padding: 1em;
white-space: pre;
}
span.tip {
background: #57ffed;
border: 1px solid #888888;
width: 40%;
float: right;
padding: 1em;
margin: 1em 0 1em 1em;
}
"#
:logo #"<a href="http://hoytech.com/antiweb/"><img border=0 src="http://hoytech.com/antiweb/antiweb.png"></a>"#
:content (p
#"This is the official manual for the #(link "http://hoytech.com/antiweb/" "Antiweb") webserver. We take documentation seriously. If you have questions that aren't answered in the docs, that is a bug. Please #(link "http://groups.google.com/group/antiweb" "report it to us") so we can answer your question and improve the manual."#
#"Which section of the manual you should read depends on your interest in Antiweb:"#
(ul
#"#(link "design.html" "Design of Antiweb4") is a high-level description of what Antiweb is and why you should use it."#
#"Once you have decided to install Antiweb, follow the instructions in the #(link "install.html" "Installation") section. If you run into problems during or after installation, check the #(link "faq.html" "FAQ")."#
#"The #(link "worker.html" "Worker Conf File Reference") describes all the options and features available to worker processes."#
#"Antiweb's experimental HTML+CSS+JS creation programs are called #(link "awp.html" "Anti Webpages"). The manual you are reading now is an Anti Webpage."#
))
:nav
(p (link "index.html" "Start")
(link "design.html" "Design of Antiweb4")
(link "install.html" "Installation")
(link "faq.html" "FAQ")
(link "worker.html" "Worker Conf File Reference")
(link "awp.html" "Anti Webpages"))
:footer "All content is © Hoytech unless otherwise noted or implied."
)
(page "design.html"
:title "Antiweb Manual: Design of Antiweb4"
:header #"<h1><u>Design of Antiweb4</u></h1>"#
:inherit "index.html"
:content
(sections
(future #"Next-Generation of Antiweb"#
#"Antiweb is a webserver written in Common Lisp, C, and Perl by #(link "http://hoytech.com" "Hoytech"). Antiweb is not a "proof of concept" and is not "exploratory code". We intend the core design of Antiweb (as described in this design paper) to be stable for the next 10+ years of use."#
#"The two webservers that have had the largest influence on Antiweb4 are #(link "http://nginx.net" "nginx") and #(link "http://www.lighttpd.net/" "lighttpd"). #(tip #"Did you know that Antiweb is older than both lighttpd and nginx? It used to be called #(link "http://hcsw.org/awhttpd/" "awhttpd")."#) We took liberal advantage investigating these and other excellent servers while designing Antiweb4. Another more obscure server that has influenced Antiweb is #(link "http://fhttpd.org" "fhttpd")."#
#"Why another webserver? In our opinion, the biggest problem with the above servers is that they aren't written in lisp. Many servers that we studied have grafted on extension languages (ie, Perl for nginx and Lua for lighttpd). Antiweb is different. Instead of being a C program that uses some other language, Antiweb is a lisp program that uses C (and Perl)."#
)
(server-design "Server Design"
#"Like nginx, lighttpd, fhttpd, and Antiweb3, Antiweb4 is an <b>asynchronous</b> or <b>event-based</b> or <b>non-blocking</b> server, meaning that a single thread of control multiplexes multiple client connections. An Antiweb system is a collection of unix processes. Connections are transferred between processes with #(link "http://www.openbsd.org/cgi-bin/man.cgi?query=sendmsg" "sendmsg()"). When this happens, any data that was initially read from the socket is transferred along with the socket itself. The socket is always closed in the sending process."#
#"To multiplex connections inside a process, Antiweb uses a state machine data structure defined in <b>src/libantiweb.h</b>. Antiweb requires either the kqueue() or epoll() stateful event APIs in level-triggered mode."#
(ul #"On a 32 bit linux/CMUCL system, 10000 inactive keepalive connections consume about 3M of user-space memory (in addition to two lisp images)."# #"The number of inactive keepalive connections has negligible performance impact on new connections."#)
#"There are three modes for sending files: medium, small, and large:"#
(ol
#"<b>Medium:</b> These files are mmap()ed (memory mapped) to avoid copying the file's data into user-space. The data is copied directly from the filesystem to the kernel's socket buffer."#
#"<b>Small:</b> These files are read into a user-space buffer because a small read() is often cheaper than mmap()+munmap()."#
#"<b>Large:</b> Antiweb uses a user-space buffer for large files. This is to avoid disk-thrashing when serving many large files to clients concurrently (#(link "http://blog.lighttpd.net/articles/2005/11/11/optimizing-lighty-for-high-concurrent-large-file-downloads" "idea from lighttpd")) and to avoid running out of address space on 32 bit systems."#
)
#"<b>Super-size it:</b> Because Antiweb uses a 64 bit off_t type and lisp's unlimited precision integers on all systems, Antiweb can serve files of any size. It also supports #(link "worker.html#DOWNLOAD-RESUMING" "download resuming") for all three file send modes."#
#"Antiweb's data structures are designed for <b>pipelining</b>. Antiweb uses <b>vectored I/O</b> (also known as scatter-gather I/O) nearly everywhere. Antiweb's internal message passing protocol uses pipelining also. For example, an HTTP connection that pipelines two requests for small files followed by one request for a medium file is responded to with a single writev() system call consisting of the following:"#
(ul
#"The HTTP headers and file contents for the first two small files"#
#"The HTTP headers for the medium file"#
#"As much of the memory mapped medium file as it takes to fill the kernel's socket buffer."#
)
#"Subsequently, all the generated log messages are written to the hub process with writev(). The hub will forward the log messages to the logger process with another writev(). Finally, the logger process will append the messages onto the <b>axslog</b> file."#
#"To see the connection statistics of a worker process, use the #(link "faq.html#STATS" "-stats") command:"#
(pre #"# antiweb -stats /var/aw/example.conf
...
Keepalive Time: 65 seconds
Total Connections: 41 HTTP requests: 72 Avg reqs/conn: 1.8
File descriptor usage (estimate): 17/32767
Current Connections: 11
Keepalives: 7 Sending files to: 2
Proxy: Sources: 0 Sinks: 0 Idle: 0
Timers: 0 Hub: 1 Unix Connections: 1
Lingering: 0 Zombies: 0
...
"#)
#"Notice that in addition to the HTTP traffic, there is also a connection to the hub's unix socket that was opened on start-up, and one other open unix socket. That other unix socket is you. You created a supervisor connection while asking for stats info."#
#"-stats will also tell you how hosts are mapped to directories on a worker:"#
(pre #"# antiweb -stats /var/aw/example.conf
...
Host -> HTML root mappings:
localhost -> /var/www/testing
example.com -> /var/www/example.com
www.example.com -> /var/www/example.com
...
"#)
#"Although usually we love it, sometimes pipelining is bad. Antiweb deliberately tears down persistent HTTP connections on certain responses:"#
(ul #"<b>4XX and 5XX HTTP Errors</b> - This is to prevent blind web vulnerability scanners like #(link "http://www.cirt.net/nikto2" "nikto") from persisting or pipelining 95+ percent of their requests."#
#"<b>Directory Listings</b> - To prevent pipelined recursive crawling."#
)
#"When finished with a connection, Antiweb will shutdown the write direction of the socket and #(link "faq.html#LINGER" "linger") as required by HTTP/1.1. Antiweb always gracefully degrades for HTTP/0.9 and HTTP/1.0 clients. Antiweb has first-class IPv6 support. If you really do want to pipeline 4XX and 5XX errors, you have two options:"#
(ol
#"Use Antiweb's #(link "worker.html#REWRITE" "rewrite module") to change problematic requests into requests for existing files."#
#"Use Antiweb's #(link "worker.html#FAST-FILES" "fast-files module"). This is a memory cache that supports accelerated static content, pre-generation of HTTP headers, negative caching, and persisting/pipelining 404 errors."#
)
#"Antiweb was designed with security in mind from the beginning. Here are some of the security decisions made during the Antiweb design process:"#
(ul
#"Virtual hosts are privilege-separated <b>without proxying</b>. Once the hub has determined which worker should handle a connection, it transfers the socket to the worker process and has nothing further to do with the connection. Worker processes run under different UIDs from the hub (and each-other). Workers are optionally #(link "worker.html#CHROOT" "chroot()ed")."#
#"Workers have no access to log files: all log messages are sent to the hub over the unix socket. The hub then subsequently sends them to the logger process. This means that a compromised worker process cannot steal previously created log messages or log messages created by other workers, and a compromised hub process cannot steal previously created log messages."#
#"#(link "design.html#CGI-PROCESS" "CGI processes") can be restricted with resource limitations."#
#"Even on lisps without unicode support, Antiweb4 guarantees all internal data and filenames are #(link "design.html#UNICODE" "UTF-8") encoded. This includes verifying all code-points are in their shortest possible representation and that there are no otherwise invalid surrogates."#
#"Antiweb processes never try to clean-up or recover in the event of an unexpected condition. A process cannot do that because it has #(link "faq.html#ERLANG" "failed"). Some other process that hasn't failed will clean-up after it."#
)
#"Antiweb also includes an experimental new technology for constructing webpages called #(link "awp.html" "Anti Webpages"). These are Perl-inspired programs that let you draw page layouts with significant whitespace, glue together HTML/CSS/Javascript, and more."#
#"<b>Antiweb was created for admins, by admins</b>. Please #(link "http://groups.google.com/group/antiweb" "let us know") any ways you think it could be better."#
)
(memory-management "Memory Management"
#"The most important memory management system in Antiweb is lisp's garbage-collector. Many implementations of Common Lisp that Antiweb supports have excellent generational collectors so you will probably never notice pausing except in stressful benchmarks."#
#"Outside of lisp, Antiweb also maintains two important data structures: <b>conns</b> and <b>ioblocks</b>. The definitions of these data structures are in the file <b>src/libantiweb.h</b>. Despite the extension, this is not a C header file. It is a special format that can be parsed by both lisp and a C compiler."#
#"You can always get a break-down of the memory being used by an Antiweb process with the <b>-room</b> command. Here is what it might look like when you query a worker using CMUCL:"#
(pre #"
# antiweb -room /var/aw/example.conf
"---ANTIWEB MEMORY STATS---
Dynamic Space Usage: 1,946,272 bytes (out of 512 MB).
Read-Only Space Usage: 24,024,304 bytes (out of 256 MB).
Static Space Usage: 3,665,792 bytes (out of 256 MB).
Control Stack Usage: 1,636 bytes (out of 128 MB).
Binding Stack Usage: 88 bytes (out of 128 MB).
The current dynamic space is 0.
Garbage collection is currently enabled.
conns and ioblocks:
Allocated conns: 2, 470 bytes
Allocated ioblocks: 1, 4112 bytes, 14 in use, 99.7% overhead
Free conns: 2, 470 bytes
Free ioblocks: 514, 2113568 bytes
Total: 2118620 bytes + malloc overhead
---END OF ANTIWEB MEMORY STATS---"
"#)
#"If you look through the file <b>src/libantiweb.c</b>, you will see that Antiweb malloc()s conn and ioblock structures but never free()s them. When Antiweb is done with a structure it pushes it onto a free-list. The next time it needs a structure it pops the most recently pushed one off the free-list. Antiweb can do this because conn and ioblock structures are always the same size."#
#"<b>Freeing memory considered harmful.</b>"#
#"In the above <b>-room</b> output, the conn and ioblock measurements represent the <b>high water mark</b>. During periods of heavy traffic, more memory is allocated. When the traffic settles down, the pages at the bottom of the free-lists are swapped out by the kernel as needed."#
)
(processes "Processes"
#"For performance and security, Antiweb is a group of unix processes. This section describes the roles and responsibilities of the different processes."#
#"The following figure illustrates the processes and responsibilities of a running Antiweb system."#
(fieldset #"Antiweb4 Processes"# #"<img src="http://hoytech.com/antiweb/processes2.png">"#)
(sections
(hub-process "Hub Process"
#"The hub process is usually the busiest process in the Antiweb system. Here are its duties:"#
(ul
#"Accept new connections over its unix socket, which may either be connecting worker processes or supervisor connections."#
#"Accept HTTP connections from the internet, decide based on the requested virtual host (vhost) which worker the connection applies to, then send the already read data from the connection along with the socket itself over the unix socket to the worker. This process closes the socket in the hub process so it is only open in the worker."#
#"Accept all log messages from worker processes and forward them to the logger process."#
#"Route inter-process messages (such as supervisor connections)."#
)
#"Some other details about the hub:"#
(ul
#"Runs as its own user or UID specified in the hub conf file."#
#"chroot()ed to the empty directory, of which it owns no permissions."#
)
)
(logger-process "Logger process"
#"The logger process is connected to the hub process over a unix socket. Its only job is to accept log messages from the hub process and write them to disk. When a worker creates a log message, it is routed through the hub to the logger process."#
(ul
#"Runs as its own user or UID specified in the hub conf file."#
#"chroot()ed to the aw_log directory, of which it has write permission."#
#"It will chmod() the log files so they are never world readable/writeable."#
#"Log files cannot be symlinks."#
)
)
(worker-process "Worker Process(es)"
#"The worker processes do the heavy lifting of processing HTTP requests."#
(ul
#"Each runs under its own user or UID specified in the #(link "worker.html#UID" "worker conf")."#
#"Optionally #(link "worker.html#CHROOT" "chroot()ed")."#
#"Because it is transferred connecting client sockets, the worker process handles all subsequent HTTP requests on these sockets. They do not go through the hub."#
)
#"#(tip #"Why would you want to run multiple workers?<br>#(ul "Privilege separated vhosts" "SMP/multi-core" "Reduce disk latency")"#) On start-up, each worker process reads its conf file and compiles a function for dispatching HTTP requests given the mount points and other features present. After it starts, a worker process will never re-open this conf file. The only way to provide it a new conf file is by message passing using a supervisor process. This is necessary to allow you to chroot() a worker to a root not containing the conf file."#
#"After registering the vhosts it is interested in with the hub, a worker process will "lock" the hub connection so it can't register additional vhosts. To later add vhosts, the connection must be manually unlocked by a supervisor process (this happens behind-the-scenes when you #(link "faq.html#RELOADING-WORKER-CONF" "-reload") a worker conf--see one possible but #(link "faq.html#RELOAD-ATTACK" "unlikely attack") related to this.). If you try to -reload with a bad worker conf, Antiweb will not install the new conf and will continue with the original conf. If you -reload a worker conf and it compiles fine but throws some error during processing an HTTP request, Antiweb will kill the worker and the reason will be logged to syslog."#
(fieldset "Privilege Separation" (ul #"A compromised worker process cannot steal connections for vhosts that don't belong to it."# #"A compromised worker process cannot intercept log messages created by other workers."#))
)
(supervisor-process "Supervisor Process(es)"
(ul
#"Supervisor processes are only intended for interactive use, not as unattended, long running processes."#
#"A supervisor process never executes the eval message."#
)
#"Supervisor processes do not run during normal Antiweb operation. The user must (as root) manually start a supervisor process. #(tip "Although you must start a supervisor process as root, root privileges are dropped once you have attached. They are dropped to the same UID/GID as the process you are attaching to.") Typically, you will only run a supervisor process to #(link "faq.html#ATTACH" "attach") to other processes for diagnostics/development/etc."#
#"Supervisor processes are created for almost every Antiweb operation, including #(link "faq.html#STATS" "-stats") queries and #(link "faq.html#ADDING-LISTENERS" "adding or removing listeners"). When you attach to a worker process, the hub passes the supervisor process's unix socket to the worker over the same unix socket that HTTP connections are transferred over."#
)
(cgi-process "CGI Process(es)"
#"#(tip "The limit on the length of POST content is defined in src/libantiweb.h as AW_MAX_POST_LEN")Antiweb is conditionally compliant with CGI/1.1. All useful environment variables are supported, as well as buffered POST content on standard input. PATH_INFO is supported and is implemented more efficiently than many other servers (including Antiweb3). Your CGI script may start receiving data before the entire POST content has been read by the worker. If the POST is terminated prematurely, the content may be cut short. Be sure to check you have read exactly $ENV{CONTENT_LENGTH} bytes."#
(ul #"CGI processes run under the same UIDs as the worker processes that spawn them. If you chroot your worker processes, expect using CGI to be more difficult."#
#"CGI scripts have all file descriptors from their parent worker closed as well as the worker's epoll descriptor (kqueues don't transfer on fork())."#
#"Requests to CGI scripts always close the HTTP connection. You don't need to send a "Connection: close", Antiweb will send that for you (unless you use #(link "worker.html#NAKED-CGI" "naked CGI scripts"))."#
#"CGI scripts are unable to issue Antiweb log messages or even indicate success/failure to Antiweb (it just ignores CGI process exit() codes). Zombies are reaped."#))))
(confs-and-xconfs "Confs and Xconfs"
#"Antiweb is not written in Common Lisp for the sake of novelty. Common Lisp was selected because <b>it is the best</b>. Instead of writing our own config file parsers, string routines, memory allocators, condition systems, dynamic binding systems, just-in-time compilers, etc, etc., we rely heavily on many features of Common Lisp (but not its I/O or pathnames)."#
#"If you haven't used lisp before, Antiweb may require a major shift in thinking. Many things you may think are impossible are easy. Languages like C are designed to be easy to implement—Common Lisp is designed to be powerful to program. #(tip #"The primary description of our lisp programming style is Doug Hoyte's book:<br>#(link "http://letoverlambda.com" "Let Over Lambda")."#) Even if you have programmed in lisp before, "The Antiweb Way" might still seem foreign. Just like Antiweb is not a conventional webserver, it is also not a conventional lisp program."#
#"This section describes the most important data-structures for installing, configuring, extending, and creating content for Antiweb: confs and xconfs."#
(sections
(confs #"confs"#
#"As an administrator, almost all Antiweb files you interact with are called <b>conf</b> files."#
#"Conf files are text files filled with lisp forms. Every one of these lisp forms must be a list with the first element a symbol identifying the type of the form. This might be an example conf:"#
(pre #"(worker blah)
(uid "my-user")"#)
#"If a worker contains an inherit element, the corresponding file will also be parsed as a conf and its contents are appended to the current file's conf:"#
(pre #"(inherit "/absolute/path/to/inherited.conf")"#)
(ul "Circular inherits are detected and signal errors.")
)
(xconfs #"xconfs"#
#"The forms inside confs are called <b>xconfs</b>. They must begin with an identifying symbol, and then are optionally followed by arguments. The xconfs in the example confs from the previous section each had one mandatory argument, like this:"# (pre #"(name "value")"#) #"But here is an xconf with no mandatory arguments and one optional argument:"#
(pre #"(name :arg "value")"#)
#"Xconfs superficially resemble Common Lisp #(link "http://www.lispworks.com/documentation/HyperSpec/Body/m_destru.htm" "destructuring") but are in fact <b>very different</b>. For instance, the same argument can be given multiple values in a single xconf:"#
(pre #"(name :arg "value1" :arg "value2")"#)
#"Depending on the type of xconf, Antiweb may use only "value1" or it may use both "value1" and "value2"."# #"Xconfs can also have boolean arguments:"#
(pre #"(name :arg "value1" :boolean-arg)
(name :boolean-arg :arg "value1")"#)
#"The presence of the :boolean-arg keyword in the above examples <b>turns on</b> some functionality. In this respect, xconfs are closer to unix shell arguments than Common Lisp destructuring."#
)
)
"Confs and xconfs are designed to be intuitive and extremely flexible. The src/conf.lisp file has more details on how and why confs and xconfs work."
)
(filesystem "Filesystem Layout"
#"Antiweb's #(link "install.html" "installation procedure") adds three (3) files to your filesystem. Their paths can be changed by editing build.lisp before compiling Antiweb. By default they are:"#
(ul
#"<b>/usr/bin/antiweb</b> - The perl launch script. All Antiweb processes are launched through this script interface."#
#"<b>/usr/lib/libantiweb32.so</b> or <b>/usr/lib/libantiweb64.so</b> - The Antiweb shared library. Most of the code for accessing the network and filesystem is compiled and stored here. The name depends on your architecture."#
#"<b>/usr/lib/antiweb.cmu.image</b> or <b>/usr/lib/antiweb.clisp.image</b> or <b>/usr/lib/antiweb.ccl.image</b> - A frozen image of the memory of an Antiweb lisp process. The name depends on your lisp environment."#
)
#"You also need to create a hub directory. Inside this directory (typically <b>/var/aw/</b>):"#
(ul #"<b>hub.conf</b> - Hub configuration. Includes which interaces/ports to listen for connections on (though you can #(link "faq.html#ADDING-LISTENERS" "add more later without restarting")), the user or UID the hub and logger processes should run as, and the file descriptor limit for the hub process."#
#"<b>hub.socket</b> - Unix domain socket for connecting to the hub. It is owned by root and no other user can connect. All Antiweb administration, development, and inter-process communication is done through this socket."#
#"<b>empty/</b> - An empty directory. The hub process is chroot()ed to this directory. It should have no write permission to this directory."#
#"<b>aw_log/</b> - The log directory. The logger process is chroot()ed to this directory. This directory name starts with the "aw_" prefix because that is a special prefix and such directories will never be served by Antiweb through HTTP in case of an incorrectly configured HTML root. This convention dates back to Antiweb2. In any case, both of Antiweb's log files are owned and only readable by the logger user. The two log files are: #(ul #"<b>syslog</b> - System log messages. Always check this file first if something isn't working."# #"<b>axslog</b> - Access logs. All valid HTTP requests are recorded here."#) Workers pass log messages to the hub after which they are passed to the logger process. There are two ways to make the logger #(link "faq.html#REOPEN-LOG-FILES" "reopen its log files")."#
)
#"There is one <b>worker.conf</b> file per worker process. These files can live anywhere but a good place is in the <b>/var/aw/</b> hub directory. They should not be owned (or writeable) by any user that a worker or hub runs as."#
#"Every worker that uses #(link "worker.html#GZIP" "gzip content encoding"), #(link "awp.html" "Anti Webpages"), #(link "worker.html#JSMIN" "javascript minification") or #(link "worker.html#CSSMIN" "CSS minification") must have a #(link "faq.html#CACHE" "cache directory"). This directory must be owned by the user the worker runs as. No other users should have write access to this directory. Cache directories should never be in /tmp/ and should never have sticky bits."#
)
(unicode "Unicode"
#"#(tip #"Although all data is internally stored as (and enforced to be) UTF-8, you can map static files to different charsets with the #(link "worker.html#MIME-TYPE" ":mime-type") parameter of the worker conf. Also, in CGIs you can send any mime-type you want."#)
Antiweb4 supports exactly one type of character data:
#(ul #"<b>UTF-8</b> encoded unicode code points."#)
All filenames must be UTF-8. The HTML content in #(link "awp.html" "Anti Webpages") is always UTF-8. Here are some technologies <b>NOT</b> supported:
#(ul "ASCII" "Latin-1" "UTF-16" "etc...")
The plan is to store user data in #(link "http://www.unicode.org/reports/tr15/" "Normalization Form C") (but this is not implemented yet).
"#
)
(awp "Anti Webpages"
#"We love #(link "http://www.perl.org" "Perl"). Anti Webpages are an attempt to bring the Perl spirit to the modern web and to make this style of programming extremely efficient. Anti Webpages are not idealist, they are pragmatic. The manual you are reading now is an Anti Webpage."#
(awp-guiding-principles)
#"See the #(link "awp.html" "Anti Webpages") section of the manual for more details."#
)
)
)
(page "install.html"
:title "Antiweb Manual: Installation"
:header #"<h1><u>Installing Antiweb</u></h1>"#
:inherit "index.html"
:content
(p #"The following steps outline the official Antiweb installation procedure. We recommend that you read the #(link "design.html" "Design of Antiweb4") page before you install Antiweb."#
(fieldset "Antiweb Installation Procedure"
(ol (p #"Install #(link "http://www.cons.org/cmucl/" "CMUCL") or #(link "http://clisp.cons.org/" "CLISP") or #(link "http://www.clozure.com/clozurecl.html" "ClozureCL") or #(link "http://www.sbcl.org/" "SBCL") (or #(link "faq.html#MULTIPLE-LISPS" "some combination of the above")). Also ensure you have perl, gcc, zlib, and all necessary #(link "faq.html#GCC-ERRORS" "header files") installed."#)
(p #"#(link "http://hoytech.com/antiweb/beta/" "Download Antiweb"), extract it, and cd into the Antiweb directory:"#
(pre #"$ tar zxf antiweb-X.tar.gz
$ cd antiweb-X"#))
(p #"OPTIONAL: Modify the build options at the top of build.lisp. Alternatively, create a #(link "faq.html#LOCAL-CONFIG" "local.lisp") file."#)
(p #"Build Antiweb. This depends on your lisp environment. For CMUCL, use this command:"#
(pre #"$ lisp -quiet -load build.lisp"#)
#"For CLISP, use this command"#
(pre #"$ clisp -q build.lisp"#)
#"For ClozureCL, use this command"#
(pre #"$ ccl64 -Q -l build.lisp"#)
#"For SBCL, use this command"#
(pre #"$ sbcl --noinform --load build.lisp"#)
#"When finished, the build script should inform you it has saved your lisp image."#)
(p #"Antiweb will not rudely scatter files around your filesystem without telling you. cd into the bin directory and review the install.sh script:"#
(pre #"$ cd bin
$ cat install.sh"#))
(p #"Once satisfied, become root and run the install script (make sure you are in the bin directory):"#
(pre #"$ su
Password:
# ./install.sh"#)
#"For information on the files that are installed, see #(link "design.html#FILESYSTEM" "filesystem")."#
;#"<i>If using CMUCL, you will now need to repeat the build and install process a second time (go back to step 4). This is because when your image is saved, the libantiweb32.so shared library must be available as a system library. For more details, see #(link "faq.html#CMUCL-LIMITATIONS" "this FAQ entry").</i>"#
)
(p #"Antiweb should now be installed. Next create a hub directory:"#
(pre #"# antiweb -skel-hub-dir /var/aw"#)
#"The hub directory you specified should have been created. OPTIONAL: You can now edit the created hub.conf file (ie <b>/var/aw/hub.conf</b>). You might do this to change the UIDs the hub and logger processes run as, or to change the ports or interfaces that Antiweb will listen on."#
)
(p #"You now need to create one or more worker conf files. They can be stored anywhere, but a good place is along with the hub.conf file in the hub directory:"#
(pre #"# antiweb -skel-worker-basic > /var/aw/worker.conf"#)
#"#(tip "-skel-worker-basic is just one of the possible worker skeletons. To see a list of all of them, run <b>antiweb</b> with no arguments.") You will now need to edit the created worker conf (ie <b>/var/aw/worker.conf</b>). At a minimum, you must specify the hub directory created in the previous step, the UID this worker should run as, the virtual hosts this worker should handle, and the location of the HTML root for this worker. For complete details on the config file format, see the #(link "worker.html" "worker conf file reference")."#
#"<b>IMPORTANT:</b> No conf files should ever be owned or writeable by a UID or GID that a hub, logger, or worker process runs as. The conf files don't even need to be readable to them (but a worker's current conf file is stored in memory so making it unreadable only prevents <i>other</i> workers from reading it.)."#
)
(p #"Finally, start the antiweb processes:"#
(pre #"# antiweb -hub /var/aw
# antiweb -worker /var/aw/worker.conf"#)
#"You may also want to ensure that these launch commands are run at start-up. They must be run by root."#
(ul #"If anything goes wrong, the first place to look is at the bottom of the syslog file (ie <b>/var/aw/aw_log/syslog</b>)."#)
)
))
)
)
(page "faq.html"
:title "Antiweb Manual: FAQ"
:header #"<h1><u>Frequently Asked Questions</u></h1>"#
:inherit "index.html"
:content
(sections
(crazy #"Antiweb is very different from other webservers. Are you guys crazy?"#
#"No. Well, maybe a little, but we aren't letting that stop us from building the best webserver ever. Before Antiweb4, we recommended the following servers:"# (ul (link "http://nginx.net" "nginx") (link "http://www.lighttpd.net" "lighttpd") (link "http://hcsw.org/awhttpd/" "awhttpd"))
#"These servers are good, but they don't take advantage of lisp, the greatest programming language in the world."#
)
(why-antiweb #"Why is it called Antiweb?"#
#"When the first generation of Antiweb was written, almost everybody was using process or thread per connection webservers. Rather than just follow what everyone else was doing, we were going to do our own thing and be the anti-web. So in 1999 we released awhttpd 2.0, an asynchronous select-based server. A couple years later, we released awhttpd 3.0, another select-based server that served us well for years."#
#"Today with servers like nginx and lighttpd, asynchronous servers are commonplace. But if you look closely at Antiweb you will notice that it is still quite different from most other servers. We like where we are going and hope you will too. (Note that we have nothing to do with #(link "http://port70.net/webless/antiweb.html" "any") #(link "http://www.virtueelplatform.nl/page/4224/en" "other") anti-webs.)"#
)
(platforms #"What platforms does Antiweb run on?"#
#"Tested platforms:"#
(ul
#"CMUCL/Linux 2.6/x86"#
#"CLISP/OpenBSD 4.3/x86"#
#"CLISP/Linux 2.6/x86"#
#"CMUCL/FreeBSD 7.0/x86"#
#"ClozureCL/Linux 2.6/x86-64"#
#"ClozureCL/FreeBSD 8/x86-64"#
#"SBCL/Linux 2.6/x86-64"#
)
#"#(link "http://www.fefe.de/nowindows/" "Please do not port Antiweb to proprietary unix or lisp environments")."#
)
(contact #"Where can I ask questions, report bugs, etc?"#
#"Please use the #(link "http://groups.google.com/group/antiweb" "Antiweb Google Group") for discussions about Antiweb. Acceptable topics include but are not limited to:"#
(ul #"Questions about installation/setup"# #"Bug reports"# #"Feature requests"#)
#"Security issues or other sensitive communications can be sent directly to #(link "http://hcsw.org/contact.php" "Doug Hoyte")."#
)
(license "What license does Antiweb use?"
#"Your rights to use and distribute Antiweb are protected under the terms and conditions of the #(link "http://www.gnu.org/licenses/gpl.html" "GNU GPL version 3")."#
(ul #"The manual.awp file is also covered by the GPL."#
#"Before accepting patches, the Antiweb project requires copyright assignment that allows us to relicense your modifications. You still keep full rights to your modifications and Antiweb will always be available under the GPL."#
)
)
(gcc-errors #"Why am I getting errors from gcc when compiling Antiweb?"#
#"Most likely you don't have all the header files installed. Some systems package header files separately from the libraries themselves. For example, on an Ubuntu machine you will need at least the following extra packages:"#
(pre #"$ sudo apt-get install libc6-dev zlib1g-dev"#)
)
(stats "How do I find out ...?"
#"If a process terminates unexpectedly, the first thing you should check is the syslog file:"#
(pre #"# tail /var/aw/aw_log/syslog"#)
#"The fastest and most reliable way to get info about what an Antiweb process is currently doing or how it is configured is to use the launch script's <b>-stats</b> command. For example, to get the stats of a running hub, run this command (as root):"#
(pre #"# antiweb -stats /var/aw"#)
#"Similarly, to get the stats of a worker process:"#
(pre #"# antiweb -stats /var/aw/worker.conf"#)
(ul #"When #(link "faq.html#ATTACH" "attached") to a process you can also get this info by evaluating <b>(stats)</b>."#)
#"For info on the memory consumption of an Antiweb process, use the <b>-room</b> command. This will give you information about the lisp managed heap, as well as Antiweb's special conn and ioblock data-structures:"#
(pre #"# antiweb -room /var/aw/worker.conf"#)
)
(local-config #"How can I change Antiweb build/install options?"#
#"As mentioned in #(link "install.html" "the installation instructions"), there are several variables that can be changed at the top of <b>build.lisp</b> that will change how Antiweb is built and installed. Although you can change the build options directly in this file, the recommended way is to create a <b>local.lisp</b> file in the Antiweb tarball directory. This way, when you upgrade Antiweb you can simply copy your existing <b>local.lisp</b> file into the new Antiweb directory."#
#"If it exists, <b>local.lisp</b> will be #(link "http://www.lispworks.com/documentation/HyperSpec/Body/f_load.htm" "load")ed before Antiweb is built. Antiweb build options can thus be changed by using the Common Lisp <b>setq</b> form."#
#"Here are some examples of <b>local.lisp</b> files:"#
(ul
#"Install Antiweb into the /usr/local/ prefix instead of /usr/: #(pre #"(setq aw-bin-dir "/usr/local/bin")
(setq aw-lib-dir "/usr/local/lib")"#)"#
#"Compile Antiweb with your system's default BerkeleyDB (requires version 4.6+): #(pre #"(setq aw-use-bdb t)"#)"#
#"On a 64 bit machine, compile a 32 bit version of Antiweb when compiling with CMUCL, but a 64 bit version when compiling with any other lisp: #(pre #"#+cmu (setq aw-extra-cflags "-m32")"#) Note: Make sure you have 32 bit libc and zlib libraries available. On a Debian x86-64 machine try this command: #(pre #"# apt-get install ia32-libs libc6-dev-i386 lib32z1-dev"#)"#
#"On a 64 bit machine, compile a 32 bit version of Antiweb using a specific 32 bit BerkeleyDB install: #(pre #"(setq aw-use-bdb t)
(setq aw-extra-cflags
"-m32 -L/usr/local/BerkeleyDB.4.7/lib/ -I/usr/local/BerkeleyDB.4.7/include/")"#)"#
)
)
(cache #"What is the cache directory for?"#
#"Workers can optionally have a <b>cache directory</b>. The worker conf has a #(link "worker.html#CACHE" "cache") xconf you need to enable if you want to use certain features:"#
(ul
#"When #(link "worker.html#GZIP" "gzip compression") is enabled, files of the appropriate extension and size are gzip compressed and stored to the cache the first time they are read, and again if their modification times change. HTTP clients that indicate they can handle gzip encoding are served the compressed data as regular static files."#
#"Every #(link "awp.html" "Anti Webpage") gets its own directory in the cache. After the page is compiled, it is stored and served out of the cache (along with a gzipped copy) until the modification time on the .awp file changes. The Anti Webpage will then be recompiled into the cache."#
#"For Anti Webpages that contain code in the form of AJAX callbacks, a lisp file is stored into the cache and compiled into a "fast load" file (.x86f or .fasl or .fas or .lib or .lx64fsl or ...). This file is loaded on the first request for the Anti Webpage, and is compiled and loaded again when the .awp file's modification time changes."#
#"When #(link "worker.html#JSMIN" "javascript minification") and/or #(link "worker.html#CSSMIN" "CSS minification") is enabled, javascript and/or CSS files will be minified, gzip compressed, and stored in the cache directory."#
)
)
(reloading-worker-conf #"Do I need to restart a worker process to reload a worker conf file?"# #"No. Antiweb is designed so that you never need to restart any of its processes. To reload a worker conf file, even if the worker is chroot()ed and can no longer access the file, run this command (as root):"# (pre #"# antiweb -reload /var/aw/worker.conf"#) (ul #"The worker will not reset itself in any way during a reload. Even connections currently being sent files and keepalive connections will not be closed."# #"If an error is detected while installing the new conf file, the worker will not install it and will continue with the old configuration."# #"If an error is encountered in an HTTP dispatch with the new conf file, Antiweb will kill the worker."#))
(adding-listeners #"Do I need to restart the hub to add new listeners?"#
#"No. You can start listening on a port in a supervisor process with root privileges and then transfer the listening socket into a running hub. To see the interfaces/ports currently being listened on, use the #(link "faq.html#STATS" "-stats") command:"#
(pre #"# antiweb -stats /var/aw
...
Listening on:
0.0.0.0 80
:: 80
..."#) #"The above stats output means the hub is listening on all IPv4 and IPv6 interfaces for connections to port 80. This command adds a new listener for port 800:"#
(pre #"# antiweb -add-listener /var/aw 0.0.0.0 800
OK"#) #"And this closes a listener:"#
(pre #"# antiweb -close-listener /var/aw 0.0.0.0 800
OK"#))
(attach #"Can I attach to a running process and give it lisp commands?"#
#"Yes, as long as you have root privileges you can <b>attach to</b> or <b>supervise</b> any hub or worker process through the hub's unix socket. Note that root privileges are dropped once you have attached to the target process. For example, to attach to the hub process, run this command (as root):"# (pre #"# antiweb -attach /var/aw"#) #"Similarly, to supervise a worker process, run this command (as root):"# (pre #"# antiweb -attach /var/aw/worker.conf"#) #"In both cases, you will be shown the output of the stats command run on that process, and then will be given a * prompt: #(pre #"[Antiweb: Attached to HUB] *"#) #(pre #"[Antiweb: Attached to worker HOYTECH] *"#) This is similar to a lisp #(link "http://en.wikipedia.org/wiki/REPL" "REPL"). The *, **, ***, +, ++, and +++ special variables are stored in the process you attached to and are unique per REPL session. The expressions are evaluated by the process being supervised. Although all Antiweb processes only have a single thread of execution, <b>a supervised process will continue to function normally while being supervised.</b>"#)
(reopen-log-files #"How can I get the hub to reopen its log files?"#
#"First of all, never send an Antiweb process a HUP signal. All communication with Antiweb is done via the <b>hub.socket</b> unix socket."#
#"To reopen the hub's log files, #(link "faq.html#ATTACH" "attach") to the hub process and evaluate <b>(reopen-log-files)</b>."#
#"For example, mv the log files to a new destination:"#
(pre #"# mv /var/aw/aw_log/* /storage/dir/"#)
#"Attach to the hub:"#
(pre #"# antiweb -attach /var/aw"#)
#"Then evaluate the <b>(reopen-log-files)</b> form at the Antiweb prompt:"#
(pre #"[Antiweb: Attached to HUB] *
(reopen-log-files)
T"#)
#"This will send a reopen-log-files message to the logger process, causing it to close and reopen its log file descriptors."#
#"When finished, press control-d or use the <b>(quit)</b> command:"#
(pre #"[Antiweb: Attached to HUB] *
(quit)
# "#)
#"Note that this does not quit the process you are attached to. To do that, either use the <b>-kill</b> command or evaluate <b>(progn (quit))</b> when attached."#
#"Alternatively, especially when doing all this from a script, you might choose to use the <b>-reopen-log-files</b> command:"#
(pre #"# antiweb -reopen-log-files /var/aw"#)
)
(install-hub-rewrite-host #"Can I manually route requests to workers?"#
#"Yes, you can use an install-hub-rewrite-host xconf in the hub.conf file. This option should be given a lambda form. This lambda form accepts one argument: the entire HTTP request header as a string. The lambda form should return a virtual host that is being handled by a worker. If nil is returned, the virtual host requested in the Host header will be used as usual. Example:"#
(pre #";; Send hosts like jimmy.user.example.com to user-handler.example.com
(install-hub-rewrite-host
(lambda (header)
(if (#~m/\r\nHost: [\w-]+[.]user[.]example[.]com\r\n/i header)
"user-handler.example.com")))
"#)
(ul
#"This xconf is most useful in combination with the #(link "worker.html#HANDLE-ALL-HOSTS" ":handle-all-hosts") option in a worker conf handler."#
#"If you need to install a new rewrite function without restarting the hub, #(link "faq.html#ATTACH" "attach") to the hub and evaluate the install-hub-rewrite-host form."#
)
)
(erlang #"Was Antiweb inspired by Erlang?"# #"Not directly, no. Hoytech engineers have never looked at any Erlang implementations and have never programmed in Erlang. But we like what we hear. Antiweb's philosophy is similar to Erlang's in several respects:"# (ul #"If an unexpected condition is encountered, die as quickly and loudly as possible. Never try to clean-up or recover. A process cannot do that because it has failed. Some other process that hasn't failed will clean-up after it."# #"Threads (pre-emptively scheduled shared memory processes) are used nowhere. All inter-process communication is done by explicit message passing."#)
)
(multiple-lisps #"Can I use multiple lisp environments at the same time?"# #"#(tip #"Caution: CLISP's readline can interfere with pasting in lisp forms. You can disable readline with the <b>-noreadline</b> option (must appear before the real command you are running). See #(link "faq.html#CLISP-LIMITATIONS" "CLISP Limitations")."#)Yes. Antiweb's "wire protocol" is independent of the lisp environment in use. #(ul #"The #(link "faq.html#STATS" "-stats") command lets you see the Common Lisp environment and version of any Antiweb process."# #"You can #(link "faq.html#ATTACH" "attach to") a CLISP process with CMUCL and vice-versa (except be careful of cross-platform problems like backquote expansions)."# #"If you have a 64 bit machine, you can run some Antiweb processes in 64 bit mode and others in 32 bit mode. See #(link "faq.html#LOCAL-CONFIG" "the local.lisp FAQ entry") for configuration examples."#)"# #"To install different lisp environments, simply follow the #(link "install.html" "installation instructions") for each of the desired lisp implementations. The antiweb launch script will default to using the <b>most recently installed</b> lisp environment. However, you can force a particular lisp environment with the -cmu, -clisp, or -ccl switches. For example:"# (pre #"# antiweb -cmu -hub /var/aw"#) #"or"# (pre #"# antiweb -clisp -worker /var/aw/worker.conf"#) #"Or if you want a REPL on a ClozureCL with all the Antiweb functions loaded:"# (pre #"$ antiweb -ccl -repl"#))
(worker-startup-time #"Why does it take a few seconds to start a worker?"# #"<b>Antiweb compiles parts of the system only once the worker's conf is loaded</b>. This adds a small compilation delay when starting worker processes. There are many advantages to having the compiler available at run-time, including more efficient HTTP dispatches that omit unused features and the ability to add new modules to workers (or shadow existing modules) without restarting them."# #"You usually will only notice this when using a slow computer, complicated config files, and a lisp environment with a slow compiler (like CMUCL)."#)
(reload-attack #"Can a compromised worker wait until I -reload to steal vhosts?"#
#"In theory it it possible for a compromised worker to "lie and wait" for you to -reload (which unlocks the worker process's connection to the hub) and then feed in extra unwanted vhosts for it to listen on. You should always <b>check the hub status with the #(link "faq.html#STATS" "-stats") command</b> after a -reload to make sure this hasn't happened (make sure the worker has the right vhosts and is locked). The effectiveness of this attack is diminished by the following two points:"#
(ul #"A worker cannot do this to steal vhosts being listened on by other workers. If a worker tries this, the hub will instantly cut it off (and log what happened)."# #"In no situations does this attack allow log messages to be intercepted."#)
)
(restarting-crashed-workers #"Will Antiweb automatically restart a crashed worker/hub?"#
#"No. Whether to do this or not is a <b>policy decision</b>, not a technical one."#
(ul #"A simple way to ensure that a worker is running is to try starting it with the <b>-check-worker</b> switch: #(pre #"# antiweb -check-worker /var/aw/worker.conf"#) The worker will only be started if it currently isn't running. <b>-check-worker</b> is identical to <b>-worker</b> except it will not add a log message in syslog if the worker was already running. For example, adding this line to your crontab will check that a particular worker is running every 15 minutes: #(pre #"0,15,30,45 * * * * /usr/bin/antiweb -check-worker /var/aw/worker.conf"#)"# #"Once correctly configured, an Antiweb process should never crash. If it does, check the syslog file and please #(link "http://groups.google.com/group/antiweb" "let us know") in as much detail as possible what happened. You may have discovered a serious bug in Antiweb."#)
)
(etag-hash #"Can I stop the Etag header from leaking inode numbers?"#
#"Yes. You can use #(link "worker.html#ETAG-HASH" "Etag hashing"). This concatenates the Etag that is normally generated with a secret key, hashes with the SHA1 algorithm, and uses the result as the Etag."#
#"OpenBSD #(link "ftp://ftp.openbsd.org/pub/OpenBSD/patches/3.2/common/008_httpd.patch" "made a similar change to httpd") in version 3.2. They store the secret key in the file logs/etag-state but Antiweb stores it in the worker conf file <b>which should of course be stored outside of the HTML root</b>. Good secret keys include Antiweb session IDs:"#
(pre #"$ antiweb -repl
* (aw-n-bit-session-id 128)
"8odxf2wrq7tbehjkwvp0h7vqu"
"#)
#"<b>aw-n-bit-session-id</b> will use /dev/arandom or /dev/urandom to seed the #(link "http://burtleburtle.net/bob/rand/isaacafa.html" "ISAAC random number generator") and return a random n-bit value in base 36. 128 bits is fine."#
#"Now add the following to a handler in your worker conf file:"#
(pre #" :etags :etag-hash "8odxf2wrq7tbehjkwvp0h7vqu""#)
#"Hoytech does not use Etag hashing on our servers so you can snoop on our inodes if you want. The only plausible attack seems to involve NFS (Network File System). If you use NFS on your webserver, enable Etag hashing. To avoid the minor overhead, don't. Antiweb is all about choice."#
)
#+nil (continuations #"Does Antiweb use continuations?"# #"No. Hoytech's R&D team has never read any convincing arguments that continuations are useful for web development. Instead, continuations pose a number of determinism/reliability #(link "http://www.nhplace.com/kent/PFAQ/unwind-protect-vs-continuations-overview.html" "issues") that Antiweb avoids by not using them. Thankfully, Common Lisp does not force the burden of continuations upon application developers seeking to build reliable systems. <b>This is a valuable feature of Common Lisp.</b>"#)
(linger #"Why does Antiweb linger on HTTP sockets?"#
#"When terminating an HTTP connection with a "Connection: close" HTTP header, Antiweb will shutdown() the write direction of the socket and continue to read and discard data from the socket for up to 2 seconds. This is <b>required</b> for HTTP/1.1 persistent connections. See #(link "http://httpd.apache.org/docs/1.3/misc/fin_wait_2.html#appendix" "here") for more details."#
#"Note that Antiweb's maximum linger period (2 seconds) is much shorter than Apache's 30 seconds. Also, we don't use a SIGALRM. Instead, lingering sockets are tracked with Antiweb's regular connection state machine. We believe this is correctly implemented but please let us know if you encounter problems."#
)
(timeout-clustering #"What is timeout clustering?"#
#"This is an experimental optimisation in Antiweb4 that so far we have had good results with. The idea is that for many types of timeouts, including timing out keepalive connections, it doesn't really matter if they occur plus or minus a second or so. Antiweb takes advantage of this by scheduling the timeouts on a second boundary. So instead of the following sequence of syscalls:"#
(pre #"kevent(200ms)
close(socket)
kevent(200ms)
close(socket)
kevent(200ms)
close(socket)
kevent(200ms)
close(socket)
kevent(200ms)
close(socket)
kevent()
"#) #"Antiweb does:"#
(pre #"kevent(1000ms)
close(socket)
close(socket)
close(socket)
close(socket)
close(socket)
kevent()
"#) #"Notice how there are four fewer calls to kevent() with clustering. In addition to making fewer system calls, we also suspect this is better for power consumption."#
)
(ssl-proxy #"Does AW support SSL and/or reverse proxying?"# #"Not yet. Currently we recommend reverse proxying SSL connections to Antiweb with #(link "http://nginx.net" "nginx"). Eventually Antiweb will be both SSL capable and able to reverse proxy SSL."# #"Here is an nginx conf file that can be used for reverse proxying SSL (probably includes some things you don't need):"#
(pre #"
user nginx;
worker_processes 1;
events {
worker_connections 1024;
}
http {
keepalive_timeout 65;
gzip on;
gzip_proxied any;
gzip_types application/x-javascript;
server {
listen 443;
server_name example.com;
ssl on;
ssl_certificate /etc/ssl/certs/example.crt;
ssl_certificate_key /etc/ssl/private/example.key;
location / {
proxy_buffer_size 256k;
proxy_buffers 8 256k;
proxy_pass http://example.com;
proxy_set_header X-Real-IP $remote_addr;
}
}
}
"#)
#"In order to log the IP addresses of clients, you should use the #(link "worker.html#ACCEPT-X-REAL-IP-FROM" ":accept-x-real-ip") xconf for all workers that handle proxied connections."#
)
(cmucl-limitations #"Are there any known limitations with CMUCL?"#
(ul
;#"CMUCL will always load the libantiweb32.so library from a system library directory, even if Antiweb tells it to load a freshly compiled version from the bin/ directory. If you add a new function to libantiweb.c, you will need to delete the library from its system location prior to recompiling Antiweb. This is only a problem during development and when upgrading Antiweb. We are looking into a workaround for this."#
#"CMUCL mmap()s a large amount of address space which can stop it from running on certain VPS systems. Note that most of this address space doesn't map to real memory. The <b>-dynamic-space-size</b> doesn't seem to reduce the size of the mmap() unfortunately. SBCL does this, probably CMUCL can too."#
)
)
(clisp-limitations #"Are there any known limitations with CLISP?"#
(ul
#"CLISP's readline support can interfere with pasting in lisp forms (S-expressions). When attaching to a process, you may want to turn it off: #(pre #"# antiweb -noreadline -attach /var/aw/worker.conf"#) If you leave readline on, be aware that symbol completion will only find symbols in the supervisor process, not the process you have attached to."#
#"The filenames of #(link "design.html#CONFS" "conf files") (like .awp files) can only contain a subset of UTF-8. They can't include the * or ? code points because there seems to be #(link "http://osdir.com/ml/lisp.clisp.general/2003-04/msg00101.html" "no way") to open or read such files in CLISP. This doesn't affect static files or CGI scripts because Antiweb uses its own filesystem interface for those."#
#"On older versions of CLISP, certain HTTP headers will be terminated with only a newline, not a carriage-return + newline. Use CLISP 2.42 or newer."#
#"Some versions of CLISP seem to ignore the -repl switch so Antiweb's -repl command won't work with them. 2.42 seems to work but 2.44 doesn't."#
;#"If you are used to CMUCL's handling of <b>top level setq</b>, be aware that CLISP does this differently. In Antiweb, this will be normalised to the CMUCL behaviour soon."#
#"If you use <b>-nodaemon</b> and press control-c to interrupt an Antiweb process, you get a functioning debugger REPL (just like CMUCL) but resuming the process when you are done debugging is problematic (unlike CMUCL, where it works perfectly). We are still tracking this issue down."#
#"<b>(lisp-implementation-version)</b> returns different information depending on whether it is a worker process or the hub process (you can observe this with -stats). We have no idea why this happens."#
)
)
(ccl-limitations #"Are there any known limitations with ClozureCL?"#
(ul
#"ClozureCL/Linux/x86 seems to have some issues with FFI and is not currently recommended."#
)
)
(sbcl-limitations #"Are there any known limitations with SBCL?"#
(ul
#"On SBCL, if you build Antiweb as a non-root user, install with sudo, and then try to launch Antiweb when logged in as root, SBCL refuses to start and puts you into the LDB debugger. Until we solve this, when using SBCL make sure if you build Antiweb as a user that you start Antiweb as that user, sudoing for root privileges when necessary."#
#"SBCL thread support has severe issues. Antiweb doesn't use threads but be very careful if you incorporate threaded libraries."#
)
)
(skillz #"Can you teach me l33t k0ding skillz?"# #"Yes, yes we can. Please refer to Doug Hoyte's book #(link "http://letoverlambda.com" "Let Over Lambda") for details on many of the coding techniques used in Antiweb4."#)
)
)
(page "worker.html"
:title "Antiweb Manual: Worker Conf File Reference"
:header #"<h1><u>Worker Conf File Reference</u></h1>"#
:inherit "index.html"
:content
(p
#>END
Every worker process must have a worker conf file. See the #(link "install.html" "installation instructions") for step-by-step instructions on setting up a worker. The most important elements in a worker conf are the #(link "#HANDLER" "handler") elements. #(tip #"There are several worker conf skeletons available. See a list of them by running <b>antiweb</b> with no arguments."#)Every virtual host that is to be handled must appear in exactly one handler in all your worker confs. If a vhost exists in two separate worker confs, the latest worker to register the duplicate vhost with the hub is killed (see syslog). If a vhost exists in two separate handlers in the same worker, only the first handler will handle the vhost.END
#"Here is a simple worker conf:"#
(pre #"
(worker example)
(hub-dir "/var/aw")
(max-fds 32767)
(uid "my-user")
(handler
:hosts ("localhost" "127.0.0.1"
"example.com" "www.example.com")
:root "/var/www/example.com"
:index ("index.html")
:etags
:cgi (pl)
)
"#)
(sections
(worker "worker" "Unique name for the worker process." (pre "(worker name)") (ul "Cannot be changed without restarting worker." "This xconf is required."))
(hub-dir "hub-dir" "Absolute path to the hub directory that this worker should attempt to connect to." (pre #"(hub-dir "/var/aw")"#) (ul "Cannot be changed without restarting worker." "This xconf is required." "Because worker processes connect to the hub before a chroot, this option is unaffected by chroot."))
(uid "uid" "User whose UID and GID the worker should drop privileges to. Can be either the name of a user or UID (in which case the GID is assumed to be the same and no user lookup is done)." (pre #"(uid "my-user")"#) (pre "(uid 20001)") (ul "Cannot be changed without restarting worker." "This xconf is required."))
(max-fds "max-fds" "Before dropping privileges, set the maximum open file descriptor limit." (pre "(max-fds 32768)") (p (tip #"To see how many file descriptors any process is limited to, along with how many it is currently using, use #(link "faq.html#STATS" "-stats"). The number of open descriptors is an estimate because there are a few open but unaccounted for descriptors not part of Antiweb's connection data structures."#) (ul "Cannot be changed without restarting worker." "This xconf is optional but highly recommended if you anticipate moderate load and/or many keepalive connections." #"On some systems you may need to raise a system-wide process descriptor limit for this option to be effective. For example, on OpenBSD use this sysctl command: #(pre #"# sysctl kern.maxfiles=32768"#)"#)))
(chroot "chroot" "This xconf is optional. If and only if it is present, the worker will chroot() to this directory before dropping privileges. Workers always chdir() to / (even if they don't chroot)." (pre #"(chroot "/absolute/path/to/chroot/to")"#) (ul "Cannot be changed without restarting worker." "If you use chroot note that most of the other paths in the worker conf will need to be relative to this new root (but still must begin with a slash)." #"Whether you should chroot your workers or not is a <b>policy decision</b>. If you chroot a worker, be aware that you will need to set up a "fake root" to run most CGI scripts."#))
(cache "cache" #"Absolute path to the cache directory for this worker. For more details on the cache, see #(link "faq.html#CACHE" "this FAQ entry")."# (pre #"(cache "/absolute/path/to/cache")"#) (ul #"The cache directory must be owned by the worker's UID. No other user should be able to write to the cache directory and it should never be in /tmp and should never have a sticky bit."# "If the worker is choot()ed, the cache directory must be inside the chroot() and the given path must be relative to the new root." "Although providing a cache directory is optional, it is required to use gzip content encoding, javascript/CSS minification, or Anti Webpages." "Delete everything in the worker's cache directory before performing major directory re-organisations. The worker may die (details always logged in syslog) if what used to be a directory is now a file, etc."))
(keepalive "keepalive" "Amount of time before closing an inactive HTTP keepalive connection. The parameter is a number followed by one of these unit specifiers: s, m, h, or d." (pre "(keepalive 65 s)") (ul "The default, 65 seconds, is slightly longer than the keepalive time of most browsers (same as nginx)."))
(eval-every "eval-every" #"A recurring timer event. Multiple eval-every events can appear in the same worker conf (potentially with different time values). The parameters are a number followed by one of these unit specifiers: s, m, h, or d, and the lisp forms to evaluate in sequence."#
(pre #"(eval-every 6 h
(gc))"#) (ul "Designed for periodically flushing expired session IDs etc." "The event does not trigger on worker start-up, but only after its first time period has elapsed." #"A #(link "faq.html#RELOADING-WORKER-CONF" "-reload") will reset the timers."#))
(handler "handler"
"The handler xconf tells Antiweb where your files are and how to serve them. Multiple handler xconfs can exist in the same worker conf file. The simplest possible handler is a basic mapping of a virtual host to an HTML tree:"
(pre #"(handler
:hosts ("localhost")
:root "/absolute/path/to/root"
)"#)
#"This section outlines the many handler parameters. All parameters are optional, except for :hosts and <b>one of</b> :root or :simple-vhost-root."#
(sections
(hosts ":hosts" "Which virtual hosts should be registered with the hub." (pre #" :hosts ("example.com" "www.example.com" "www.example.com:8080")"#) (ul "This parameter is required otherwise the hub will not route any connections to this handler." "Make sure you specify all hosts this worker should handle, including sub-domains, ports, IPv4 and IPv6 addresses, etc." "Two separate handlers <b>cannot</b> both handle the same host (only the first defined will get connections)."))
(handle-all-hosts ":handle-all-hosts" "Handle hosts even if they aren't specified in :hosts." (pre #" :handle-all-hosts"#) (ul #"A handler that uses this option should appear last in the worker conf because no handlers specified later in the file will have a chance to handle the request."# #"This option is only useful when combined with the #(link "faq.html#INSTALL-HUB-REWRITE-HOST" "install-hub-rewrite-host") xconf in hub.conf."#))
(root ":root" "Absolute path to the HTML tree that should be served." (pre #" :root "/absolute/path/to/root""#) (ul "One of (but not both) a :root or a :simple-vhost-root argument is required." "If the worker process is chroot()ed, it must be the absolute path from the new root, not the original root."))
(simple-vhost-root ":simple-vhost-root" "Absolute path to a directory containing HTML trees named by the virtual hosts being served. The names of these child directories must be names of registered vhosts for this worker." (pre #" :simple-vhost-root "/absolute/path/to/root""#) (ul "One of (but not both) a :simple-vhost-root or a :root argument is required." "If the worker process is chroot()ed, it must be the absolute path from the new root, not the original root." "The mere fact that a directory exists is not enough to register a virtual host. Make sure that all hosts are registered in the :hosts parameter." "The directory names should be the lowercase versions of the virtual hosts." "You can use symlinks so that multiple virtual hosts are mapped to the same directory." #":simple-vhost-root is for #(link "http://hcsw.org/awhttpd/" "Antiweb3") and #(link "http://trac.lighttpd.net/trac/wiki/Docs%3AModSimpleVhost" "lighttpd") compatibility."#))
(rewrite ":rewrite" #"#(tip #"Although :rewrite can do much more than just rewrite request paths, it is named in recognition of Apache's #(link "http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html" "mod_rewrite")."#):rewrite lets you compile Common Lisp code directly into the worker's HTTP dispatch function. You can have as many :rewrite parameters as you want. They are evaluated in sequence or until the connection is <b>redirected</b> or until <b>(done-rewrite)</b> or <b>(keepalive)</b> is evaluated. The rewriting happens before any other request processing is done. Here is a simple example that will redirect domains that start with www to their no-www versions:"#
(pre #"
:rewrite (if-match (#~m/^www[.](.*)/ http-host)
(redir 301 "http://~a~a" $1 http-path))
"#)
#"When redirecting a connection to a different worker or a different server altogether, you might choose to redir-close which tears down HTTP 1.1 keepalive connections:"#
(pre #"
:rewrite (if-match (#~m/^www[.](.*)/ http-host)
(redir-close 301 "http://~a~a" $1 http-path))
"#)
#"Supported codes for :redir and :redir-close are:"# (ul #"301 - Moved Permanently"# #"302 - Found"# #"307 - Temporary Redirect"#)
#"There are many variables that you can access and even modify before the request is handled. Here is a partial list:"#
(ul #"http-method - The requested HTTP method. Always the symbol GET or the symbol POST."#
#"http-ver - The HTTP protocol version in use. Either "0.9", "1.0", or "1.1"."#
#"http-path-encoded - The path portion of the URL before URL decoding."#
#"http-path - The decoded path portion of the URL. This will always begin with a / character. This will include the path-info portion of the path."#
#"http-args - The URL encoded URL arguments (portion of URL after the ? character, not including the ?)."#
#"http-host - The lowercase version of the virtual host requested by the client."#
#"$u-anything-you-like - These are #(link "http://letoverlambda.com" "sub-lexical") variables. You can use them for anything, including sharing values between rewrite rules or other Antiweb modules. They are initially bound to nil."#
#"$h-any-http-header - These are also sub-lexical variables. You can use them to access any HTTP header. To be honest, they are regular expressions. $h-referr?er will contain the contents of a Referer or Referrer header line (whichever appears first)."#
)
#"The form <b>add-header-to-response</b> adds an HTTP header to any successful response:"#
(pre #"
:rewrite
(if-match (#~m|^/logo[.]png$| http-path)
(add-header-to-response "Cache-Control: public, max-age=3600, must-revalidate"))
"#)
#"Here is how to use :rewrite to add a virtual URL <b>/stats.html</b> that will display stats and room info about a worker process:"#
(pre #"
:rewrite
(if-match (#~m|^/stats[.]html$| http-path)
(let ((body (format nil #"<html><title>Antiweb Worker Stats</title>
<h1>Antiweb Worker Stats</h1>
<h2>-stats</h2><pre>~a</pre><br>
<h2>-room</h2><pre>~a</pre></html>"#
(stats) (aw-room))))
(send-http-response-headers 200
("Content-Type" "text/html; charset=utf-8")
("Content-Length" "~a" (length body)))
(send-raw body)
(keepalive)))
"#)
#"The above is a low-level way of building an HTML response, sending it to the client, and keeping the connection alive (HTTP/1.1 clients only). Another way this could have been written is with the <b>send-html-response-and-keepalive</b> macro:"#
(pre #"
:rewrite
(if-match (#~m|^/stats[.]html$| http-path)
(send-html-response-and-keepalive
#"<html><title>Antiweb Worker Stats</title>
<h1>Antiweb Worker Stats</h1>
<h2>-stats</h2><pre>"#
(stats)
#"</pre><br><h2>-room</h2><pre>"#
(aw-room)
#"</pre></html>"#))
"#)
#"Soon there will be more :rewrite recipes available here, in the #(link "faq.html" "FAQ"), and elsewhere."#
(ul #"<b>Never paste something you don't understand into a conf file.</b>"#)
)
(default-mime-type ":default-mime-type" "Sets the default MIME type for files with unrecognised extensions (or no extensions at all)." (pre #" :default-mime-type "text/plain; charset=utf-8""#))
(mime-type ":mime-type" "A two element list. The first element is a file extension and the second is the MIME type and optionally charset to map the extension to." (pre #" :mime-type (htm "text/html; charset=iso-8859-1")"#) (ul "You can over-ride a default Antiweb MIME type with this parameter." "The file extensions are case-insensitive." #"There can be multiple :mime-type options in a handler. The first one that matches is used."#))
(index ":index" "A list of index files to be searched for when a directory is requested." (pre #" :index ("index.html" "index.pl")"#) (ul "The first index file found is the one used (left-to-right)." "A 404 Not Found is served if no index is found (unless :dir-listings are enabled)."))
(dir-listings ":dir-listings" "If no index file is found, this option causes an HTML listing of the files in a directory to be served instead of a 404." (pre #" :dir-listings"#) (ul "Directory listings always tear down persistent HTTP connections to prevent recursive crawlers from taking advantage of HTTP pipelining."))
(download-resuming ":download-resuming" "Enables the sending of 206 Partial Content if the client indicates it already has a prefix range of a static file." (pre #" :download-resuming"#) (ul #"No other byte-ranges are supported."#))
(etags ":etags" "Enables the sending of etag (entity tag) HTTP headers when serving static files. Clients that cache the files are sent 304 Not Modified responses if they re-request the file and it hasn't changed." (pre #" :etags"#) (ul #"Antiweb uses the standard(ish) etag format "INODE-SIZE-MTIME" (in hex)."# #"Last-Modified is never sent by Antiweb."#))
(etag-hash ":etag-hash" "Uses the SHA1 algorithm to disguise the Etag generated with :etags to avoid exposing your inode numbers. Requires a secret key value." (pre #" :etags :etag-hash "key value goes here""#) (ul #"You must also enable the :etag xconf for this to work."# #"See #(link "faq.html#ETAG-HASH" "this FAQ entry") for more information."#))
(accept-x-real-ip-from ":accept-x-real-ip-from" "A trusted IP address that is permitted to set a connection's IP address with the X-Real-IP header. This is so that the client's IP address will be properly logged when reverse proxying is used." (pre #" :accept-x-real-ip-from "127.0.0.1""#) (ul #"#(link "faq.html#SSL-PROXY" "This FAQ entry") describes an example nginx configuration that sends this header when reverse proxying SSL connections."#))
(gzip ":gzip" "A list of file extensions for files that should be gzip compressed and stored in the worker's cache directory and then served as static files. Only clients that indicate compression support are sent the compressed versions." (pre #" :gzip (html txt css js)"#) (ul "The gziped copies are updated when the original file's modification time (mtime) changes." "There is no point compressing formats like png and mp3 because they are already compressed."))
(gzip-size-range ":gzip-size-range" #"A list of two elements. The first is the minimum file size (in bytes) to compress and store in the cache. The second is the maximum file size (also in bytes)."# (pre #" :gzip-size-range (256 1000000)"#) (ul "This parameter is optional. If :gzip is used without :gzip-size-range, sensible defaults are used."))
(jsmin ":jsmin" #"Enables "javascript minification". Files that end in .js in your HTML root will be minified, gzip compressed, and stored in the cache. Minification removes comments, unnecessary whitespace, etc from your javascript files for more efficient use of bandwidth and faster loading pages."# (pre #" :jsmin"#) (ul #"When the modification time (mtime) of the original .js file changes, the file will be re-minified on the next request."# #"jsmin.lisp was written by Ury Marshak for ht-ajax. It is based on an algorithm by #(link "http://javascript.crockford.com/jsmin.html" "Douglas Crockford")."# #"Invalid javascript files, such as ones that forget to close comments, are not minified. Instead, the original files are sent to clients."# #":js-main fields in AWP files have their contents minified when the AWP file is compiled."#))
(cssmin ":cssmin" #"Enables "CSS minification". Files that end in .css in your HTML root will be minified, gzip compressed, and stored in the cache. Minification removes comments, unnecessary whitespace, etc from your CSS files for more efficient use of bandwidth and faster loading pages."# (pre #" :cssmin"#) (ul #"When the modification time (mtime) of the original .css file changes, the file will be re-minified on the next request."# #"cssmin is based on #(link "http://www.thinkvitamin.com/features/webapps/serving-javascript-fast" "an algorithm by Cal Henderson")."# #":css fields in AWP files have their contents minified when the AWP file is compiled."#))
(fast-1x1gif ":fast-1x1gif" "Adds a URL that serves a 1 pixel by 1 pixel transparent gif." (pre #" :fast-1x1gif "/1x1.gif""#) (ul "The gif and its pre-generated HTTP headers are served directly from memory. This eliminates a stat call, generating the headers, opening the file, reading from the file, and closing the file." #"The 43 byte gif file is from #(link "http://wiki.codemongers.com/NginxHttpEmptyGifModule" "nginx")."#))
(fast-files ":fast-files"
#"A list of URLs that should be served directly from a memory cache:"#
(pre #" :fast-files ("/favicon.ico" "/robots.txt")"#)
(ul "After they are first read, these files and their pre-generated HTTP headers are served directly from a cache in memory. This eliminates a stat call, generating the HTTP headers, opening the file, reading from the file (or mmap()+munmap()ing it), and closing the file."
#"When the worker conf file is #(link "faq.html#RELOADING-WORKER-CONF" "-reload")ed, the memory cache is flushed and the files are then re-loaded from the filesystem on-demand. Alternatively, to avoid the slight delay when you re-compile your HTTP dispatch function, you can evaluate <b>(flush-fast-files)</b> while #(link "faq.html#ATTACH" "attached to") a worker."#
#"If Antiweb is unable to access one of the fast files, pre-generated 404s are subsequently sent without even consulting the filesystem (this is called <b>negative caching</b>). Unlike normal 404s, these will not tear down a persistent connection and will pipeline just fine."#
#"You can see how many fast files, fast 404s, and bytes are currently in a worker's fast-file memory cache with the #(link "faq.html#STATS" "-stats") command. The byte count includes pre-generated HTTP headers."#
#"If simple-vhost-root is used, each vhost will have its own memory cache."#
#"Only small files should be cached in memory. Medium and large files are usually served optimally from the filesystem."#
))
(fast-files-header ":fast-files-header"
#"HTTP headers to add to #(link "worker.html#FAST-FILES" ":fast-files") served files."#
(pre #" :fast-files-header "Cache-Control: public, max-age=3600, must-revalidate""#)
)
(cgi ":cgi" "A list of file extensions to treat as CGI scripts." (pre #" :cgi (pl php)"#) (ul #"The extensions are case-insensitive."# #"See #(link "design.html#CGI-PROCESS" "Design of CGI Processes in Antiweb4") for details."#))
(naked-cgi ":naked-cgi" "A list of file extensions to treat as naked CGI scripts." (pre #" :naked-cgi (npl)"#) (ul #"The extensions are case-insensitive."# #"Naked CGI scripts are identical to regular CGI scripts except Antiweb will not prefix the following: #(pre #"HTTP/1.1 200 OK\r\nConnection: close\r\n"#) The script must send this prefix itself."# #"Naked CGI scripts are similar to #(link "http://htmlhelp.com/faq/cgifaq.2.html#6" "NPH") (No Parsed Headers)."#))
(cgi-maxfiles ":cgi-maxfiles" #"Limit the number of file descriptors a CGI or naked CGI process may have open at once:"# (pre #" :cgi-maxfiles 100"#) (ul #"If not specified, a sensible default value is used."# #"This value must be smaller than the worker's #(link "worker.html#MAX-FDS" "max-fds") value."#))
(cgi-no-forking ":cgi-no-forking" #"Use the NPROC resource limit to ensure that CGI or naked CGI processes launched from this handler cannot fork()."# (pre #" :cgi-no-forking"#) (ul #"This option negates certain common mistakes in CGI scripts. For example, a bug that allows an attacker to launch system() or shell "backquotes" will result in the fork() call failing."# #"This a very restrictive option and will prevent many perfectly legitimate CGI scripts from working. If you don't understand exactly what this does, you probably don't need it."# #"We may add additional CGI resource limits in the future. Let us know which you find most useful."#))
(awp ":awp" "Enable Anti Webpages." (pre #" :awp"#) (ul #"Worker must have a #(link "faq.html#CACHE" "cache directory")."# #"Because all code required to compile and serve Anti Webpages is stored in the lisp image, you can #(link "worker.html#CHROOT" "chroot") workers that use :awp."# #"Anti Webpages are affected by the #(link "worker.html#ETAGS" ":etags") and #(link "worker.html#GZIP" ":gzip") options just like regular static files."# #"See #(link "awp.html" "Anti Webpages") for more details."#))
)
)
))
)
(page "awp.html"
:title "Antiweb Manual: Anti Webpages"
:header #"<h1><u>Anti Webpages</u></h1>"#
:inherit "index.html"
:content (p
(awp-guiding-principles)
#"Anti Webpages are an experimental and innovative new way of creating web content. The server portion of Antiweb is separate from Antiweb Pages and is more straightforward--all it has to do is implement HTTP 1.1 as efficiently and securely as possible.#(tip #"Installing an .awp file is as easy as copying it into an Antiweb HTML root, making sure the worker has a #(link "faq.html#CACHE" "cache directory"), and adding #(link "worker.html#AWP" ":awp") to the worker's conf. However, you can also compile an .awp file with the launch script's -awp command even if no Antiweb server is running."#) This stuff is kinda crazy. Antiweb Pages are unstable meaning their exact specification will change over time (but we think we're pretty close)."#
#"The point of Anti Webpages is to create static HTML files which can be served very efficiently by Antiweb. Although they support AJAX callbacks and flat-file or BerkeleyDB data-stores, Anti Webpages revolve around static content and that is all this manual currently describes."#
(sections
(pages-and-layouts "Pages and Layouts"
#"An Anti Webpage is a file that ends in .awp. Like almost all of Antiweb's files, .awp files are #(link "design.html#CONFS-AND-XCONFS" "confs"). Each .awp file maps to an .awp/ <b>directory</b> on your website. There can be multiple pages inside this directory, each indicated with an xconf. Here is a simple .awp file with one <b>page</b> xconf:"#
(pre #"
(page "index.html"
:layout #"
content |
"#
:content #"Hello world!"#
)
"#)
(ul #"Strings can be delimited with regular double quotes (") or with the special #" and "# quotes. These special quotes allow you to insert quote characters, backslashes, etc, without having to escape them."#
#"The :layout option positions the segments of the awp file. There must be at least one line terminated with a vertical bar (|). All lines must be terminated by vertical bars except blank lines. All the vertical bars should "line up"."#
)
#"The :layout option positions the segments of the awp file. There must be at least one line terminated with a vertical bar (|). The above code positions the :content segment in the middle of the page. Multiple bars can be used to indicate more specific positioning. For example, the following code "bounds" :content in a right-most portion of the page:"#
(pre #"
(page "index.html"
:layout #"
| content |
"#
:content #"Hello world!"#
)
"#)
#"Alternatively, you can use the locator modifier (@) to position a segment within its area. The following is similar to the previous example:"#
(pre #"
(page "index.html"
:layout #"
content@r |
"#
:content #"Hello world!"#
)
"#)
#"@r means it should positioned at the right of its area. The possible modifiers are @r @l @t @b @tl @tr @bl @br (though the letter arrangements don't matter). Here is a more complicated example:"#
(pre #"
(page "index.html"
:title "Antiweb Manual"
:layout-width 800
:layout #"
logo@r | | header@l | slogan |
nav@rt | | content@tl |
footer |
"#
:header #"<h1><u>Antiweb Manual</u></h1>"#
)
"#)
#"When the above .awp file is rendered, there is one segment displayed (:header) and the rest are NIL because you haven't added them yet. There are some special keywords that don't relate to the layout:"#
(ul #"<b>:title</b> - This is the page's HTML title."#
#"<b>:css</b> - CSS code. There can be multiple :css parameters. They are all added to a CSS block at the top of the rendered HTML page."#
#"<b>:js</b> - Javascript code. There can be multiple :js parameters. They are all added to a Javascript block at the top of the rendered HTML page."#
#"<b>:js-end</b> - Identical to <b>:js</b> except the code is added to a Javascript block at the bottom of the page, not the top."#
)
)
(inheritance "Inheritance"
#"Because it is so common to want to "re-use" parts of other pages, Anti Webpages support <b>page inheritance</b>. This is different from the inheritance of #(link "design.html#CONFS" "conf files") and is only given the same name to add to the general confusion. Of course .awp files are confs so you can use that inheritance too. You can even inherit pages across inherited .awp files."# #"Here is how you use page inheritance:"#
(pre #"
(page "index.html"
:title "my title"
:layout #"
| header | |
content@r |
"#
:header "my site"
:content #"my content"#
)
(page "other.html"
:inherit "index.html"
:content #"my other content"#
)
"#)
#"Now, when other.html is rendered, it is exactly the same as index.html except for the :content parameter. This parameter has been <b>over-ridden</b> or <b>shadowed</b>. What happens is the xconf for index.html is appended on to the end of other.html's xconf. When Antiweb goes to render other.html, it only looks for the first parameter named :content so it gets the shadowing one."#
(ul #"Any parameter can be inherited or shadowed, including :layout and :title."#
#"Since Antiweb takes all :css, :js, and :js-end parameters, not just the first ones it finds, all CSS and JS code is inherited."#
)
)
(super-glue "Super-Glue"
#"So what are these things we're passing as arguments? They are lisp strings. But they don't need to be. They can be anything and Anti Webpages will <b>super-glue</b> them into HTML. There are several built-in list forms provided. For example, p takes any amount of arguments and will wrap HTML <p> tags around each one:"#
(pre #"
(page "other.html"
:inherit "index.html"
:content (p "pargraph 1"
#"paragraph 2"#
(p #"subparagraph"#)
)
)
"#)
#"But another way you could have done that is by giving a string and then <b>unquoting</b> a list-based expression inside that string. If super-glue finds the sequence of characters # and then ( followed by a terminating ) later inside a string, it will treat it as a list form and will super-glue it too:"#
(pre #"
(page "other.html"
:inherit "index.html"
:content #"
#(p "pargraph 1"
#"paragraph 2"#
(p #"subparagraph"#)
)
"#
)
"#)
#"<b>There is no bottom.</b>"#
#"Anti Webpages don't care if you use HTML. The two previous examples could both have been written like this:"#
(pre #"
(page "other.html"
:inherit "index.html"
:content #"
<p>pargraph 1</p>
<p>pargraph 2</p>
<p><p>subparagraph</p></p>
"#
)
"#)
(ul
#"You can create your own glue types like <b>p</b> with the <b>defglue</b> form. Glue types added in an .awp file are local to that .awp file only."#
)
)
(super-glue "More Info"
#"<i>Ya ok you guys are nuts but that sounds pretty cool.</i>"#
#"For more info see the following files:"#
(ul #"src/manual.awp - The .awp file for the manual you are reading now."#
#"src/awp.lisp - The implementation of Anti Webpages."#
#"src/glue.lisp - Default glue types included with Antiweb."#
)
)
)
)
)
| 88,416 | Common Lisp | .l | 860 | 96.923256 | 1,497 | 0.712921 | hoytech/antiweb | 83 | 9 | 0 | GPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 784dc8a13a035ade11b66e6d8c29ca0747c1dd9f0be947a25e4edc529f59e05a | 2,489 | [
-1
] |
2,550 | build.lisp | inaimathi_cl-notebook/build/build.lisp | (ql:quickload :cl-notebook)
(ql:write-asdf-manifest-file "build.manifest")
(with-open-file (s "build.manifest" :direction :output :if-exists :append)
(loop for sys in (list :session-token :house :fact-base :cl-notebook)
do (format s "~a~%" (merge-pathnames (format nil "~(~a~).asd" sys) (asdf/system:system-source-directory sys)))))
(ql:quickload :buildapp)
(buildapp:build-buildapp)
| 391 | Common Lisp | .lisp | 7 | 53.857143 | 117 | 0.721354 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | fc3d0d198162f5940fabc84fc075de95aeb8bd9857f2693247a2d05d5d649522 | 2,550 | [
-1
] |
2,551 | cl-notebook.lisp | inaimathi_cl-notebook/test/cl-notebook.lisp | (in-package #:cl-notebook/test)
(tests
(is (+ 2 3) 5 "Addition works")
;; (is (+ 2 3) 6 "Intentionally fails")
(for-all ((a a-number) (b a-number))
(is= (+ a b) (+ b a))
"Addition is commutative")
;; (for-all ((a a-number) (b a-number))
;; (is= (- a b) (- b a))
;; "Subtraction is not, so this should fail")
)
| 331 | Common Lisp | .lisp | 11 | 27.727273 | 49 | 0.559748 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 9a92b568b8c87c151f3aed2161dfdccf702ab7e1122cb38389a19cfc5d0247d7 | 2,551 | [
-1
] |
2,552 | model.lisp | inaimathi_cl-notebook/src/model.lisp | (in-package :cl-notebook)
;;;;;;;;;; Notebook and constructor/destructor
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defclass notebook (fact-base)
((namespace :accessor namespace :initform (find-package :cl-notebook) :initarg :namespace)))
(defun make-notebook (&key (file-name (make-unique-name-in *books* "new-book")))
(make-instance
'notebook :file-name file-name :in-memory? t
:index (fact-base::make-index *default-indices*)
:history (fact-base::queue)))
(defun new-notebook! (path)
(let ((book (make-notebook :file-name path)))
(insert-new! book :notebook-name (pathname-name path))
(insert-new!
book :notebook-package (default-package book))
(setf (namespace book) (notebook-package! book))
(register-notebook! book)
book))
(defmethod load-notebook! ((file-name pathname))
(assert (cl-fad:file-exists-p file-name) nil "Nonexistent file ~s" file-name)
(let* ((book (make-notebook :file-name file-name)))
(with-open-file (s file-name :direction :input)
(loop for entry = (handler-case
(fact-base::read-entry! s)
(#+sbcl sb-int:simple-reader-package-error #-sbcl error (e)
(load-package (slot-value e 'package))
(fact-base::read-entry! s)))
while entry
do (incf (fact-base::entry-count book))
do (fact-base::apply-entry! book entry)))
(handler-bind (#+sbcl (sb-ext:name-conflict
(lambda (e)
(invoke-restart
(or (find-restart 'sb-impl::take-new e)
(find-restart 'sb-impl::shadowing-import-it e))))))
(setf (namespace book)
(notebook-package! book))
(eval-notebook book))
(register-notebook! book)))
;;;;;;;;;; Notebook methods
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod new-cell! ((book notebook) &key (cell-language :common-lisp) (cell-type :code))
(multi-insert! book `((:cell nil) (:cell-type ,cell-type) (:cell-language ,cell-language) (:contents "") (:result ""))))
(defmethod notebook-id ((book notebook))
(namestring (file-name book)))
(defmethod default-package ((book notebook))
(format nil "(defpackage ~s~% (:use :cl :fact-base :cl-notebook))" (notebook-name book)))
(defmethod notebook-name ((book notebook))
(caddar (lookup book :b :notebook-name)))
(defmethod notebook-cell-order ((book notebook))
(let* ((ordered-ids (caddar (lookup book :b :cell-order)))
(unordered-ids (set-difference
(reverse (mapcar #'car (lookup book :b :cell :c nil)))
ordered-ids)))
(concatenate 'list ordered-ids unordered-ids)))
(defun reorder-cells! (book cell-order)
(awhen (first (lookup book :b :cell-order))
(delete! book it))
(insert-new! book :cell-order cell-order)
(write! book)
book)
(defun notebook-cell (book cell-id)
(cons (cons :id cell-id)
(for-all `(,cell-id ?k ?v)
:collect (cons ?k ?v)
:in book)))
(defun map-cells (fn book)
(loop for id in (notebook-cell-order book)
collect (funcall fn (notebook-cell book id))))
(defun do-cells (fn book)
(loop for id in (notebook-cell-order book)
do (funcall fn (notebook-cell book id))))
(defmethod notebook-package-spec-string ((book notebook))
(caddar (lookup book :b :notebook-package)))
(defmethod notebook-package-spec ((book notebook))
(let ((default (default-package book)))
(handler-case
(or (read-from-string (notebook-package-spec-string book)) (read-from-string default))
(error ()
(read-from-string default)))))
(defmethod notebook-package! ((book notebook))
;; TODO handle loading and package-related errors here
(let ((spec (notebook-package-spec book)))
(load-dependencies! spec)
(or (find-package (second spec)) (eval spec))))
(defun load-package (package)
(unless (find-package package)
(publish-update! nil 'loading-package :package package)
(handler-bind ((error (lambda (e)
(publish-update! nil 'package-load-failed :package package :error (front-end-error nil e)))))
(qlot:with-local-quicklisp (*storage*)
(qlot/utils:with-package-functions :ql (quickload)
(quickload package)))
(publish-update! nil 'finished-loading-package :package package))))
(defmethod load-dependencies! ((package-form list))
(loop for exp in (cddr package-form)
do (case (car exp)
(:use (mapc #'load-package (cdr exp)))
(:import-from (load-package (second exp)))
(:shadowing-import-from (load-package (second exp))))))
(defmethod repackage-notebook! ((book notebook) (new-package string))
(let ((package-form (read-from-string new-package))
(package-fact (first (lookup book :b :notebook-package)))
(old-name (package-name (namespace book))))
(handler-bind ((error (lambda (e)
(setf (namespace book) (rename-package (namespace book) old-name))
(insert! book (list (first package-fact) :package-error (front-end-error package-form e))))))
(if (string= new-package (third package-fact))
(values book nil)
(progn
(setf (namespace book) (rename-package (namespace book) (second package-form)))
(load-dependencies! package-form)
(handler-bind (#+sbcl (sb-ext:name-conflict
(lambda (e)
(invoke-restart
(or (find-restart 'sb-impl::take-new e)
(find-restart 'sb-impl::shadowing-import-it e))))))
(eval package-form))
(awhen (first (lookup book :b :package-error)) (delete! book it))
(if package-fact ;; TODO - remove conditional eventually. All notebooks should have such facts.
(change! book package-fact (list (first package-fact) :notebook-package new-package))
(insert-new! book :notebook-package new-package))
(write! book)
(values book t))))))
(defmethod rename-notebook! ((book notebook) (new-name string))
"Takes a book and a new name.
Returns two values; the renamed book, and a boolean specifying whether the name was changed.
If the new name passed in is the same as the books' current name, we don't insert any new facts."
(let* ((name-fact (first (lookup book :b :notebook-name)))
(same? (equal (third name-fact) new-name)))
(unless same?
(change! book name-fact (list (first name-fact) :notebook-name new-name))
(write! book))
(values book (not same?))))
(defun fork-at! (book index)
(let* ((old-path (file-name book))
(new-path (make-unique-name-in
(make-pathname :directory (pathname-directory old-path))
(format nil "~a.4k" (file-namestring old-path))))
(new (load-notebook! (fork-at book index :file-name new-path)))
(new-name (format nil "Fork of '~a'" (notebook-name book))))
(rename-notebook! new new-name)
(register-notebook! new)
new))
;;;;;;;;;; Notebooks table and related functions
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar *notebooks* (make-hash-table :test 'equal))
(defun loaded-books! ()
(sort
(loop for k being the hash-keys of *notebooks*
for v being the hash-values of *notebooks*
if (cl-fad:file-exists-p k)
collect (list k v)
else do (remhash k *notebooks*))
#'string<= :key #'first))
(defmethod register-notebook! ((book notebook))
(setf (gethash (notebook-id book) *notebooks*) book))
(defmethod get-notebook! ((name string))
(let ((n (quri:url-decode name)))
(aif (gethash n *notebooks*)
it
(let ((book (load-notebook! (pathname n))))
(setf (gethash n *notebooks*) book)
book))))
| 7,696 | Common Lisp | .lisp | 164 | 40.097561 | 122 | 0.633009 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | dc23974e242df3bf98b23d95ed794a068aa10378340ce1e3543d6a6b6c1d3d42 | 2,552 | [
-1
] |
2,553 | package.lisp | inaimathi_cl-notebook/src/package.lisp | ;;;; package.lisp
(defpackage #:cl-notebook
(:use #:cl #:house #:parenscript #:cl-who #:fact-base)
(:import-from #:cl-css #:inline-css)
(:shadowing-import-from #:cl-css #:%)
(:import-from #:anaphora #:aif #:awhen #:it)
(:import-from #:alexandria #:with-gensyms)
(:shadowing-import-from
#+openmcl-native-threads #:ccl
#+cmu #:pcl
#+sbcl #:sb-pcl
#+lispworks #:hcl
#+allegro #:mop
#+clisp #:clos
#:class-slots #:slot-definition-name)
(:shadowing-import-from #:fact-base #:lookup)
(:export :bar-graph :draw-bar-graph :main :str :htm :who-ps-html :new :create :@ :chain :define-css))
(in-package #:cl-notebook)
(defvar *storage* nil)
(defvar *books* nil)
(defvar *static* nil)
(defvar *ql* nil)
(defvar *static-files* nil)
(defvar *default-indices* '(:a :b :ab :abc))
(defun >>notebook (book-id)
(let ((book (get-notebook! book-id)))
(assert (typep book 'notebook))
book))
(defun >>package (name)
(let ((pkg (or (find-package name) (find-package (intern (string-upcase name) :keyword)))))
(assert (not (null pkg)))
pkg))
(defun >>existing-filepath (path)
(let ((p (pathname path)))
(assert (cl-fad:file-exists-p p))
p))
(defun >>existing-directory (path)
(let ((p (pathname path)))
(assert (cl-fad:directory-exists-p p))
p))
(defun >>nonexistent-file (path)
(let ((p (pathname path)))
(not (or (cl-fad:directory-exists-p p)
(cl-fad:file-exists-p p)))
p))
(defun >>export-format (format)
(let ((fmt (intern (string-upcase format) :keyword)))
(member fmt (export-book-formats))
fmt))
| 1,598 | Common Lisp | .lisp | 49 | 29.163265 | 103 | 0.642625 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 38bdb6d06cff4ccdd97b412553ce3734fb3c50d3b37b8be7991a0e2ab14b1447 | 2,553 | [
-1
] |
2,554 | util.lisp | inaimathi_cl-notebook/src/util.lisp | (in-package #:cl-notebook)
;;;;; Basic HTML stuff
(defmacro html-to-str (&rest forms)
`(with-html-output-to-string (s nil :indent t)
,@forms))
;;;;; Basic data structure stuff
(defun hash (&rest entries)
(let ((h (make-hash-table)))
(loop for (k v) on entries by #'cddr
do (setf (gethash k h) v))
h))
(defun alist (&rest k/v-pairs)
"Association lists with less consing"
(loop for (k v) on k/v-pairs by #'cddr
collect (cons k v)))
(defun aget (k alist)
(cdr (assoc k alist)))
(defmethod first-char ((str string))
(char str 0))
(defmethod last-char ((pth pathname)) (last-char (file-namestring pth)))
(defmethod last-char ((str string)) (aref str (- (length str) 1)))
;;;;; Basic command line args and file-system stuff
(defun parse-args! (raw)
(pop raw)
(flet ((arg? (str) (eql #\- (first-char str)))
(->flag (str) (intern (string-upcase (string-left-trim "-" str)) :keyword))
(->arg (str) (or (parse-integer str :junk-allowed t) str)))
(loop for next = (pop raw) while next
if (and (arg? next) (or (not raw) (arg? (car raw))))
collect (cons (->flag next) t) into params
else if (arg? next)
collect (cons (->flag next) (->arg (pop raw))) into params
else collect next into args
finally (return (values params args)))))
(defun get-param (names params)
(loop for (a . b) in params
if (member a names) do (return b)))
(defun sys-dir (path)
(let ((path (cl-fad:pathname-as-directory path)))
(ensure-directories-exist path)
path))
(defmethod stem-path ((path pathname) stem-from)
(let ((stemmed (member stem-from (cdr (pathname-directory path)) :test #'string=)))
(make-pathname
:directory
(if stemmed
(cons :relative stemmed)
(pathname-directory path))
:name (pathname-name path)
:type (pathname-type path))))
(defmethod make-unique-name-in ((dir pathname) (base-name string))
(assert (cl-fad:directory-pathname-p dir))
(let ((name (merge-pathnames base-name dir)))
(if (cl-fad:file-exists-p name)
(loop for i from 0
for name = (merge-pathnames (format nil "~a-~a" base-name i) dir)
unless (cl-fad:file-exists-p name) return name)
name)))
;;;;; Error-related
(defun instance->alist (instance)
(loop for s in (closer-mop:class-slots (class-of instance))
for slot-name = (slot-definition-name s)
when (slot-boundp instance slot-name)
collect (cons (intern (symbol-name slot-name) :keyword)
(slot-value instance slot-name))))
(defun type-tag (thing)
"Extracts just the type tag from compound type specifications.
Returns primitive type specifications as-is."
(let ((tp (type-of thing)))
(if (listp tp)
(first tp)
tp)))
(defun ignored-error-prop? (prop-name)
(member prop-name
(list :args :control-string :second-relative :print-banner
:references :format-control :format-arguments :offset
:stream
:new-location)))
(defun stringified-error-prop? (prop-name)
(member prop-name '(:name :new-function :specializers :old-method :datum :expected-type :generic-function)))
(defun printable-readably? (thing)
(handler-case
(let ((*print-readably* t))
(values t (prin1-to-string thing)))
(print-not-readable ()
nil)))
(defun front-end-error (form e)
"Takes a form and an error pertaining to it.
Formats the error for front-end display, including a reference to the form."
(let ((err-alist (instance->alist e)))
`((condition-type . ,(symbol-name (type-tag e)))
,@(let ((f-tmp (cdr (assoc :format-control err-alist)))
(f-args (cdr (assoc :format-arguments err-alist))))
(when (and f-tmp f-args)
(list (cons :error-message (apply #'format nil f-tmp f-args)))))
,@(when form (list (cons :form form)))
,@(loop for (a . b) in err-alist
if (or (stringified-error-prop? a)
(not (printable-readably? b)))
collect (cons a (format nil "~s" b))
else if (not (ignored-error-prop? a))
collect (cons a b)))))
;;;;; Lisp internal stuff
(defmethod arglist ((fn symbol))
#+ccl (ccl:arglist fn)
#+lispworks (lw:function-lambda-list fn)
#+clisp (or (ignore-errors
(second (function-lambda-expression fn)))
(ext:arglist fn))
#+sbcl(sb-introspect:function-lambda-list fn))
(defmethod read-all ((str stream))
(let ((eof (gensym "EOF-")))
(loop for s-exp = (read str nil eof) until (eq s-exp eof)
collect s-exp)))
(defmethod read-all ((str string))
(read-all (make-string-input-stream str)))
(defmethod capturing-eval ((str stream))
"Takes the next s-expression from a stream and tries to evaluate it.
Returns either NIL (if there are no further expressions)
or a (:stdout :warnings :values) alist representing
- The *standard-output* emissions
- collected warnings
- return values (which may be errors)
from each expression in turn."
(let* ((eof (gensym "EOF-"))
(res nil)
(warnings)
(exp)
(stdout
(with-output-to-string (*standard-output*)
(handler-case
(handler-bind ((warning (lambda (w) (push (front-end-error nil w) warnings))))
(setf
exp (read str nil eof)
res (if (eq eof exp)
:eof
(mapcar
(lambda (v) (alist :type (format nil "~s" (type-tag v)) :value (write-to-string v)))
(multiple-value-list (eval exp))))))
(error (e)
(setf res (list
(alist
:type 'error
:value (front-end-error (format nil "~s" exp) e)))))))))
(if (eq :eof res)
nil
(alist :stdout stdout :warnings warnings :values res))))
(defmethod capturing-eval ((str string))
"Evaluates each form in the given string, collecting return values, warnings and *standard-output* emissions."
(let ((stream (make-string-input-stream str)))
(loop for res = (capturing-eval stream)
while res collect res)))
| 5,811 | Common Lisp | .lisp | 152 | 34.052632 | 112 | 0.661522 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 5cfa86bd36fa87a86652c6c210c4da8169994e9f0afe0b321ed9f93aeec5b0a4 | 2,554 | [
-1
] |
2,555 | evaluators.lisp | inaimathi_cl-notebook/src/evaluators.lisp | (in-package #:cl-notebook)
(defvar *front-end-eval-thread* nil)
(defmethod front-end-eval (cell-language cell-type (contents string))
"A cell that fits no other description returns an error"
(list
(alist
:stdout "" :warnings nil ; Without these, :json encodes this as an array rather than an object
:values (list (alist :type 'error :value
(alist 'condition-type "UNKNOWN-LANGUAGE:TYPE-COMBINATION"
'cell-language cell-language
'cell-type cell-type))))))
(defmethod front-end-eval (cell-language cell-type (contents null)) "")
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :tests)) (contents string))
"A Common-Lisp:Test cell is just evaluated, capturing all warnings, stdout emissions and errors.
It's treated differently in export situations."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :code)) (contents string))
"A Common-Lisp:Code cell is just evaluated, capturing all warnings, stdout emissions and errors."
(capturing-eval contents))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :markup)) (contents string))
"A Common-Lisp:Markup cell is evaluated as a :cl-who tree"
(list
(alist :stdout "" :warnings nil ; Without these, :json encodes this as an array rather than an object
:values
(handler-case
(list
(alist
:type "string"
:value (eval
`(with-html-output-to-string (s)
,@(read-all contents)))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defmethod front-end-eval ((cell-language (eql :common-lisp)) (cell-type (eql :parenscript)) (contents string))
"A Common-Lisp:Parenscript cell is evaluated as a `ps` form"
(list
(alist :stdout "" :warnings nil
:values
(handler-case
(list
(alist
:type "js"
:value (apply #'ps* (read-all contents))))
(error (e)
(list (alist :type 'error :value (front-end-error nil e))))))))
(defun front-end-eval-formats ()
(let ((h (make-hash-table)))
(loop for m in (closer-mop:generic-function-methods #'front-end-eval)
for (a b _) = (closer-mop:method-specializers m)
when (and (typep a 'closer-mop:eql-specializer) (typep b 'closer-mop:eql-specializer))
do (push (closer-mop:eql-specializer-object b)
(gethash (closer-mop:eql-specializer-object a) h nil)))
h))
(defmethod eval-notebook ((book notebook) &key (cell-type :code))
(let ((ids (notebook-cell-order book)))
(loop for cell-id in ids
when (lookup book :a cell-id :b :cell-type :c cell-type)
do (let ((stale? (first (lookup book :a cell-id :b :stale :c t)))
(res-fact (first (lookup book :a cell-id :b :result)))
(*package* (namespace book)))
(let ((res
(handler-case
(bt:with-timeout (.1)
(front-end-eval
(caddar (lookup book :a cell-id :b :cell-language))
cell-type
(caddar (lookup book :a cell-id :b :contents))))
#-sbcl (bordeaux-threads:timeout () :timed-out)
#+sbcl (sb-ext:timeout () :timed-out))))
(unless (eq :timed-out res)
(when stale? (delete! book stale?))
(unless (equalp (third res-fact) res)
(let ((new (list cell-id :result res)))
(if res-fact
(change! book res-fact new)
(insert! book new))))))))
(write! book)))
(defmethod empty-expression? ((contents string))
(when (cl-ppcre:scan "^[ \n\t\r]*$" contents) t))
(defmethod eval-cell ((book notebook) cell-id (contents string) res-fact cell-language cell-type)
(unless (empty-expression? contents)
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target cell-id)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(let ((*package* (namespace book)))
(let ((res (front-end-eval cell-language cell-type contents)))
(when (and res-fact res)
(change! book res-fact (list cell-id :result res))
(delete! book (list cell-id :stale t))
(write! book))
(publish-update! book 'finished-eval :cell cell-id :contents contents :result res))))))))
(defmethod eval-package ((book notebook) (contents string))
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! book 'starting-eval :target :package)
(setf *front-end-eval-thread*
(bt:make-thread
(lambda ()
(handler-case
(multiple-value-bind (book repackaged?) (repackage-notebook! book contents)
(when repackaged?
(unless (lookup book :b :package-edited?)
(insert-new! book :package-edited? t))
(write! book))
(publish-update! book 'finished-package-eval :contents contents))
(error (e)
(publish-update! book 'finished-package-eval :contents contents :result (front-end-error nil e))))))))
| 5,051 | Common Lisp | .lisp | 112 | 39.883929 | 111 | 0.664773 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 7b2969f9e20407f960f406cefc0c4fb04ea913329d2b1e204ffde26cbdcccedc | 2,555 | [
-1
] |
2,556 | main.lisp | inaimathi_cl-notebook/src/main.lisp | (in-package :cl-notebook)
; System initialization and related functions
(defun read-statics ()
"Used to read the cl-notebook static files into memory.
Only useful during the build process, where its called with an --eval flag."
(setf *static-files* (make-hash-table :test #'equal))
(flet ((read-file (filename)
(with-open-file (stream filename :element-type '(unsigned-byte 8))
(let ((data (make-array (list (file-length stream)))))
(read-sequence data stream)
data))))
(let ((root (asdf:system-source-directory :cl-notebook)))
(cl-fad:walk-directory
(sys-dir (merge-pathnames "static" root))
(lambda (filename)
(unless (eql #\~ (last-char filename))
(setf (gethash filename *static-files*) (read-file filename))))))))
(defun write-statics (&key force?)
(when *static-files*
(loop for k being the hash-keys of *static-files*
for v being the hash-values of *static-files*
do (let ((file (if (string= "books" (car (last (pathname-directory k))))
(merge-pathnames (pathname-name k) *books*)
(merge-pathnames (stem-path k "static") *storage*))))
(unless (and (cl-fad:file-exists-p file) (not force?))
(format t " Writing ~a ...~%" file)
(ensure-directories-exist file)
(with-open-file (stream file :direction :output :element-type '(unsigned-byte 8) :if-exists :supersede :if-does-not-exist :create)
(write-sequence v stream)))))
(setf *static-files* nil)))
(defun main (&optional argv &key (port 4242) (public? nil))
(multiple-value-bind (params) (parse-args! argv)
(flet ((dir-exists? (path) (cl-fad:directory-exists-p path)))
(let ((p (or (get-param '(:p :port) params) port))
(host (if (or (get-param '(:o :open :public) params) public?) usocket:*wildcard-host* #(127 0 0 1))))
(format t "Initializing storage directories...~%")
(setf *storage* (sys-dir (merge-pathnames ".cl-notebook" (user-homedir-pathname)))
*books* (sys-dir (merge-pathnames "books" *storage*))
*ql* (merge-pathnames "quicklisp" *storage*))
(unless *static*
(format t "Initializing static files...~%")
(setf *static* (merge-pathnames "static" *storage*))
(when (and (or (not (dir-exists? *static*))
(null (cl-fad:list-directory *static*)))
(null *static-files*))
(setf *static* (sys-dir *static*))
(read-statics))
(write-statics :force? (get-param '(:f :force) params)))
(format t "Checking for quicklisp...~%")
(unless (dir-exists? *ql*)
(qlot/install/quicklisp:install-quicklisp *ql*))
(if (find-package :quicklisp)
(format t " quicklisp already loaded...~%")
(progn
(format t " Loading quicklisp from ~s...~%" *ql*)
(load (merge-pathnames "setup.lisp" *ql*))))
(in-package :cl-notebook)
(format t "Loading config books...~%")
(dolist (book (cl-fad:list-directory *books*))
(format t " Loading ~a...~%" book)
(load-notebook! book))
(define-file-handler *static* :stem-from "static")
(when (get-param '(:d :debug) params)
(format t "Starting in debug mode...~%")
(house::debug!))
(format t "Listening on '~s'...~%" p)
#+ccl (setf ccl:*break-hook*
(lambda (cond hook)
(declare (ignore cond hook))
(ccl:quit)))
#-sbcl(start p host)
#+sbcl(handler-case
(start p host)
(sb-sys:interactive-interrupt (e)
(declare (ignore e))
(cl-user::exit)))))))
(defun main-dev ()
(house::debug!)
(setf *static* (sys-dir (merge-pathnames "static" (asdf:system-source-directory :cl-notebook))))
(bt:make-thread
(lambda () (main))))
| 3,769 | Common Lisp | .lisp | 81 | 39.62963 | 144 | 0.612666 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 6d80abfa1d815783194186da8c9f1363b17b10a0053df5d71cf77102d25e3914 | 2,556 | [
-1
] |
2,557 | publish-update.lisp | inaimathi_cl-notebook/src/publish-update.lisp | (in-package #:cl-notebook)
(defun publish-update-internal! (book action k/v-pairs)
(let ((hash (make-hash-table)))
(loop for (k v) on k/v-pairs by #'cddr
do (setf (gethash k hash) v))
(setf (gethash :book hash) book
(gethash :action hash) action)
(publish! 'cl-notebook/source (json:encode-json-to-string hash))
nil))
(defmethod publish-update! (book (action symbol) &rest k/v-pairs)
(publish-update-internal! book action k/v-pairs))
(defmethod publish-update! ((book notebook) (action symbol) &rest k/v-pairs)
(publish-update-internal! (notebook-id book) action k/v-pairs))
| 610 | Common Lisp | .lisp | 13 | 43.230769 | 76 | 0.698653 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | bba3c9f0282815fbff7ddae25b6fe535037475b0f08a42a2dd6070009532a19a | 2,557 | [
-1
] |
2,558 | cell.lisp | inaimathi_cl-notebook/src/ui/http-api/cell.lisp | (in-package #:cl-notebook)
(define-json-handler (cl-notebook/notebook/eval-to-cell) ((book >>notebook) (cell-id >>integer) (contents >>string))
(let ((cont-fact (first (lookup book :a cell-id :b :contents)))
(val-fact (first (lookup book :a cell-id :b :result)))
(cell-lang (caddar (lookup book :a cell-id :b :cell-language)))
(cell-type (caddar (lookup book :a cell-id :b :cell-type))))
(change! book cont-fact (list cell-id :contents contents))
(publish-update! book 'content-changed :cell cell-id :contents contents)
(eval-cell book cell-id contents val-fact cell-lang cell-type))
:ok)
(define-json-handler (cl-notebook/notebook/change-cell-contents) ((book >>notebook) (cell-id >>integer) (contents >>string))
(let ((cont-fact (first (lookup book :a cell-id :b :contents))))
(unless (string= contents (third cont-fact))
(change! book cont-fact (list cell-id :contents contents))
(insert! book (list cell-id :stale t))
(publish-update! book 'content-changed :cell cell-id :contents contents)))
:ok)
(define-json-handler (cl-notebook/notebook/change-cell-language) ((book >>notebook) (cell-id >>integer) (new-language >>keyword))
(let ((cont-fact (first (lookup book :a cell-id :b :contents)))
(val-fact (first (lookup book :a cell-id :b :result)))
(cell-type (caddar (lookup book :a cell-id :b :cell-type)))
(lang-fact (first (lookup book :a cell-id :b :cell-language))))
(unless (eq (third lang-fact) new-language)
(change! book lang-fact (list cell-id :cell-type new-language))
(publish-update! book 'change-cell-language :cell cell-id :new-language new-language)
(eval-cell book cell-id (third cont-fact) val-fact new-language cell-type)))
:ok)
(define-json-handler (cl-notebook/notebook/change-cell-type) ((book >>notebook) (cell-id >>integer) (new-type >>keyword))
(let ((cont-fact (first (lookup book :a cell-id :b :contents)))
(val-fact (first (lookup book :a cell-id :b :result)))
(cell-lang (caddar (lookup book :a cell-id :b :cell-language)))
(tp-fact (first (lookup book :a cell-id :b :cell-type))))
(unless (eq (third tp-fact) new-type)
(change! book tp-fact (list cell-id :cell-type new-type))
(publish-update! book 'change-cell-type :cell cell-id :new-type new-type)
(eval-cell book cell-id (third cont-fact) val-fact cell-lang new-type)))
:ok)
(define-json-handler (cl-notebook/notebook/change-cell-noise) ((book >>notebook) (cell-id >>integer) (new-noise >>keyword))
(let ((old-noise-fact (first (lookup book :a cell-id :b :noise)))
(new-noise-fact (unless (eq new-noise :normal) (list cell-id :noise new-noise))))
(cond ((and old-noise-fact new-noise-fact)
(change! book old-noise-fact new-noise-fact))
(old-noise-fact
(delete! book old-noise-fact))
(new-noise-fact
(insert! book new-noise-fact))))
(publish-update! book 'change-cell-noise :cell cell-id :new-noise new-noise)
:ok)
(define-json-handler (cl-notebook/notebook/new-cell) ((book >>notebook) (cell-language >>keyword) (cell-type >>keyword))
(let ((cell-id (new-cell! book :cell-type cell-type :cell-language cell-language)))
(write! book)
(publish-update! book 'new-cell :cell-id cell-id :cell-type cell-type :cell-language cell-language))
:ok)
(define-json-handler (cl-notebook/notebook/kill-cell) ((book >>notebook) (cell-id >>integer))
(loop for f in (lookup book :a cell-id) do (delete! book f))
(write! book)
(publish-update! book 'kill-cell :cell cell-id)
:ok)
| 3,507 | Common Lisp | .lisp | 58 | 56.724138 | 129 | 0.688844 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 041fc02f4cfede2dc78e78b88ea186a8af869f588d749e6e4d733221bb7bba2c | 2,558 | [
-1
] |
2,559 | system.lisp | inaimathi_cl-notebook/src/ui/http-api/system.lisp | (in-package #:cl-notebook)
;;;;;;;;;; System-level hooks
(define-json-handler (cl-notebook/system/kill-thread) ()
(when (and (bt:threadp *front-end-eval-thread*)
(bt:thread-alive-p *front-end-eval-thread*))
(bt:destroy-thread *front-end-eval-thread*))
(publish-update! nil 'killed-eval)
:ok)
(define-json-handler (cl-notebook/system/formats) ()
(hash :eval (front-end-eval-formats)
:export (export-book-formats)))
(define-json-handler (cl-notebook/system/home-path) ()
(namestring (user-homedir-pathname)))
(define-json-handler (cl-notebook/system/ls) ((dir >>existing-directory))
(let ((dirs nil)
(files nil))
(loop for f in (cl-fad:list-directory dir)
do (let* ((dir (pathname-directory f))
(p (hash :string (namestring f)
:path-type (first dir)
:directory (rest dir)
:name (format nil "~a~@[.~a~]" (pathname-name f) (pathname-type f)))))
(if (cl-fad:directory-pathname-p f)
(push p dirs)
(push p files))))
(hash :files (nreverse files) :directories (nreverse dirs))))
(define-channel (cl-notebook/source) () t)
(define-json-handler (cl-notebook/loaded-books) ()
(mapcar
(lambda (book)
(hash :path (car book) :title (notebook-name (second book))))
(loaded-books!)))
;;;;;;;;;; Server-side hint hooks
(defun get-completions (partial package)
(let* ((split (cl-ppcre:split "::?" partial))
(match (cl-ppcre:scan-to-strings "::?" partial))
(partial (string-downcase (or (second split) partial)))
(package (if (cdr split)
(or (find-package (read-from-string (first split))) package)
package)))
(when package
(sort
(remove-duplicates
(if (string= ":" match)
(loop for s being the external-symbols of package
for n = (string-downcase (symbol-name s))
when (alexandria:starts-with-subseq partial n) collect n)
(loop for s being the symbols of package
for n = (string-downcase (symbol-name s))
when (alexandria:starts-with-subseq partial n) collect n)))
#'< :key #'length))))
(define-json-handler (cl-notebook/system/complete) ((partial >>string) (package >>package))
(get-completions partial package))
(define-handler (cl-notebook/system/macroexpand-1 :content-type "plain/text") ((expression >>string))
(format nil "~s" (macroexpand-1 (read-from-string expression))))
(define-handler (cl-notebook/system/macroexpand :content-type "plain/text") ((expression >>string))
(format nil "~s" (macroexpand (read-from-string expression))))
(define-json-handler (cl-notebook/system/arg-hint) ((name >>string) (package >>package))
(multiple-value-bind (sym-name fresh?) (intern (string-upcase name) package)
(if (fboundp sym-name)
(hash :args (labels ((->names (thing)
(typecase thing
(list (case (car thing)
(&environment (->names (cddr thing)))
(quote
(if (cddr thing)
(->names (cdr thing))
(concatenate 'string "'" (->names (cadr thing)))))
(t (mapcar #'->names thing))))
(symbol (string-downcase (symbol-name thing)))
(t thing))))
(->names (arglist sym-name))))
(progn (when (not fresh?) (unintern sym-name))
(hash :error :function-not-found)))))
| 3,442 | Common Lisp | .lisp | 74 | 38.662162 | 101 | 0.614239 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 1af1b7da98ea7b66cdff172edca2fdf0159abb4182b09ab7bd2f3b0830b89b31 | 2,559 | [
-1
] |
2,560 | notebook.lisp | inaimathi_cl-notebook/src/ui/http-api/notebook.lisp | (in-package #:cl-notebook)
(define-json-handler (cl-notebook/notebook/export) ((book >>notebook) (format >>export-format))
(hash
:contents (export-as format book)
:mimetype (mimetype-of format)
:name (filename-of format book)))
(define-json-handler (cl-notebook/notebook/fork-at) ((book >>notebook) (index >>integer))
(let ((new (fork-at! book index)))
(publish-update! new 'new-book :book-name (notebook-name new))
(hash :facts (current new) :history-size (total-entries new) :id (notebook-id new) :book-name (notebook-name new))))
(define-json-handler (cl-notebook/notebook/reorder-cells) ((book >>notebook) (cell-order >>json))
(reorder-cells! book cell-order)
(publish-update! book 'reorder-cells :new-order cell-order)
:ok)
(define-json-handler (cl-notebook/notebook/rewind) ((book >>notebook) (index >>integer))
(hash :facts (rewind-to book index) :history-size (total-entries book) :history-position index :id (notebook-id book)))
(define-json-handler (cl-notebook/notebook/current) ((book >>notebook))
(hash :facts (current book) :history-size (total-entries book) :id (notebook-id book)))
(define-json-handler (cl-notebook/notebook/new) ((path >>nonexistent-file))
(let* ((book (new-notebook! path))
(cell-id (new-cell! book :cell-type :code :cell-language :common-lisp))
(cont-fact (first (lookup book :a cell-id :b :contents))))
(change! book cont-fact (list cell-id :contents ";;; TODO - awesome things"))
(write! book)
(publish-update! book 'new-book :book-name (notebook-name book))
(hash :facts (current book) :history-size (total-entries book) :id (notebook-id book))))
(define-json-handler (cl-notebook/notebook/load) ((path >>existing-filepath))
(let ((book (load-notebook! path)))
(publish-update! book 'new-book :book-name (notebook-name book))
(hash :facts (current book) :history-size (total-entries book) :id (notebook-id book))))
(define-json-handler (cl-notebook/notebook/repackage) ((book >>notebook) (new-package >>string))
(eval-package book new-package)
:ok)
(define-json-handler (cl-notebook/notebook/rename) ((book >>notebook) (new-name >>string))
(multiple-value-bind (book renamed?) (rename-notebook! book new-name)
(when renamed?
(unless (or (lookup book :b :package-edited?) (lookup book :b :package-error))
(repackage-notebook! book (default-package book))
(publish-update! book 'finished-package-eval :contents (notebook-package-spec-string book)))
(publish-update! book 'rename-book :new-name new-name)))
:ok)
| 2,546 | Common Lisp | .lisp | 41 | 58.707317 | 121 | 0.710337 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 58913d05d8501934e3e1da4ec6e342602ebe053548187b2b9f0d3ef4b4dcea69 | 2,560 | [
-1
] |
2,561 | api.lisp | inaimathi_cl-notebook/src/ui/http-front-end/api.lisp | (in-package :cl-notebook)
(define-handler (js/api.js :content-type "application/javascript") ()
(ps (defun kill-thread ()
(post/json "/cl-notebook/system/kill-thread" (create)))
(defun arg-hint (symbol x y &key current-arg)
(post/json "/cl-notebook/system/arg-hint" (create :name symbol :package :cl-notebook)
(lambda (res)
(unless (and (@ res error) (= (@ res error) 'function-not-found))
(dom-append
(by-selector "body")
(who-ps-html
(:div :class "notebook-arg-hint cm-s-default"
:style (+ "left:" x "px; top: " y "px")
"(" (:span :class "name" symbol)
(join (loop for arg in (@ res args)
collect (cond
((and (string? arg) (= (@ arg 0) "&"))
(who-ps-html (:span :class "modifier cm-variable-2" arg)))
((string? arg)
(who-ps-html (:span :class "arg" arg)))
(t
(who-ps-html (:span :class "compound-arg"
"(" (join
(loop for a in arg
if (null a)
collect (who-ps-html (:span :class "arg" "NIL"))
else collect (who-ps-html (:span :class "arg" a)))) ")")))))) ")")))))))
(defun rewind-book (index)
(post/json "/cl-notebook/notebook/rewind" (create :book (notebook-id *notebook*) :index index)
#'notebook!))
(defvar debounced-rewind (debounce #'rewind-book 10))
(defun fork-book (callback)
(post/json "/cl-notebook/notebook/fork-at" (create :book (notebook-id *notebook*) :index (@ (by-selector "#book-history-slider") value))
callback))
(defun export-book (format)
(when format
(post/json "/cl-notebook/notebook/export"
(create :book (notebook-id *notebook*) :format format)
(lambda (data)
(console.log data)
(save-file
(@ data :name)
(@ data :contents)
(+ (@ data :mimetype) ";charset=utf-8"))))
(setf (@ (by-selector "#book-exporters") value) "")))
(defun notebook/current (name)
(post/json "/cl-notebook/notebook/current" (create :book name)
#'notebook!
(lambda (res)
(dom-set
(by-selector "#notebook")
(who-ps-html (:h2 "Notebook '" name "' not found..."))))))
(defun new-book (path)
(post/json "/cl-notebook/notebook/new" (create :path path) #'notebook!))
(defun load-book (path)
(post/json "/cl-notebook/notebook/load" (create :path path) #'notebook!))
(defun rename-book (new-name)
(post/fork "/cl-notebook/notebook/rename" (create :book (notebook-id *notebook*) :new-name new-name)))
(defun repackage-book (new-package)
(post/fork "/cl-notebook/notebook/repackage" (create :book (notebook-id *notebook*) :new-package new-package)))
(defun notebook/eval-to-cell (cell-id contents)
(post/fork "/cl-notebook/notebook/eval-to-cell" (create :book (notebook-id *notebook*) :cell-id cell-id :contents contents)))
(defun new-cell (&optional (cell-language :common-lisp) (cell-type :code))
(post/fork "/cl-notebook/notebook/new-cell" (create :book (notebook-id *notebook*) :cell-type cell-type :cell-language cell-language)))
(defun kill-cell (cell-id)
(post/fork "/cl-notebook/notebook/kill-cell" (create :book (notebook-id *notebook*) :cell-id cell-id)))
(defun change-cell-contents (cell-id contents)
(post/fork "/cl-notebook/notebook/change-cell-contents" (create :book (notebook-id *notebook*) :cell-id cell-id :contents contents)))
(defun change-cell-type (cell-id new-type)
(post/fork "/cl-notebook/notebook/change-cell-type" (create :book (notebook-id *notebook*) :cell-id cell-id :new-type new-type)))
(defun change-cell-language (cell-id new-language)
(post/fork "/cl-notebook/notebook/change-cell-language" (create :book (notebook-id *notebook*) :cell-id cell-id :new-language new-language)))
(defun change-cell-noise (cell-id new-noise)
(post/fork "/cl-notebook/notebook/change-cell-noise" (create :book (notebook-id *notebook*) :cell-id cell-id :new-noise new-noise)))
(defun reorder-cells (ev)
(prevent ev)
(let ((ord (loop for elem in (by-selector-all ".cell")
collect (parse-int (chain elem (get-attribute :cell-id))))))
(notebook-cell-ordering! *notebook* ord)
(post "/cl-notebook/notebook/reorder-cells"
(create :book (notebook-id *notebook*)
:cell-order (obj->string ord)))))
(defun system/macroexpand-1 (expression callback)
(post "/cl-notebook/system/macroexpand-1"
(create :expression expression)
callback))
(defun system/macroexpand (expression callback)
(post "/cl-notebook/system/macroexpand"
(create :expression expression)
callback))))
| 4,812 | Common Lisp | .lisp | 90 | 45.188889 | 142 | 0.622714 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | c33b79efaa4c539489d2f42dde51995365804b91280d76991589200ca14f7d30 | 2,561 | [
-1
] |
2,562 | css.lisp | inaimathi_cl-notebook/src/ui/http-front-end/css.lisp | (in-package #:cl-notebook)
(defparameter +css-input+
`(:border "2px solid #ccc" :border-right-color "#aaa" :border-bottom-color "#aaa" :border-radius 4px :height 24px :font-weight bold))
(defparameter *notebook-css*
(cl-css:css
`((body :font-family sans-serif :overflow-x hidden)
("button" ,@+css-input+ :min-width 34px :font-size 1em :float left :margin-right 1% :color "#666" :cursor pointer)
("button.right" :float right)
("button.genericon" :font-size 1.4em)
("button .btn-text" :display inline-block)
("button:hover" :color "#000")
(select ,@+css-input+ :color "#666" :margin-right 1%)
("select:hover" :color "#000" :background-color "#eee")
(input.text ,@+css-input+ :padding 3px)
(.book-title :margin "10px 10px 5px 5px" :padding 0px)
(".book-title h1" :cursor pointer :margin 0px :margin-bottom 5px :padding 0px)
(".book-title input" :margin-bottom 5px :width 50%)
(.book-package :margin "0px 5px 10px 5px" :padding 0px)
(.main-controls
:background-color "#eee" :border "2px solid #ccc" :border-radius "0px 0px 5px 5px"
:z-index 10 :position fixed :bottom 0px :padding 0px :margin 0px
:width 100% :padding 1%)
(".main-controls #book-history-slider" :width 98% :margin "5px 0px")
(".main-controls button" :width 20% :min-height 32px)
(".main-controls select" :font-size 1em :width 24% :padding-top 4px :min-height 32px)
(".main-controls .ui-element" :font-size 1em :width 28% :padding-top 4px :min-height 32px)
(".main-controls input" :margin 0px :padding 0px :margin-bottom 3px)
(.notebook-selector :background-color "#eee" :padding 10px :max-height 80vh)
(".notebook-selector .filesystem-input" :width 80%)
(".notebook-selector .loaded-books-list" :list-style-type none :columns "5 100px" :background-color white :padding-left 5px :height 20% :overflow auto)
(".notebook-selector .loaded-books-list li" :padding 5px)
(".notebook-selector .filesystem-list" :list-style-type none :columns "5 100px" :background-color white :padding-left 5px :margin 0px :height 50% :overflow auto)
(.thread-controls :padding "8px 0px" :border-radius "5px"
:font-weight bold :color "rgba(255, 255, 255, .6)"
:width 98% :background-color "rgba(50, 50, 200, .4)" :border "2px solid rgba(50, 50, 200, .6)"
:margin-top 10px)
(".thread-controls .notice" :padding-left 5px)
(".thread-controls img" :height 1.6em :opacity .6)
(".thread-controls button" :background-color "rgba(50, 50, 200, .4)" :font-size 1em
:color "rgba(255, 255, 255, .6)" :border-color "rgba(255, 255, 255, .6)"
:margin-right 8px)
(".thread-controls button:hover" :border-color white :color white :background-color "rgba(75, 75, 200, .4)")
(.notebook-arg-hint :position absolute :z-index 8 :padding 3px :border "1px solid #ccc" :border-radius 3px :background-color white :font-size small)
(".notebook-arg-hint span" :margin-right 6px)
(".notebook-arg-hint span:last-child" :margin-right 0px)
(".notebook-arg-hint .name")
(".notebook-arg-hint .modifier" :font-style oblique)
(.cells :list-style-type none :padding 0px :margin 0px :margin-bottom 20%)
(".cells .cell" :padding 5px :margin-bottom 10px :border-top "3px solid transparent" :background-color "#eee")
(".cells .cell.stale" :border "2px solid orange")
(".cells .cell.markup" :background-color "#fff")
(".cells .cell .cell-value" :display block :min-height 30px)
(".cell .controls"
:display none :position absolute :margin-top -41px :padding 5px :padding-right 10px
:background-color "#eee" :border "2px solid #ccc" :border-bottom none :border-radius "5px 5px 0px 0px" :z-index 8 :white-space nowrap)
(".cell .controls button" :width 32px)
(".cell .controls span"
:height 19px :width 31px :font-size 1.4em :float left :margin-right 1% :color "#666"
:padding-top 5px :padding-left 3px :cursor move)
(".cell .controls span:hover" :color "#000")
(".cell blockquote" :font-style oblique :border-left "2px solid #eee" :padding 10px)
(".cell:hover, .cell.focused" :border-top "3px solid #ccc" :z-index 15)
(".cell:hover .controls, .cell.focused .controls" :display block)
(.result :border "1px solid #ccc" :background-color "#fff" :list-style-type none :margin 0px :margin-top 5px :padding 0px :white-space pre-wrap)
(.stdout :margin 0px :padding 5px :color "#8b2252" :background-color "#efefef")
(".result li" :padding 5px)
(".result .type" :color "#228b22")
(".warnings .condition-contents"
:background-color "#fc6" :color "#c60" :border "1px solid #c60"
:padding 5px :margin "5px 0px")
(".result .error" :background-color "#fdd" :color "#933")
(.condition-contents :list-style-type none :margin 0px :padding 0px)
(".condition-contents .condition-type" :font-weight bolder)
(".condition-contents .condition-property" :font-style oblique)
(".condition-contents .condition-property .label" :display inline-block :margin-right 5px :font-size .8em)
("#macro-expansion"
:width 60% :height 95% :position :fixed :top 3% :right 0 :opacity 0.6
:z-index 9 :border-radius 5px :border "2px solid #ccc" :background-color "#eee")
("#macro-expansion .CodeMirror" :height 100% :width 100%))))
(define-handler (css/notebook.css :content-type "text/css") ()
*notebook-css*)
(defparameter *addon-css-rules* (make-hash-table :test 'equalp))
(defun define-css (name rules)
(setf (gethash name *addon-css-rules*) rules)
(publish-update! nil 'addon-updated :addon-type :css :addon-name name)
(cl-css:css rules))
(define-handler (css/notebook-addons.css :content-type "text/css") ()
(cl-css:css (loop for v being the hash-values of *addon-css-rules* append v)))
| 5,967 | Common Lisp | .lisp | 88 | 60.863636 | 166 | 0.66348 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 734fa6b33806e8cfbec68988a7a3cfd13ca4b55d104874340407b63260058ef1 | 2,562 | [
-1
] |
2,563 | templates.lisp | inaimathi_cl-notebook/src/ui/http-front-end/templates.lisp | (in-package :cl-notebook)
(define-handler (js/templates.js :content-type "application/javascript") ()
(ps
(defun condition-template (err)
(who-ps-html
(:ul :class "condition-contents"
(:li :class "condition-type" (@ err condition-type))
(:li :class "condition-form" (@ err form))
(join (map
(lambda (v k)
(if (and v (not (or (= k "conditionType") (= k "form"))))
(who-ps-html
(:li :class "condition-property"
(:span :class "label" k ":") (dom-escape v)))
""))
err)))))
(defun result-values-template (result-vals)
(when result-vals
(who-ps-html
(:ul :onclick "selectContents(event, this)" :class "result"
(join (loop for v in result-vals
collect (with-slots (type value) v
(if (= type :error)
(who-ps-html (:li :class "error" (condition-template value)))
(who-ps-html (:li (:span :class "value" (dom-escape value))
(:span :class "type" " :: " type)))))))))))
(defun result-warnings-template (result-warnings)
(who-ps-html
(:span :onclick "selectContents(event, this)" :class "warnings"
(join (loop for w in result-warnings
collect (condition-template w))))))
(defun result-stdout-template (stdout)
(if stdout
(who-ps-html
(:p :onclick "selectContents(event, this)" :class "stdout"
stdout))
""))
(defun terse-result-template (results)
(result-values-template (@ (last results) values)))
(defun normal-result-template (results)
(let ((all-stdout (new (-array)))
(all-warnings (new (-array)))
(res))
(loop for r in results
do (with-slots (stdout warnings) r
(chain all-stdout (push stdout))
(when warnings
(loop for w in warnings
unless (*warning-filter* w)
do (chain all-warnings (push w)))))
finally (setf res (@ r values))))
(who-ps-html
(result-stdout-template (join all-stdout))
(result-warnings-template all-warnings)
(result-values-template res)))
(defun verbose-result-template (results)
(join
(loop for res in results
when (@ res stdout)
collect (result-stdout-template (@ res stdout))
when (@ res warnings)
collect (result-warnings-template (@ res warnings))
when (@ res values)
collect (result-values-template (@ res values)))))
(defun result-template (noise result)
(when result
(who-ps-html
(:pre (case noise
(:verbose
(verbose-result-template result))
(:terse
(terse-result-template result))
(:silent "")
(t (normal-result-template result)))))))
(defun cell-markup-result-template (result)
(if result
(let ((val (@ result 0 values 0 value)))
(cond ((and (string? val) (= "" val))
(who-ps-html (:p (:b "[[EMPTY CELL]]"))))
((string? val) val)
(t (result-template :verbose result))))
(who-ps-html (:p (:b "[[EMPTY CELL]]")))))
(defun cell-value-template (cell)
(with-slots (cell-type result noise stale) cell
(case cell-type
(:markup (cell-markup-result-template result))
(otherwise (result-template noise result :stale? stale)))))
(defun cell-markup-template (cell)
(who-ps-html
(:div :onclick (+ "showEditor(" (@ cell id) ")")
(:span :class "cell-value" (cell-value-template cell)))))
(defun cell-code-template (cell)
(who-ps-html (:span :class "cell-value" (cell-value-template cell))))
(defun cell-controls-template (cell)
(who-ps-html
(:div :class "controls"
(:span :class "genericon genericon-draggable")
(:button :class "genericon genericon-trash"
:onclick (+ "killCell(" (@ cell id) ")") " ")
(:select
:onchange (+ "changeCellType(" (@ cell id) ", this.value)")
(join (loop for tp in (@ *cl-notebook* formats eval (@ cell cell-language))
if (= (@ cell cell-type) tp)
collect (who-ps-html (:option :value tp :selected "selected" tp))
else collect (who-ps-html (:option :value tp tp)))))
;; (:select
;; :onchange (+ "changeCellLanguage(" (@ cell id) ", this.value)")
;; (join (loop for lang in (list :common-lisp)
;; for lb in (list 'common-lisp) ;; curse these symbol case issues
;; if (= (@ cell cell-type) lb)
;; collect (who-ps-html (:option :value lang :selected "selected" lang))
;; else
;; collect (who-ps-html (:option :value lang lang)))))
(:select
:onchange (+ "changeCellNoise(" (@ cell id) ", this.value)")
(join (loop for ns in (list :silent :terse :normal :verbose)
if (or (and (@ cell noise) (= (@ cell noise) ns))
(and (not (@ cell noise)) (= ns :normal)))
collect (who-ps-html (:option :value ns :selected "selected" ns))
else
collect (who-ps-html (:option :value ns ns))))))))
(defun cell-template (cell)
(with-slots (id cell-type language contents stale) cell
(who-ps-html
(:li :class (+ "cell " cell-type (if stale " stale" "")) :id (+ "cell-" id) :cell-id id
:onmousedown (+ "focusCell(" id ")") :onmouseenter "unfocusCells()"
:ondragend "reorderCells(event)" :draggable "true"
(cell-controls-template cell)
(:textarea :class "cell-contents" :language (or language "commonlisp") contents)
(case (@ cell cell-type)
(:markup (cell-markup-template cell))
(otherwise (cell-code-template cell)))))))
(defun show-thread-controls! (&optional (notice "Processing"))
(dom-replace (by-selector ".thread-controls .notice") (who-ps-html (:span :class "notice" notice)))
(show! (by-selector ".thread-controls")))
(defun hide-thread-controls! ()
(hide! (by-selector ".thread-controls")))
(defun show-macro-expansion! ()
(show! (by-selector "#macro-expansion")))
(defun hide-macro-expansion! ()
(hide! (by-selector "#macro-expansion")))
(defun show-title-input ()
(let ((input (by-selector ".book-title input")))
(show! input)
(show! (by-selector ".book-package"))
(chain input (focus))
(chain input (select))
(hide! (by-selector ".book-title h1"))))
(defun hide-title-input ()
(hide! (by-selector ".book-title input"))
(hide! (by-selector ".book-package"))
(show! (by-selector ".book-title h1")))
(defun notebook-package-template (package &optional result)
(who-ps-html
(:div :class "book-package"
(:textarea :onchange "repackageBook(this.value)" package)
(when result
(who-ps-html
(:ul :class "result"
(:li :class "error" (condition-template result))))))))
(defun notebook-title-template (name)
(who-ps-html
(:div :class "book-title"
(:input :class "text" :onchange "renameBook(this.value)" :value name)
(:h1 :onclick "showTitleInput()" name))))
(defun notebook-template (notebook)
(+ (notebook-title-template (notebook-name notebook))
(notebook-package-template (notebook-package notebook))
(who-ps-html
(:ul :class "cells"
(join (map (lambda (cell) (cell-template cell))
(notebook-cells notebook)))))))))
| 7,295 | Common Lisp | .lisp | 172 | 35.465116 | 105 | 0.602535 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a8e38e3273b129a0aed5b2b5521fae20708b0919f4d157cc4c30fb947fd070c4 | 2,563 | [
-1
] |
2,564 | base.lisp | inaimathi_cl-notebook/src/ui/http-front-end/base.lisp | (in-package :cl-notebook)
(defparameter *base-js*
(ps
;;;; base.js contains general utilities that might be useful in other JS
;;;; applications too. Nothing notebook-specific here.
(defun now! ()
(chain -date (now)))
;; basic functional stuff
(defun identity (thing) thing)
(defun constantly (thing) (lambda () thing))
(defun rest (array) (chain array (slice 1)))
(defun map (fn thing)
(if (object? thing)
(let ((res (-array)))
(for-in (k thing) (chain res (push (fn (aref thing k) k))))
res)
(loop for elem in thing collect (fn elem))))
(defun copy-list (list)
(map identity list))
(defun sort (list comparison &key (key identity))
(chain (copy-list list)
(sort (lambda (a b)
(let ((a^ (key a))
(b^ (key b)))
(cond ((comparison a^ b^) -1)
((comparison b^ a^) 1)
(t 0)))))))
(defun reverse (list)
(chain (copy-list list) (reverse)))
(defun fold (fn memo thing)
(let ((m memo))
(if (object? thing)
(for-in (k thing) (setf m (fn (aref thing k) m)))
(loop for elem in thing do (setf m (fn elem m))))
m))
(defun filter (fn thing)
(loop for elem in thing when (fn elem) collect elem))
(defun extend (obj &rest other-objs)
(flet ((ext! (dest src) (map (lambda (v k) (setf (aref dest k) v)) src)))
(let ((res (create)))
(ext! res obj)
(map (lambda (obj) (ext! res obj)) other-objs)
res)))
(defun append-new (list-a list-b)
(let ((s (new (-set list-a)))
(lst (map #'identity list-a)))
(loop for elem in list-b
unless (chain s (has elem))
do (chain lst (push elem)))
lst))
(defun lines (string) (chain string (split #\newline)))
(defun join (strings &optional (separator "")) (chain strings (join separator)))
;; basic timeout/interval stuff
(defvar *intervals-and-timeouts* (create))
(defun clear-all-delays! ()
(map
(lambda (v) (clear-timeout v) (clear-interval v))
*intervals-and-timeouts*)
(setf *intervals-and-timeouts* (create)))
(defun clear-delay! (name)
($aif (@ *intervals-and-timeouts* name)
(progn (clear-timeout it) (clear-interval it)))
nil)
(defun interval! (name fn delay)
(clear-delay! name)
(setf (@ *intervals-and-timeouts* name)
(set-interval fn delay)))
(defun timeout! (name fn delay)
(clear-delay! name)
(setf (@ *intervals-and-timeouts* name)
(set-interval fn delay)))
;; basic hash/array stuff
(defun vals (obj) (map identity obj))
(defun keys (obj) (map (lambda (v k) k) obj))
(defun last (array) (aref array (- (length array) 1)))
(defun member? (elem thing)
(if (object? thing)
(in elem thing)
(> (chain thing (index-of elem)) -1)))
(defun equal? (a b)
(let ((type-a (typeof a))
(type-b (typeof b)))
(and (equal type-a type-b)
(cond
((member? type-a (list "number" "string" "function"))
(equal a b))
((array? a)
(and
(= (length a) (length b))
(loop for elem-a in a for elem-b in b
unless (equal? elem-a elem-b) return f
finally (return t))))
((object? a)
;; object comparison here
;; and
;; all keys of a are in b
;; all keys of b are in a
;; all keys of a and b have the same values
nil)))))
;; basic regex stuff
(defun regex-match (regex string)
(chain (-reg-exp regex) (test string)))
(defun regex-match-any (string &rest regexes)
(loop for reg in regexes
when (regex-match reg string) return t
finally (return nil)))
(defun matching? (regex)
(lambda (string) (regex-match regex string)))
;; basic DOM/event stuff
(defun add-listener! (elem event-name fn)
(cond ((@ elem add-event-listener)
(chain elem (add-event-listener event-name fn)))
((@ elem attach-event)
(chain elem attach-event (+ "on" event-name) fn))
(t (setf (aref elem (+ "on" event-name)) fn))))
(defun dom-ready (callback)
(add-listener! document "DOMContentLoaded" callback))
(defun remove-all-event-handlers (elem)
(let ((clone (chain elem (clone-node t))))
(chain elem parent-node (replace-child clone elem))
clone))
(defun prevent (ev) (when ev (chain ev (prevent-default))))
(defun debounce (fn delay immediate?)
(let ((timeout))
(lambda ()
(let ((context this)
(args arguments))
(clear-timeout timeout)
(setf timeout (set-timeout
(lambda ()
(setf timeout nil)
(unless immediate?
(chain fn (apply context args))))
delay))
(when (and immediate? (not timeout))
(chain fn (apply context args)))))))
(defun scroll-to-elem (elem)
(let ((x (@ elem offset-left))
(y (@ elem offset-top)))
(chain window (scroll-to x y))))
(defun show! (elem)
(setf (@ elem hidden) nil))
(defun hide! (elem)
(setf (@ elem hidden) t))
(defun by-selector (a &optional b)
(let ((object (if b a document))
(selector (or b a)))
(chain object (query-selector selector))))
(defun by-selector-all (a &optional b)
(let ((object (if b a document))
(selector (or b a)))
(chain object (query-selector-all selector))))
(defun dom-empty! (elem)
(setf (@ elem inner-h-t-m-l) ""))
(defun dom-empty? (elem)
(string= "" (@ elem inner-h-t-m-l)))
(defun dom-escape (string)
(when (string? string)
(chain string
(replace "<" "<")
(replace ">" ">"))))
(defun dom-append (elem markup)
(let ((new-content (chain document (create-element "span"))))
(setf (@ new-content inner-h-t-m-l) markup)
(loop while (@ new-content first-child)
do (chain elem (append-child (@ new-content first-child))))))
(defun dom-replace (elem markup)
(let ((new-content (chain document (create-element "span")))
(parent (@ elem parent-node)))
(setf (@ new-content inner-h-t-m-l) markup)
(loop for child in (@ new-content child-nodes)
do (chain parent (insert-before new-content elem)))
(chain elem (remove))))
(defun dom-set (elem markup)
(setf (@ elem inner-h-t-m-l) markup))
;; basic type stuff
(defun number? (obj) (string= "number" (typeof obj)))
(defun string? (obj) (string= "string" (typeof obj)))
(defun function? (obj) (string= "function" (typeof obj)))
(defun type? (obj type-string)
(eql (chain -object prototype to-string (call obj)) type-string))
(defun array? (arr) (type? arr "[object Array]"))
(defun object? (obj) (type? obj "[object Object]"))
;; basic encoding/decoding stuff
(defun encode (string)
(encode-u-r-i-component string))
(defun decode (string)
(decode-u-r-i string))
(defun string->obj (string)
(chain -j-s-o-n (parse string)))
(defun obj->string (object)
(chain -j-s-o-n (stringify object)))
(defun obj->params (object)
(join
(map (lambda (v k)
(+ (encode k) "="
(encode (if (object? v) (obj->string v) v))))
object)
"&"))
;; basic AJAX stuff
(defun save-file (filename contents &optional (type "application/json;charset=utf-8"))
(let* ((content-string (if (string? contents) contents (obj->string contents)))
(blob (new (-blob (list content-string) (create :type type)))))
(save-as blob filename)))
(defun get-page-hash ()
(let ((hash (@ window location hash))
(res (create)))
(when hash
(loop for pair in (chain (rest hash) (split "&"))
for (k v) = (chain pair (split "="))
do (setf (aref res (decode k)) (decode v)))
res)))
(defun set-page-hash (hash-object)
(setf (@ window location hash) (obj->params hash-object)))
(defun get (uri params callback)
(let ((req (new (-x-m-l-http-request))))
(setf (@ req onreadystatechange)
(lambda ()
(when (and (equal (@ req ready-state) 4)
(equal (@ req status) 200))
(let ((result (@ req response-text)))
(callback result)))))
(chain req (open :GET (if params (+ uri "?" (obj->params params)) uri) t))
(chain req (send))))
(defun get/json (uri params callback)
(get uri params
(lambda (raw)
(when (function? callback)
(callback (string->obj raw))))))
(defun post (uri params on-success on-fail)
(let ((req (new (-x-m-l-http-request)))
(encoded-params (obj->params params)))
(setf (@ req onreadystatechange)
(lambda ()
(when (equal (@ req ready-state) 4)
(if (equal (@ req status) 200)
(when (function? on-success)
(let ((result (@ req response-text)))
(on-success result)))
(when (function? on-fail)
(on-fail req))))))
(chain req (open :POST uri t))
(chain req (set-request-header "Content-type" "application/x-www-form-urlencoded"))
(chain req (send encoded-params))))
(defun post/json (uri params on-success on-fail)
(post uri params
(lambda (raw)
(when (function? on-success)
(on-success (string->obj raw))))
on-fail))
(defun event-source (uri bindings)
(let ((stream (new (-event-source uri))))
(setf (@ stream onopen) (lambda (e) (console.log "Stream OPENED!"))
(@ stream onerror) (lambda (e) (console.log "Stream ERRORED!"))
(@ stream onmessage)
(lambda (e)
(let* ((res (string->obj (@ e data)))
(callback (aref bindings (@ res action))))
(if callback
(funcall callback res)
(console.log "Unhandled message" res)))))
stream))))
(define-handler (js/base.js :content-type "application/javascript") ()
*base-js*)
| 10,935 | Common Lisp | .lisp | 264 | 30.893939 | 91 | 0.531644 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | ef4abe5eb8f59e82eb7d421138c2334085588c262a340c4c5409359e9742ced6 | 2,564 | [
-1
] |
2,565 | pareditesque.lisp | inaimathi_cl-notebook/src/ui/http-front-end/pareditesque.lisp | (in-package :cl-notebook)
(define-handler (js/pareditesque.js :content-type "application/javascript") ()
(ps
;;;;;;;;;; Utility for s-exp navigation
;;;;;;;;;;;;;;;
(defun matching-brace (brace)
(aref
(create "(" ")" ")" "("
"[" "]" "]" "["
"{" "}" "}" "{"
"<" ">" ">" "<")
brace))
;;;;;;;;;; Basic codemirror-related predicates and getters
;;;;;;;;;;;;;;;
(defun at-beginning? (mirror &key (ls (lines (mirror-contents mirror))))
(with-slots (line ch) (get-cur :right mirror)
(and (>= 0 line) (>= 0 ch))))
(defun at-end? (mirror &key (ls (lines (mirror-contents mirror))))
(with-slots (line ch) (get-cur :right mirror)
(and (>= line (- (length ls) 1))
;; the line length doesn't include newline
;; so we don't subtract one here
(>= ch (length (last ls))))))
(defun at-empty-line? (mirror &key (ls (lines (mirror-contents mirror))))
(with-slots (line ch) (get-cur :right mirror)
(= 0 (length (aref ls line)))))
(defun cur-compare (a b)
(cond ((and (= (@ a line) (@ b line)) (= (@ a ch) (@ b ch)))
:eq)
((= (@ a line) (@ b line))
(if (> (@ a ch) (@ b ch))
:gt
:lt))
((> (@ a line) (@ b line)) :gt)
(t :lt)))
(defun mirror-contents (mirror)
(chain mirror (get-value)))
(defun get-cur (direction mirror &optional (component :head))
(with-slots (line ch) (chain mirror (get-cursor component))
(create :line line :ch (if (= direction :left) (- ch 1) ch))))
(defun token-type-at-cursor (direction mirror)
(with-slots (line ch) (get-cur direction mirror)
(chain mirror (get-token-type-at (create :line line :ch (+ 1 ch))))))
(defun token-type-at-cursor? (direction mirror type)
(= type (token-type-at-cursor direction mirror)))
(defun string-at-cursor? (direction mirror)
(token-type-at-cursor? direction mirror :string))
(defun bracket-at-cursor? (direction mirror)
(token-type-at-cursor? direction mirror :bracket))
(defun go-char (direction mirror)
(chain mirror (exec-command
(case direction
(:left "goCharLeft")
(:right "goCharRight")))))
(defun go-line (direction mirror)
(chain mirror (exec-command
(case direction
(:up "goLineUp")
(:down "goLineDown")))))
(defun char-at-cursor (direction mirror &key (ls (lines (mirror-contents mirror))))
(with-slots (line ch) (get-cur direction mirror)
(aref ls line ch)))
(defun char-at-cursor? (direction mirror char &key (ls (lines (mirror-contents mirror))))
(= char (char-at-cursor direction mirror :ls ls)))
;;;;;;;;;; Character skipping for code-mirror contents
;;;;;;;;;;;;;;;
(defun skip-while (fn mirror direction &key (ls (lines (mirror-contents mirror))))
(let ((til (case direction
(:left #'at-beginning?)
(:right #'at-end?))))
(loop until (til mirror ls) while (fn (char-at-cursor direction mirror :ls ls))
do (go-char direction mirror))))
(defun skip-until (fn mirror direction &key (ls (lines (mirror-contents mirror))))
(let ((til (case direction
(:left #'at-beginning?)
(:right #'at-end?))))
(loop do (go-char direction mirror) until (til mirror ls)
until (fn (char-at-cursor direction mirror :ls ls)))))
(defun skip-to (direction mirror chars &key (ls (lines (mirror-contents mirror))))
(let ((s (new (-set chars))))
(skip-until (lambda (char) (chain s (has char))) mirror direction :ls ls)))
(defun skip-over (direction mirror chars &key (ls (lines (mirror-contents mirror))))
(let ((s (new (-set chars))))
(skip-while (lambda (char) (chain s (has char))) mirror direction :ls ls)))
(defun skip-whitespace (direction mirror &key (ls (lines (mirror-contents mirror))))
(skip-over direction mirror (list #\space #\newline #\tab undefined) :ls ls))
;;;;;;;;;; block navigation
;;;;;;;;;;;;;;;
(defun go-block (direction mirror)
(let ((til (case direction
(:up #'at-beginning?)
(:down #'at-end?)))
(ls (lines (mirror-contents mirror))))
(when (at-empty-line? mirror :ls ls) (go-line direction mirror))
(loop until (or (til mirror :ls ls) (at-empty-line? mirror :ls ls))
do (go-line direction mirror))))
(defun select-block (direction mirror)
(let ((start (get-cur direction mirror)))
(go-block direction mirror)
(chain mirror (extend-selection (get-cur direction mirror) start))))
;;;;;;;;;; s-exp navigation
;;;;;;;;;;;;;;;
(defun go-sexp (direction mirror)
(destructuring-bind (paren til)
(case direction
(:right (list "(" #'at-end?))
(:left (list ")" #'at-beginning?)))
(let ((ls (lines (mirror-contents mirror)))
(other-paren (matching-brace paren)))
(skip-whitespace direction mirror :ls ls)
(cond ((and (string-at-cursor? direction mirror) (not (char-at-cursor? direction mirror "\"" :ls ls)))
(skip-to direction mirror (list " " "\"" undefined) :ls ls))
((string-at-cursor? direction mirror)
(skip-until
(lambda (c) (not (string-at-cursor? direction mirror)))
mirror direction :ls ls))
((token-type-at-cursor? direction mirror :comment)
(skip-to direction mirror (list " " undefined) :ls ls))
((token-type-at-cursor? direction mirror :quote-char)
(skip-until
(lambda (c) (not (token-type-at-cursor? direction mirror :quote-char)))
mirror direction :ls ls)
(go-sexp direction mirror))
((and (bracket-at-cursor? direction mirror)
(char-at-cursor? direction mirror other-paren :ls ls))
(go-char direction mirror))
((and (bracket-at-cursor? direction mirror)
(char-at-cursor? direction mirror paren :ls ls))
(loop with tally = 1 until (til mirror :ls ls)
do (go-char direction mirror)
when (and (char-at-cursor? direction mirror paren :ls ls)
(not (string-at-cursor? direction mirror)))
do (incf tally)
when (and (char-at-cursor? direction mirror other-paren :ls ls)
(not (string-at-cursor? direction mirror)))
do (decf tally)
until (and (char-at-cursor? direction mirror other-paren :ls ls) (= 0 tally)))
(go-char direction mirror))
(t
(skip-to direction mirror (+ " " other-paren) :ls ls))))))
(defun select-sexp (direction mirror)
(destructuring-bind (desired opposite)
(case direction
(:left (list :gt :right))
(:right (list :lt :left)))
(let ((start (get-cur :right mirror :anchor))
(end (get-cur :right mirror)))
(go-sexp direction mirror)
(if (and (chain mirror (something-selected))
(= desired (cur-compare start end)))
(chain mirror (extend-selection end))
(chain mirror (set-selection start (get-cur :right mirror)))))))
(defun kill-sexp (direction mirror)
(replace-sexp-at-point direction mirror ""))
;;;;;;;;;; s-exp extras
(defun sexp-at-point (direction mirror)
(let ((start (get-cur direction mirror)))
(go-sexp direction mirror)
(let ((res (chain mirror (get-range start (get-cur :right mirror)))))
(chain mirror (set-cursor start))
res)))
(defun replace-sexp-at-point (direction mirror new-sexp)
(let ((start (get-cur direction mirror)))
(go-sexp direction mirror)
(chain mirror (replace-range new-sexp start (get-cur :right mirror)))))
(defun slurp-sexp (direction mirror)
(console.log "TODO -- slurp-sexp"))
(defun barf-sexp (direction mirror)
(console.log "TODO -- barf-sexp"))
(defun transpose-sexp (direction mirror)
(console.log "TODO -- transpose-sexp"))
(defun toggle-comment-region (mirror)
(let ((anchor (get-cur :right mirror :anchor))
(head (get-cur :right mirror :head)))
(destructuring-bind (from to) (if (> (@ anchor line) (@ head line)) (list head anchor) (list anchor head))
(if (token-type-at-cursor? :right mirror :comment)
(chain mirror (uncomment from to))
(chain mirror (line-comment from to))))))
;;;;;;;;;; cell navigation
(defun go-cell (direction cell-id)
(let* ((cell (by-cell-id cell-id))
(next (case direction
(:down (@ cell next-sibling))
(:up (@ cell previous-sibling)))))
(when next
(scroll-to-elem next)
(show-editor (elem->cell-id next)))))
(defun transpose-cell! (direction cell-id)
(let* ((cell (by-cell-id cell-id))
(next (case direction
(:down (@ cell next-sibling))
(:up (@ cell previous-sibling)))))
(when next
(cond ((equal :up direction)
(chain next parent-node (insert-before cell next)))
((and (equal :down direction) (@ next next-sibling))
(chain next parent-node (insert-before cell (@ next next-sibling))))
(t
(chain next parent-node (append-child cell))))
(reorder-cells nil)
(scroll-to-elem cell)
(show-editor cell-id))))))
| 8,914 | Common Lisp | .lisp | 202 | 38.331683 | 107 | 0.621721 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 5c014bbee293e1d3f13d5ae130dff60cd49021e2c5cafd0230fb218a930af965 | 2,565 | [
-1
] |
2,566 | notebook-selector.lisp | inaimathi_cl-notebook/src/ui/http-front-end/notebook-selector.lisp | (in-package :cl-notebook)
(define-handler (js/notebook-selector.js :content-type "application/javascript") ()
(ps
(defvar *current-fs-listing* nil)
(defun common-prefix-of (starting-point strings)
(let ((max-prefix (loop for s in strings minimize (length s)))
(same-at? (lambda (ix)
(let ((chr (aref strings 0 ix))
(res t))
(loop for s in strings unless (string= (aref s ix) chr) do (setf res f))
res))))
(+ starting-point
(join
(loop for i from (length starting-point) to max-prefix
when (same-at? i) collect (aref strings 0 i))))))
(defun notebook-link-template (notebook current-notebook-id)
(if (equal? current-notebook-id (@ notebook :path))
(who-ps-html
(:li :class "book-link current-book" :title (@ notebook :path) (@ notebook :title)))
(who-ps-html
(:li :class "book-link" :title (@ notebook :path)
(:a :href (+ "/#book=" (@ notebook :path)) (@ notebook :title))))))
(defvar filesystem-input-change
(debounce
(lambda (event elem)
(let* ((val (@ elem value))
(dval (if (chain val (ends-with "/")) val (+ val "/")))
(filtered (filter-fs-listing *current-fs-listing* val))
(fnames (map (lambda (d) (@ d :string)) (@ filtered :files)))
(dirnames (map (lambda (d) (@ d :string)) (@ filtered :directories)))
(key-code (@ event key-code)))
(cond
((= 9 key-code)
(chain event (prevent-default))
(chain elem (focus))
(let ((completed (common-prefix-of val (chain fnames (concat dirnames)))))
(setf (@ elem value) completed)
(when (chain completed (ends-with "/"))
(filesystem! (by-selector ".filesystem-view") completed))))
((and (= key-code 13) (member? val fnames))
(setf (@ window location href) (+ "/#book=" val)))
((and (member? key-code (list 13 47)) (member? dval dirnames))
(filesystem! (by-selector ".filesystem-view") dval))
((and (= 13 key-code))
(new-book val))
((or (= 8 key-code) (= 46 key-code))
(filesystem!
(by-selector ".filesystem-view")
(+ (chain val (split "/") (slice 0 -1) (join "/")) "/")
:filter? f))
((not (= 0 (@ event char-code)))
(unless (and (= 0 (length (@ filtered :directories))) (= 0 (length (@ filtered :files))))
(render-filesystem! (by-selector ".filesystem-view") filtered))))))
200))
(defun filesystem-directory-click (directory)
(setf (@ (by-selector ".filesystem-input") value) directory)
(filesystem! (by-selector ".filesystem-view") directory))
(defun selector-template ()
(who-ps-html
(:div :class "notebook-selector"
(:ul :class "loaded-books-list")
(:input :class "filesystem-input" :onkeydown "filesystemInputChange(event, this)")
(:span :class "filesystem-view"))))
(defun file-template (file)
(who-ps-html
(:li :class "file-link"
(:a :href (+ "/#book=" (@ file :string)) (@ file :name)))))
(defun directory-template (directory)
(let ((call (+ "filesystemDirectoryClick('" (@ directory :string) "')")))
(who-ps-html
(:li :class "directory-link"
(:span :class "directory-link" :onclick call
(last (@ directory :directory)))))))
(defun filesystem-template (listing)
(who-ps-html
(:ul :class "filesystem-list"
(+ (join (map directory-template (@ listing :directories)))
(join (map file-template (@ listing :files)))))))
(defun filter-fs-listing (listing prefix)
(if listing
(let ((f (lambda (path) (chain (@ path :string) (starts-with prefix)))))
(create :directories (filter f (@ listing :directories))
:files (filter f (@ listing :files))))
(create :directories (list) :files (list))))
(defun render-filesystem! (elem listing)
(dom-set elem (filesystem-template listing)))
(defun filesystem! (elem directory &key (filter? t))
(get/json "/cl-notebook/system/ls" (create :dir directory)
(lambda (dat)
(setf *current-fs-listing*
(create :directories (or (@ dat :directories) (list))
:files (or (@ dat :files) (list))))
(render-filesystem!
elem
(if filter?
(filter-fs-listing
*current-fs-listing*
(@ (by-selector ".filesystem-input") value))
*current-fs-listing*)))))
(defun get-loaded-books! (elem current-notebook-id)
(get/json
"/cl-notebook/loaded-books" (create)
(lambda (dat)
(dom-set
elem
(join
(map
(lambda (bk)
(notebook-link-template bk current-notebook-id))
dat))))))
(defun notebook-selector! (selector)
(let ((elem (by-selector selector)))
(dom-set elem (selector-template))
(get-loaded-books!
(by-selector elem ".loaded-books-list")
(@ *notebook* id))
(chain (by-selector elem ".filesystem-input") (focus))
(get/json "/cl-notebook/system/home-path" (create)
(lambda (initial-dir)
(setf (@ (by-selector elem ".filesystem-input") value) initial-dir)
(filesystem! (by-selector elem ".filesystem-view") initial-dir)))))))
| 5,910 | Common Lisp | .lisp | 121 | 35.975207 | 103 | 0.526234 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 744e167771848052c985c5133f9354a95d377c5a91484f014b2a6a5abb936fb4 | 2,566 | [
-1
] |
2,567 | core.lisp | inaimathi_cl-notebook/src/ui/http-front-end/core.lisp | (in-package :cl-notebook)
(define-handler (/) ()
(with-html-output-to-string (s nil :prologue t :indent t)
(:html
(:head
(:title "cl-notebook")
(:link :rel "stylesheet" :href "/css/notebook.css")
(:link :rel "stylesheet" :href "/static/css/genericons.css")
(:link :rel "stylesheet" :href "/static/css/codemirror.css")
(:link :rel "stylesheet" :href "/static/css/dialog.css")
(:link :rel "stylesheet" :href "/static/css/show-hint.css")
(:script
:type "text/javascript"
(str
(format
nil "var CLNOTEBOOK = ~a"
(json:encode-json-to-string
(hash
:formats
(hash :eval (front-end-eval-formats)
:export (export-book-formats)))))))
(:script :type "text/javascript" :src "/js/base.js")
(:script :type "text/javascript" :src "/static/js/Blob.js")
(:script :type "text/javascript" :src "/static/js/FileSaver.js")
(:script :type "text/javascript" :src "/js/templates.js")
(:script :type "text/javascript" :src "/js/api.js")
(:script :type "text/javascript" :src "/js/core.js")
(:script :type "text/javascript" :src "/js/pareditesque.js")
(:script :type "text/javascript" :src "/js/notebook-selector.js")
(:script :type "text/javascript" :src "/static/js/native-sortable.js")
(:script :type "text/javascript" :src "/static/js/codemirror.js")
(:script :type "text/javascript" :src "/static/js/modes/commonlisp.js")
(:script :type "text/javascript" :src "/static/js/addons/comment.js")
(:script :type "text/javascript" :src "/static/js/addons/closebrackets.js")
(:script :type "text/javascript" :src "/static/js/addons/matchbrackets.js")
(:script :type "text/javascript" :src "/static/js/addons/search.js")
(:script :type "text/javascript" :src "/static/js/addons/searchcursor.js")
(:script :type "text/javascript" :src "/static/js/addons/match-highlighter.js")
(:script :type "text/javascript" :src "/static/js/addons/active-line.js")
(:script :type "text/javascript" :src "/static/js/addons/mark-selection.js")
(:script :type "text/javascript" :src "/static/js/addons/show-hint.js")
(:script :type "text/javascript" :src "/static/js/addons/anyword-hint.js")
(:script :type "text/javascript" :src "/static/js/addons/dialog.js")
(:script :type "text/javascript" :src "/static/js/addons/runmode/runmode.js"))
(:body
(:span :id "cl-notebook-front-end-addons"
(:link :rel "stylesheet" :href "/css/notebook-addons.css"))
(:div :id "macro-expansion" (:textarea :language "commonlisp"))
(:div :id "notebook")
(:div :class "main-controls"
(:div :id "notebook-selector")
(:input :id "book-history-slider" :onchange "rewindBook(this.value)" :oninput "debouncedRewind(this.value)" :type "range" :min 0 :max 500 :value 500)
(:button :onclick "newCell()" "> New Cell")
(:button :onclick "toggleOpenBookMenu()" "> Open Book")
(:select :id "book-exporters"
:onchange "exportBook(this.value)"
:onselect "exportBook(this.value)"
(:option :value "" "Export as...")
(loop for format in (export-book-formats)
do (htm (:option :value format (str format)))))
(:div :class "thread-controls"
(:span :class "notice" "Processing")
(:img :src "/static/img/dots.png")
(:button :onclick "killThread()" :class "right" "! Abort")))))))
(define-handler (js/core.js :content-type "application/javascript") ()
(ps
;; cl-notebook specific utility
(defun by-cell-id (cell-id &rest children)
(by-selector
(+ "#cell-" cell-id
(if (> (length children) 0) " " "")
(join children " "))))
(defun elem->cell-id (elem)
(parse-int
(chain elem (get-attribute "id")
(match (-reg-exp "cell-([1234567890]+)"))
1)))
(defun elem-to-cell (elem)
(aref *notebook* :objects (elem->cell-id elem)))
(defun clear-selection ()
(let ((sel (chain window (get-selection))))
(if (@ sel empty)
;; chrome
(chain sel (empty))
;; firefox
(chain sel (remove-all-ranges)))))
(defun select-contents (ev elem)
(unless (@ ev shift-key)
(clear-selection))
(let ((r (new (-range))))
(chain r (select-node-contents elem))
(chain window (get-selection) (add-range r))))
(defun in-present? ()
(let ((slider (by-selector "#book-history-slider")))
(= (@ slider value) (chain slider (get-attribute :max)))))
(defun post/fork (uri args on-success on-fail)
(if (in-present?)
(post/json uri args on-success on-fail)
(fork-book (lambda (res)
(surgical! res)
(setf document.title (+ (@ res book-name) " - cl-notebook"))
(setf (@ args :book) (@ res id))
(dom-replace (by-selector ".book-title") (notebook-title-template (@ res book-name)))
(post/json uri args on-success on-fail)))))
;; cl-notebook specific events
(defun reload-addon-resources! (resource-type resource-name)
(console.log "RELOADING" resource-type resource-name "(TODO - be surgical about this)")
(dom-set
(by-selector "#cl-notebook-front-end-addons")
(who-ps-html
(:link :rel "stylesheet" :href (+ "/css/notebook-addons.css?now=" (now!))))))
(defun hash-updated ()
(let ((book-name (@ (get-page-hash) :book)))
(when book-name
(notebook/current book-name))
(dom-set (by-selector "#notebook-selector") "")))
(defun esc-pressed ()
(clear-selection)
(hide-title-input)
(hide-macro-expansion!)
(hide-open-book-menu!)
(map (lambda (cell)
(with-slots (id cell-type) cell
(when (= :markup cell-type)
(hide-editor id))))
(notebook-cells *notebook*)))
;; cl-notebook specific DOM manipulation
(defun display-book (book-name)
(when book-name
(set-page-hash (create :book book-name))
(hash-updated)))
(defun hide-open-book-menu! ()
(dom-set (by-selector "#notebook-selector") ""))
(defun toggle-open-book-menu ()
(let ((el (by-selector "#notebook-selector")))
(if (dom-empty? el)
(notebook-selector! "#notebook-selector")
(dom-set el ""))))
(defun dom-replace-cell-value! (cell)
(when (@ cell result)
(let ((res (@ cell result result)))
(dom-set (by-cell-id (@ cell :id) ".cell-value")
(cell-value-template cell)))))
(defun dom-replace-cell (cell)
(dom-replace (by-cell-id (@ cell id)) (cell-template cell))
(setup-cell-mirror! cell))
;; CodeMirror and utilities
(defun register-helpers (type object)
(map
(lambda (fn name)
(chain -code-mirror
(register-helper type name fn)))
object))
(defun register-commands (object)
(map
(lambda (fn name)
(setf (aref -code-mirror :commands name) fn))
object))
(defun show-editor (cell-id)
(show! (by-cell-id cell-id ".CodeMirror"))
(chain (cell-mirror cell-id) (focus)))
(defun hide-editor (cell-id)
(hide! (by-cell-id cell-id ".CodeMirror")))
(defun cell-mirror (cell-id)
(@ (notebook-cell *notebook* cell-id) editor))
(defun cell-editor-contents (cell-id)
(chain (cell-mirror cell-id) (get-value)))
(defun eval-ps-cell! (cell)
(with-captured-log log-output
(chain
cell result
(push
(try
(let* ((res (window.eval (@ cell result 0 values 0 value)))
(tp (typeof res)))
(create
:stdout (join log-output #\newline) :warnings nil
:values (list (create :type tp :value (+ "" res)))))
(:catch (err)
(create
:stdout (join log-output #\newline) :warnings nil
:values (list (create :type "error" :value (list err.message))))))))))
(defun mirror! (text-area &key (extra-keys (create)) (line-wrapping? t))
(let ((options
(create
"async" t
"lineNumbers" t
"matchBrackets" t
"autoCloseBrackets" t
"lineWrapping" line-wrapping?
"viewportMargin" -infinity
"smartIndent" t
"extraKeys" (extend
(create "Ctrl-Space" 'autocomplete
"Ctrl-Right" (lambda (mirror) (go-sexp :right mirror))
"Ctrl-Left" (lambda (mirror) (go-sexp :left mirror))
"Shift-Ctrl-Right" (lambda (mirror) (select-sexp :right mirror))
"Shift-Ctrl-Left" (lambda (mirror) (select-sexp :left mirror))
"Ctrl-Down" (lambda (mirror) (go-block :down mirror))
"Shift-Ctrl-Down" (lambda (mirror) (select-block :down mirror))
"Ctrl-Up" (lambda (mirror) (go-block :up mirror))
"Shift-Ctrl-Up" (lambda (mirror) (select-block :up mirror))
"Ctrl-Alt-K" (lambda (mirror) (kill-sexp :right mirror))
"Shift-Ctrl-Alt-K" (lambda (mirror) (kill-sexp :left mirror))
"Tab" 'indent-auto
"Ctrl-;" (lambda (mirror) (toggle-comment-region mirror)))
extra-keys))))
(chain -code-mirror (from-text-area text-area options))))
(defun setup-cell-mirror! (cell)
(let* ((cell-id (@ cell id))
(mirror (mirror! (by-cell-id cell-id ".cell-contents")
:extra-keys (create
"Ctrl-Enter"
(lambda (mirror)
(let ((contents (cell-editor-contents cell-id)))
(notebook/eval-to-cell cell-id contents)))
"Ctrl-]" (lambda (mirror) (go-cell :down cell-id))
"Ctrl-[" (lambda (mirror) (go-cell :up cell-id))
"Shift-Ctrl-]" (lambda (mirror) (transpose-cell! :down cell-id))
"Shift-Ctrl-[" (lambda (mirror) (transpose-cell! :up cell-id))
"Shift-Ctrl-E" (lambda (mirror)
(show-macro-expansion!)
(chain *macro-expansion-mirror* (focus)))
"Ctrl-E" (lambda (mirror)
(system/macroexpand-1
(sexp-at-point :right mirror)
(lambda (res)
(show-macro-expansion!)
(chain *macro-expansion-mirror*
(set-value res)))))
"Ctrl-Space" (lambda (mirror)
(console.log "TOKEN: " (token-type-at-cursor :right mirror)))
"Ctrl-Delete" (lambda (mirror)
(kill-cell cell-id)
(let ((prev (get-cell-before *notebook* cell-id)))
(when prev
(show-editor (@ prev id)))))))))
(setf (@ cell editor) mirror)
(chain mirror (on 'cursor-activity
(lambda (mirror)
(unless (chain mirror (something-selected))
(chain mirror (exec-command 'show-arg-hint))))))
(chain mirror (on 'change
(lambda (mirror)
(let ((elem (by-cell-id (@ cell id))))
(if (= (chain mirror (get-value)) (@ cell contents))
(chain elem class-list (remove "stale"))
(chain elem class-list (add "stale")))))))
(unless (= (@ cell type) "markup")
(chain mirror (on 'change
(lambda (mirror change)
(when (or (= "+input" (@ change origin)) (= "+delete" (@ change origin)))
(chain -code-mirror commands
(autocomplete
mirror (@ -code-mirror hint ajax)
(create :async t "completeSingle" false))))))))
mirror))
;; Notebook-related
(defvar *notebook*)
(defun notebook-condense (notebook)
(let ((res (create)))
(loop for (id prop val) in notebook
unless (aref res id) do (setf (aref res id) (create :id id))
do (if (null val)
(setf (aref res id :type) prop)
(setf (aref res id prop) val)))
res))
(defun notebook-name (notebook) (@ notebook name))
(defun notebook-package (notebook) (@ notebook package))
(defun notebook-id (notebook) (@ notebook id))
(defun notebook-name! (notebook new-name) (setf (@ notebook name) new-name))
(defun notebook-package! (notebook new-package) (setf (@ notebook package) new-package))
(defun notebook-facts (notebook) (@ notebook facts))
(defun notebook-objects (notebook) (@ notebook objects))
(defun notebook-cell-ordering! (notebook new-order)
(let ((id (or (loop for (a b c) in (notebook-facts notebook)
when (= b 'cell-order) do (return a))
-1)))
(setf
(@ notebook facts)
(chain
(list (list id 'cell-order new-order))
(concat
(filter
(lambda (fact) (not (= (@ fact 1) 'cell-order)))
(notebook-facts notebook))))
(aref (@ notebook objects) id) (create id id cell-order new-order))))
(defun notebook-cell-ordering (notebook)
(let ((ord (loop for (a b c) in (notebook-facts notebook)
when (= b 'cell-order) do (return c)))
(all-cell-ids
(loop for (a b c) in (notebook-facts notebook)
when (and (= b 'cell) (null c)) collect a)))
(chain all-cell-ids (reverse))
(if ord
(append-new ord all-cell-ids)
all-cell-ids)))
(defun notebook-cells (notebook)
(let ((obj (notebook-objects notebook))
(ord (notebook-cell-ordering notebook)))
(loop for id in ord for res = (aref obj id)
when res collect res)))
(defun notebook-cell (notebook id)
(aref notebook :objects id))
(defun unfocus-cells ()
(loop for c in (by-selector-all ".cell.focused")
do (chain c class-list (remove "focused"))))
(defun focus-cell (cell-id)
(let ((cell (by-cell-id cell-id)))
(unless (chain cell class-list (contains "focused"))
(unfocus-cells)
(chain (by-cell-id cell-id) class-list (add "focused")))))
(defun get-cell-after (notebook cell-id)
(loop for (a b) on (notebook-cells notebook)
if (and a (= (@ a id) cell-id))
return b))
(defun get-cell-before (notebook cell-id)
(loop for (a b) on (notebook-cells notebook)
if (and b (= (@ b id) cell-id))
return a))
(defun setup-package-mirror! ()
(mirror!
(by-selector ".book-package textarea")
:extra-keys
(create "Ctrl-]" (lambda (mirror)
(let ((next (by-selector ".cells .cell")))
(when next
(hide-title-input)
(scroll-to-elem next)
(show-editor (elem->cell-id next)))))
"Ctrl-Enter" (lambda (mirror)
(repackage-book (chain mirror (get-value))))))
(hide! (by-selector ".book-package")))
(defun setup-macro-expansion-mirror! ()
(setf *macro-expansion-mirror*
(mirror!
(by-selector "#macro-expansion textarea")
:line-wrapping? nil
:extra-keys
(create "Ctrl-E" (lambda (mirror)
(system/macroexpand-1
(sexp-at-point :right mirror)
(lambda (res)
(chain
mirror
(operation
(lambda ()
(let ((start (get-cur :right mirror)))
(replace-sexp-at-point :right mirror res)
(chain mirror (set-selection start (get-cur :right mirror)))
(chain mirror (exec-command 'indent-auto))
(chain mirror (set-cursor start)))))))))))))
(defun surgical! (raw)
(let* ((slider (by-selector "#book-history-slider"))
(count (@ raw history-size))
(pos (or (@ raw history-position) count))
(id (@ raw id)))
(chain slider (set-attribute :max count))
(setf (@ *notebook* id) id
(@ slider value) pos)
(hide! (by-selector ".book-title input"))
(setup-package-mirror!)
(set-page-hash (create :book id))))
(defvar *notebook-loaded-hook*
(lambda () (console.log "FINISHED LOADING BOOK")))
(defun book-ready (callback)
(setf *notebook-loaded-hook* callback)
nil)
(defun notebook! (raw)
(clear-all-delays!)
(let* ((fs (@ raw facts)))
(setf *notebook*
(create :facts fs :objects (notebook-condense fs)
:history-size (@ raw history-size)
:id (@ raw :id)
:name (loop for (a b c) in fs
when (equal b "notebookName")
do (return c))
:package (loop for (a b c) in fs
when (equal b "notebookPackage")
do (return c))))
(map (lambda (cell)
(when (= :parenscript (@ cell cell-type))
(eval-ps-cell! cell)))
(notebook-cells *notebook*))
(dom-set
(by-selector "#notebook")
(notebook-template *notebook*))
(surgical! raw)
(setf document.title (+ (notebook-name *notebook*) " - cl-notebook"))
(nativesortable (by-selector "ul.cells"))
(map (lambda (cell)
(with-slots (id cell-type) cell
(setup-cell-mirror! cell)
(when (= :markup cell-type)
(hide! (by-cell-id id ".CodeMirror")))))
(notebook-cells *notebook*))
(funcall *notebook-loaded-hook*)))
(defun relevant-event? (ev)
(and (in-present?) (equal (notebook-id *notebook*) (@ ev book))))
(defun notebook-events ()
(event-source
"/cl-notebook/source"
(create
'new-cell
(lambda (res)
(when (relevant-event? res)
(let ((id (@ res 'cell-id))
(cell (create 'type "cell" 'contents "" 'result ""
'cell-type (@ res cell-type)
'cell-language (@ res cell-language)
'id (@ res 'cell-id))))
(setf (aref (notebook-objects *notebook*) id) cell)
(chain (notebook-facts *notebook*) (unshift (list id 'cell nil)))
(dom-append (by-selector ".cells")
(cell-template cell))
(setup-cell-mirror! cell)
(scroll-to-elem (by-cell-id id))
(show-editor id))))
'change-cell-type
(lambda (res)
(when (relevant-event? res)
(let ((cell (notebook-cell *notebook* (@ res cell))))
(setf (@ cell cell-type) (@ res new-type))
(dom-replace-cell cell))))
'change-cell-language
(lambda (res)
(when (relevant-event? res)
(let ((cell (notebook-cell *notebook* (@ res cell))))
(setf (@ cell cell-language) (@ res new-language))
(dom-replace-cell cell))))
'change-cell-noise
(lambda (res)
(when (relevant-event? res)
(let ((cell (notebook-cell *notebook* (@ res cell))))
(setf (@ cell noise) (@ res new-noise))
(dom-replace-cell-value! cell))))
'starting-eval
(lambda (res) (show-thread-controls!))
'killed-eval
(lambda (res) (hide-thread-controls!))
'finished-eval
(lambda (res)
(hide-thread-controls!)
(when (relevant-event? res)
(let ((cell (notebook-cell *notebook* (@ res cell))))
(setf (@ cell contents) (@ res contents)
(@ cell result) (@ res result))
(delete (@ cell stale))
(chain (by-cell-id (@ res cell)) class-list (remove "stale"))
(when (= :parenscript (@ cell cell-type))
(eval-ps-cell! cell))
(dom-replace-cell-value! cell))))
'finished-package-eval
(lambda (res)
(hide-thread-controls!)
(let ((id (@ res book))
(new-package (@ res contents))
(err (@ res result)))
(when (relevant-event? res)
(dom-replace (by-selector ".book-package") (notebook-package-template new-package err))
(notebook-package! *notebook* new-package)
(setup-package-mirror!)
(if err
(show-title-input)
(hide-title-input)))))
'addon-updated
(lambda (res)
(reload-addon-resources! (@ res addon-type) (@ res addon-name)))
'loading-package
(lambda (res) (show-thread-controls! (+ "Loading package '" (@ res package) "'")))
'finished-loading-package
(lambda (res) (hide-thread-controls!))
'package-load-failed
(lambda (res) (hide-thread-controls!))
'content-changed
(lambda (res)
(when (relevant-event? res)
(let* ((cell (notebook-cell *notebook* (@ res cell)))
(mirror (cell-mirror (@ res cell)))
(cursor (chain mirror (get-cursor))))
(setf (@ cell contents) (@ res contents)
(@ cell stale) t)
(chain (by-cell-id (@ res cell)) class-list (add "stale"))
(chain mirror (set-value (@ res contents)))
(chain mirror (set-cursor cursor)))))
'kill-cell
(lambda (res)
(when (relevant-event? res)
(delete (aref *notebook* 'objects (@ res cell)))
(chain (by-cell-id (@ res cell)) (remove))))
'reorder-cells
(lambda (res)
(when (relevant-event? res)
(unless (equal? (@ res new-order) (notebook-cell-ordering *notebook*))
(let* ((ord (@ res new-order))
(cs (loop for n in ord
collect (by-cell-id n)))
(elem (by-selector "#notebook .cells")))
(dom-empty! elem)
(loop for c in cs do (chain elem (append-child c)))
(notebook-cell-ordering! *notebook* ord)))))
'new-book
(lambda (res)
(let ((id (@ res book)))
(console.log "NEW BOOK CREATED" book)))
'rename-book
(lambda (res)
(let ((id (@ res book))
(new-name (@ res new-name)))
(when (relevant-event? res)
(dom-replace (by-selector ".book-title") (notebook-title-template new-name))
(notebook-name! *notebook* new-name)
(hide-title-input)))))))
(defvar *warning-filter*
(lambda (w)
(or (chain (@ w condition-type) (starts-with "REDEFINITION"))
(chain (@ w condition-type) (starts-with "IMPLICIT-GENERIC-"))
(and (@ w error-message)
(or (chain (@ w error-message) (starts-with "undefined "))
(chain (@ w error-message) (ends-with "never used.")))))))
(dom-ready
(lambda ()
;;; Setting up some custom CodeMirror code ;;;;;;;;;;;;;;;;;;;;
(register-helpers
"hint"
(create :ajax
(lambda (mirror callback options)
(let* ((cur (chain mirror (get-cursor)))
(tok (chain mirror (get-token-at cur))))
(when (> (length (@ tok string)) 2)
(get "/cl-notebook/system/complete" (create :partial (@ tok string) :package :cl-notebook)
(lambda (res)
(callback
(create :list (or (string->obj res) (new (-array)))
:from (chain -code-mirror (-pos (@ cur line) (@ tok start)))
:to (chain -code-mirror (-pos (@ cur line) (@ tok end))))))))))
:auto
(lambda (mirror options)
(chain -code-mirror commands
(autocomplete mirror (@ -code-mirror hint ajax) (create :async t))))))
(register-commands
(create show-arg-hint
(debounce
(lambda (mirror)
($aif (by-selector-all ".notebook-arg-hint")
(map (lambda (elem) (chain elem (remove))) it))
(labels ((find-first (ctx)
(cond ((null ctx) nil)
((or (= "arglist" (@ ctx node_type))
(and (@ ctx prev)
(@ ctx prev node_type)
(= "arglist" (@ ctx prev node_type)))) nil)
((= "(" (@ ctx opening)) (@ ctx first))
(t (find-first (@ ctx prev))))))
(let* ((coords (chain mirror (cursor-coords)))
(cur (chain mirror (get-cursor)))
(tok (chain mirror (get-token-at cur))))
($aif (and tok (find-first (@ tok state ctx)))
(arg-hint it (+ 1 (@ coords right)) (@ coords bottom))))))
100)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(notebook-events)
(hide-thread-controls!)
(hide-macro-expansion!)
(chain
(by-selector "body")
(add-event-listener
:keydown (key-listener
<esc> (esc-pressed)
"O" (when ctrl?
(toggle-open-book-menu)
(chain event (prevent-default)))
"?" (when ctrl?
(console.log "TODO" :show-help-here))
<space> (when ctrl?
(new-cell)
(chain event (prevent-default))))))
(unless (get-page-hash)
(get/json
"/cl-notebook/loaded-books" (create)
(lambda (dat)
(set-page-hash (create :book (@ dat 0 path))))))
(setup-macro-expansion-mirror!)
(setf (@ window onhashchange) #'hash-updated)
(hash-updated)))))
| 23,878 | Common Lisp | .lisp | 586 | 33.069966 | 154 | 0.584801 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 40aa91c84a88019f11b056375fb382533bfcca2edebf83767685392bfde33fe4 | 2,567 | [
-1
] |
2,568 | macros.lisp | inaimathi_cl-notebook/src/ui/http-front-end/macros.lisp | (in-package #:cl-notebook)
(defparameter +mod-keys+
`((shift? (@ event shift-key)) (alt? (@ event alt-key)) (ctrl? (@ event ctrl-key)) (meta? (@ event meta-key))))
(defparameter +key-codes+
`((<ret> 13) (<esc> 27) (<space> 32) (<up> 38) (<down> 40) (<left> 37) (<right> 39)))
(defpsmacro key-listener (&body key/body-pairs)
`(lambda (event)
(let (,@+mod-keys+
,@+key-codes+
(key-code (or (@ event key-code) (@ event which))))
(cond
,@(loop for (key body) on key/body-pairs by #'cddr
collect `((= key-code ,(if (stringp key) `(chain ,key (char-code-at 0)) key))
,body))))))
(defpsmacro $aif (test if-true &optional if-false)
`(let ((it ,test))
(if it ,if-true ,if-false)))
(defpsmacro with-captured-log (var-name &body body)
(with-gensyms (old-console)
`(let* ((,old-console console.log)
(,var-name (list)))
(setf
console.log
(lambda (&rest args)
(chain ,var-name (push (join (map obj->string args))))))
(try
(progn ,@body)
(:finally (setf console.log ,old-console))))))
| 1,094 | Common Lisp | .lisp | 28 | 33.642857 | 113 | 0.579642 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | f6f3596652209e8a8cf8f3e90e91daba4904121fffcabecf5ad5e07232c066e7 | 2,568 | [
-1
] |
2,569 | commonlisp.js | inaimathi_cl-notebook/static/js/modes/commonlisp.js | CodeMirror.defineMode("commonlisp", function (config) {
var assumeBody = /^with|^def|^lambda|^do|^prog|^f?let\*?|case$|bind$|a?when$|a?unless$/i;
var numLiteral = /^(?:[+\-]?(?:\d+|\d*\.\d+)(?:[efd][+\-]?\d+)?|[+\-]?\d+(?:\/[+\-]?\d+)?|#b[+\-]?[01]+|#o[+\-]?[0-7]+|#x[+\-]?[\da-f]+)/;
var symbol = /[^\s'`,@()\[\]";]/;
var builtin = /^(if|when|cond|lambda|case|f?let\*?|loop|prog.)$/i;
var type;
function readSym(stream) {
var ch;
while (ch = stream.next()) {
if (ch == "\\") stream.next();
else if (!symbol.test(ch)) { stream.backUp(1); break; }
}
return stream.current();
}
function base(stream, state) {
if (stream.eatSpace()) {type = "ws"; return null;}
if (stream.match(numLiteral)) return "number";
var ch = stream.next();
if (ch == "\\") ch = stream.next();
if (ch == '"') return (state.tokenize = inString)(stream, state);
else if (ch == "(") { type = "open"; return "bracket";
}
else if (ch == ")" || ch == "]") { type = "close"; return "bracket"; }
else if (ch == ";") { stream.skipToEnd(); type = "ws"; return "comment"; }
else if (/['`,@]/.test(ch)) return "quote-char";
else if (ch == "|") {
if (stream.skipTo("|")) { stream.next(); return "symbol"; }
else { stream.skipToEnd(); return "error"; }
} else if (ch == "#") {
var ch = stream.next();
if (ch == "[") { type = "open"; return "bracket"; }
else if (/[+\-=\.']/.test(ch)) return null;
else if (/\d/.test(ch) && stream.match(/^\d*#/)) return null;
else if (ch == "|") return (state.tokenize = inComment)(stream, state);
else if (ch == ":") { readSym(stream); return "meta"; }
else return "error";
} else {
var name = readSym(stream);
if (name == ".") return null;
type = "symbol"
if (!state.ctx.first) state.ctx.first = name;
// highlighting the names of defined terms (the first symbol after a definition form)
if (/^def/.test(name)) {
if (state.ctx.prev && name != "defvar" && name != "defparameter" && name != "defconstant")
state.ctx.prev.looking_for_args_p = true;
return "def";
}
/////////////////////////////////////////////////////////////////////////////////////
if (/^(error|warn)/.test(name)) return "error-related";
if (builtin.test(name)) return "builtin";
if (name == "nil" || name == "t") return "atom";
if (name.charAt(0) == "*" && name.charAt(name.length-1) == "*") return "special-variable";
if (name.charAt(0) == ":") return "keyword";
if (name.charAt(0) == "&") return "variable-2";
return "variable";
}
}
function inLocalBody(stream, state) {
return (state.ctx.prev && state.ctx.prev.prev && state.ctx.prev.prev.prev && state.ctx.prev.prev.prev.local_body_form_p)
}
function inString(stream, state) {
var escaped = false, next;
while (next = stream.next()) {
if (next == '"' && !escaped) { state.tokenize = base; break; }
escaped = !escaped && next == "\\";
}
return "string";
}
function inComment(stream, state) {
var next, last;
while (next = stream.next()) {
if (next == "#" && last == "|") { state.tokenize = base; break; }
last = next;
}
type = "ws";
return "comment";
}
return {
startState: function () {
return {ctx: {prev: null, start: 0, indentTo: 0}, tokenize: base};
},
token: function (stream, state) {
if (stream.sol() && typeof state.ctx.indentTo != "number")
state.ctx.indentTo = state.ctx.start + 1;
type = null;
var style = state.tokenize(stream, state);
if (type != "ws") {
if (state.ctx.indentTo == null) {
var sym_p = (type == "symbol");
var cur = stream.current();
// Special case for flet/labels (whose properties should be indented as though body args)
if (cur == "flet" | cur == "labels") {
state.ctx.prev.local_body_form_p = true;
}
/////////////////////////////////////////////////////////////////////////////////////////
if (sym_p && assumeBody.test(cur) | inLocalBody(stream, state))
state.ctx.indentTo = state.ctx.start + config.indentUnit;
else
state.ctx.indentTo = "next";
} else if (state.ctx.indentTo == "next") {
state.ctx.indentTo = stream.column();
}
}
if (type == "open") {
state.ctx = { prev: state.ctx, start: stream.column(), indentTo: null, opening: "(" }
// explicitly labelling arglists for arg-hinting purposes
if (state.ctx.prev.prev && state.ctx.prev.prev.looking_for_args_p) {
state.ctx.prev.prev.looking_for_args_p = false;
state.ctx.node_type = "arglist";
}
//////////////////////////////////////////////////////////////////////////////////////////////
} else if (type == "close") { state.ctx = state.ctx.prev || state.ctx; }
return style;
},
indent: function (state, _textAfter) {
var i = state.ctx.indentTo;
return typeof i == "number" ? i : state.ctx.start + 1;
},
lineComment: ";;",
blockCommentStart: "#|",
blockCommentEnd: "|#"
};
});
CodeMirror.defineMIME("text/x-common-lisp", "commonlisp");
| 5,080 | Common Lisp | .lisp | 124 | 36.403226 | 142 | 0.549199 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 71bd17afa14ba6b11e62def579c03530fa74170e4e35cfe999cf6bdea739b91e | 2,569 | [
-1
] |
2,570 | cl-notebook.asd | inaimathi_cl-notebook/cl-notebook.asd | ;;;; cl-notebook.asd
(asdf:defsystem #:cl-notebook
:description "A notebook-style in-browser editor for Common Lisp"
:author "Inaimathi <[email protected]>"
:license "AGPL3"
:serial t
:depends-on (#+sbcl #:sb-introspect #:qlot #:quri
#:alexandria #:anaphora #:cl-fad #:closer-mop
#:cl-who #:cl-css #:parenscript
#:house #:fact-base)
:components ((:module
src :components
((:file "package")
(:file "model")
(:file "util")
(:file "publish-update")
(:module
ui :components
((:module
http-api :components
((:file "system")
(:file "notebook")
(:file "cell")))
(:module
http-front-end :components
((:file "macros")
(:file "css")
(:file "core")
(:file "base") (:file "templates") (:file "api")
(:file "notebook-selector")
(:file "pareditesque")))))
(:file "evaluators")
(:file "exporters")
(:file "main")))))
(asdf:defsystem #:cl-notebook/test
:description "Test suite for :cl-notebook"
:author "Inaimathi <[email protected]>"
:license "AGPL3"
:serial t
:depends-on (#:cl-notebook #:test-utils)
:defsystem-depends-on (#:prove-asdf)
:components ((:module
test :components
((:file "package")
(:test-file "cl-notebook"))))
:perform (test-op
:after (op c)
(funcall (intern #.(string :run) :prove) c)))
| 1,703 | Common Lisp | .asd | 48 | 23.895833 | 69 | 0.489994 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 8a812e74f235d1b214d193f38bc6be262d0a87f1096bbd4068b6002fa4803cb6 | 2,570 | [
-1
] |
2,572 | qlfile.lock | inaimathi_cl-notebook/qlfile.lock | ("quicklisp" .
(:class qlot.source.ql:source-ql-all
:initargs (:project-name "quicklisp" :%version :latest)
:version "2018-02-28"))
("house" .
(:class qlot.source.github:source-github
:initargs (:project-name "house" :repos "inaimathi/house" :ref nil :branch nil :tag nil)
:version "github-fb47533304b4580b24d7c95eef93397fd647856e"
:repos "inaimathi/house"
:url "https://github.com/inaimathi/house/archive/fb47533304b4580b24d7c95eef93397fd647856e.tar.gz"
:ref "fb47533304b4580b24d7c95eef93397fd647856e"))
("fact-base" .
(:class qlot.source.github:source-github
:initargs (:project-name "fact-base" :repos "inaimathi/fact-base" :ref nil :branch nil :tag nil)
:version "github-fb7e2996b61ee1974084a3c4d84569cc2b91e5ca"
:repos "inaimathi/fact-base"
:url "https://github.com/inaimathi/fact-base/archive/fb7e2996b61ee1974084a3c4d84569cc2b91e5ca.tar.gz"
:ref "fb7e2996b61ee1974084a3c4d84569cc2b91e5ca"))
("defmain" .
(:class qlot.source.github:source-github
:initargs (:project-name "defmain" :repos "40ants/defmain" :ref nil :branch nil :tag nil)
:version "github-38efd1723c921984ec30000f859a894a8cda73ee"
:repos "40ants/defmain"
:url "https://github.com/40ants/defmain/archive/38efd1723c921984ec30000f859a894a8cda73ee.tar.gz"
:ref "38efd1723c921984ec30000f859a894a8cda73ee"))
| 1,310 | Common Lisp | .l | 25 | 49.88 | 103 | 0.785214 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 570934e0fa13f0712a06d7aaad8c2ea1c90aa2cbda32cb3ebdf04663195ae585 | 2,572 | [
-1
] |
2,573 | qlfile | inaimathi_cl-notebook/qlfile | ql :all :latest
github house inaimathi/house
github fact-base inaimathi/fact-base
github defmain 40ants/defmain
| 113 | Common Lisp | .l | 4 | 27 | 36 | 0.861111 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3e3fdf1bcc0746d89100d12e5f9f967187007f2becec3b7f3b4528faddee2940 | 2,573 | [
-1
] |
2,575 | .travis.yml | inaimathi_cl-notebook/.travis.yml | language: common-lisp
sudo: required
install:
- curl -L https://raw.githubusercontent.com/snmsts/roswell/release/scripts/install-for-ci.sh | sh
script:
- ros -s prove -e '(progn (ql:quickload (list :cl-notebook :cl-notebook/test)) (or (prove:run :cl-notebook/test) (uiop:quit -1)))'
| 289 | Common Lisp | .l | 6 | 46.166667 | 132 | 0.733096 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3df626a405b314733aa2403fbfa260e2daf352fc9fb46ceb45fb76b68ff51d84 | 2,575 | [
-1
] |
2,576 | build.sh | inaimathi_cl-notebook/build/build.sh | sbcl --load "build.lisp" --quit
./buildapp --manifest-file build.manifest --load-system cl-css --load-system cl-who --load-system named-readtables --load-system trivial-gray-streams --load-system closer-mop --load-system sb-bsd-sockets --load-system sb-posix --load-system cl-json --load-system cl-ppcre --load-system cl-base64 --load-system anaphora --load-system alexandria --load-system parenscript --load-system flexi-streams --load-system optima --load-system usocket --load-system bordeaux-threads --load-system cl-fad --load-system local-time --load-system session-token --load-system house --load-system fact-base --load-system cl-notebook --eval '(cl-notebook::read-statics)' --output cl-notebook --entry cl-notebook:main
sha512sum cl-notebook > cl-notebook.sha512
sha256sum cl-notebook > cl-notebook.sha256
tar -zcvf cl-notebook.tar.gz cl-notebook
| 860 | Common Lisp | .l | 5 | 170.6 | 698 | 0.76905 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b14a50c77a1f0376602933c8a5c095b713d2c5d8b5ffb8b89fbd4dc99a3dd508 | 2,576 | [
-1
] |
2,596 | cl-notebook.ros | inaimathi_cl-notebook/roswell/cl-notebook.ros | #!/bin/sh
#|-*- mode:lisp -*-|#
#|
exec ros -Q -- $0 "$@"
|#
(progn ;;init forms
(ros:ensure-asdf)
(ql:quickload '(cl-notebook defmain) :silent t))
(defpackage :ros.script.cl-notebook
(:use :cl)
(:import-from #:defmain
#:defmain))
(in-package :ros.script.cl-notebook)
;; Include all the associated static files along with the binary.
(cl-notebook::read-statics)
(defmain main ((port "TCP port to bind the server"
:default 4242))
(cl-notebook:main nil :port port))
| 514 | Common Lisp | .l | 18 | 24.777778 | 65 | 0.643585 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 1d263cc134e2e08c296ba94a9aec2fbfd5aade1f1516d14257815778a5049c3a | 2,596 | [
-1
] |
2,597 | FileSaver.js | inaimathi_cl-notebook/static/js/FileSaver.js | /* FileSaver.js
* A saveAs() FileSaver implementation.
* 2013-01-23
*
* By Eli Grey, http://eligrey.com
* License: X11/MIT
* See LICENSE.md
*/
/*global self */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
var saveAs = saveAs
|| (navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))
|| (function(view) {
"use strict";
var
doc = view.document
// only get URL when necessary in case BlobBuilder.js hasn't overridden it yet
, get_URL = function() {
return view.URL || view.webkitURL || view;
}
, URL = view.URL || view.webkitURL || view
, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
, can_use_save_link = !view.externalHost && "download" in save_link
, click = function(node) {
var event = doc.createEvent("MouseEvents");
event.initMouseEvent(
"click", true, false, view, 0, 0, 0, 0, 0
, false, false, false, false, 0, null
);
node.dispatchEvent(event);
}
, webkit_req_fs = view.webkitRequestFileSystem
, req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem
, throw_outside = function (ex) {
(view.setImmediate || view.setTimeout)(function() {
throw ex;
}, 0);
}
, force_saveable_type = "application/octet-stream"
, fs_min_size = 0
, deletion_queue = []
, process_deletion_queue = function() {
var i = deletion_queue.length;
while (i--) {
var file = deletion_queue[i];
if (typeof file === "string") { // file is an object URL
URL.revokeObjectURL(file);
} else { // file is a File
file.remove();
}
}
deletion_queue.length = 0; // clear queue
}
, dispatch = function(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
}
, FileSaver = function(blob, name) {
// First try a.download, then web filesystem, then object URLs
var
filesaver = this
, type = blob.type
, blob_changed = false
, object_url
, target_view
, get_object_url = function() {
var object_url = get_URL().createObjectURL(blob);
deletion_queue.push(object_url);
return object_url;
}
, dispatch_all = function() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
}
// on any filesys errors revert to saving with object URLs
, fs_error = function() {
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_object_url(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
window.open(object_url, "_blank");
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
}
, abortable = function(func) {
return function() {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
}
, create_if_not_found = {create: true, exclusive: false}
, slice
;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_object_url(blob);
save_link.href = object_url;
save_link.download = name;
click(save_link);
filesaver.readyState = filesaver.DONE;
dispatch_all();
return;
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) {
var save = function() {
dir.getFile(name, create_if_not_found, abortable(function(file) {
file.createWriter(abortable(function(writer) {
writer.onwriteend = function(event) {
target_view.location.href = file.toURL();
deletion_queue.push(file);
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
};
writer.onerror = function() {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function(event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function() {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, {create: false}, abortable(function(file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function(ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
}
, FS_proto = FileSaver.prototype
, saveAs = function(blob, name) {
return new FileSaver(blob, name);
}
;
FS_proto.abort = function() {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error =
FS_proto.onwritestart =
FS_proto.onprogress =
FS_proto.onwrite =
FS_proto.onabort =
FS_proto.onerror =
FS_proto.onwriteend =
null;
view.addEventListener("unload", process_deletion_queue, false);
return saveAs;
}(self));
if (typeof module !== 'undefined') module.exports = saveAs;
| 6,613 | Common Lisp | .l | 212 | 26.169811 | 90 | 0.628303 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 417c2414f393cc3d84cc5e1d8dad40d2f550b5f5a22c9e4775ddf29aa3b30ad1 | 2,597 | [
-1
] |
2,598 | Blob.js | inaimathi_cl-notebook/static/js/Blob.js | /* Blob.js
* A Blob implementation.
* 2013-06-20
*
* By Eli Grey, http://eligrey.com
* By Devin Samarin, https://github.com/eboyjr
* License: X11/MIT
* See LICENSE.md
*/
/*global self, unescape */
/*jslint bitwise: true, regexp: true, confusion: true, es5: true, vars: true, white: true,
plusplus: true */
/*! @source http://purl.eligrey.com/github/Blob.js/blob/master/Blob.js */
if (!(typeof Blob === "function" || typeof Blob === "object") || typeof URL === "undefined")
if ((typeof Blob === "function" || typeof Blob === "object") && typeof webkitURL !== "undefined") self.URL = webkitURL;
else var Blob = (function (view) {
"use strict";
var BlobBuilder = view.BlobBuilder || view.WebKitBlobBuilder || view.MozBlobBuilder || view.MSBlobBuilder || (function(view) {
var
get_class = function(object) {
return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];
}
, FakeBlobBuilder = function BlobBuilder() {
this.data = [];
}
, FakeBlob = function Blob(data, type, encoding) {
this.data = data;
this.size = data.length;
this.type = type;
this.encoding = encoding;
}
, FBB_proto = FakeBlobBuilder.prototype
, FB_proto = FakeBlob.prototype
, FileReaderSync = view.FileReaderSync
, FileException = function(type) {
this.code = this[this.name = type];
}
, file_ex_codes = (
"NOT_FOUND_ERR SECURITY_ERR ABORT_ERR NOT_READABLE_ERR ENCODING_ERR "
+ "NO_MODIFICATION_ALLOWED_ERR INVALID_STATE_ERR SYNTAX_ERR"
).split(" ")
, file_ex_code = file_ex_codes.length
, real_URL = view.URL || view.webkitURL || view
, real_create_object_URL = real_URL.createObjectURL
, real_revoke_object_URL = real_URL.revokeObjectURL
, URL = real_URL
, btoa = view.btoa
, atob = view.atob
, ArrayBuffer = view.ArrayBuffer
, Uint8Array = view.Uint8Array
;
FakeBlob.fake = FB_proto.fake = true;
while (file_ex_code--) {
FileException.prototype[file_ex_codes[file_ex_code]] = file_ex_code + 1;
}
if (!real_URL.createObjectURL) {
URL = view.URL = {};
}
URL.createObjectURL = function(blob) {
var
type = blob.type
, data_URI_header
;
if (type === null) {
type = "application/octet-stream";
}
if (blob instanceof FakeBlob) {
data_URI_header = "data:" + type;
if (blob.encoding === "base64") {
return data_URI_header + ";base64," + blob.data;
} else if (blob.encoding === "URI") {
return data_URI_header + "," + decodeURIComponent(blob.data);
} if (btoa) {
return data_URI_header + ";base64," + btoa(blob.data);
} else {
return data_URI_header + "," + encodeURIComponent(blob.data);
}
} else if (real_create_object_URL) {
return real_create_object_URL.call(real_URL, blob);
}
};
URL.revokeObjectURL = function(object_URL) {
if (object_URL.substring(0, 5) !== "data:" && real_revoke_object_URL) {
real_revoke_object_URL.call(real_URL, object_URL);
}
};
FBB_proto.append = function(data/*, endings*/) {
var bb = this.data;
// decode data to a binary string
if (Uint8Array && (data instanceof ArrayBuffer || data instanceof Uint8Array)) {
var
str = ""
, buf = new Uint8Array(data)
, i = 0
, buf_len = buf.length
;
for (; i < buf_len; i++) {
str += String.fromCharCode(buf[i]);
}
bb.push(str);
} else if (get_class(data) === "Blob" || get_class(data) === "File") {
if (FileReaderSync) {
var fr = new FileReaderSync;
bb.push(fr.readAsBinaryString(data));
} else {
// async FileReader won't work as BlobBuilder is sync
throw new FileException("NOT_READABLE_ERR");
}
} else if (data instanceof FakeBlob) {
if (data.encoding === "base64" && atob) {
bb.push(atob(data.data));
} else if (data.encoding === "URI") {
bb.push(decodeURIComponent(data.data));
} else if (data.encoding === "raw") {
bb.push(data.data);
}
} else {
if (typeof data !== "string") {
data += ""; // convert unsupported types to strings
}
// decode UTF-16 to binary string
bb.push(unescape(encodeURIComponent(data)));
}
};
FBB_proto.getBlob = function(type) {
if (!arguments.length) {
type = null;
}
return new FakeBlob(this.data.join(""), type, "raw");
};
FBB_proto.toString = function() {
return "[object BlobBuilder]";
};
FB_proto.slice = function(start, end, type) {
var args = arguments.length;
if (args < 3) {
type = null;
}
return new FakeBlob(
this.data.slice(start, args > 1 ? end : this.data.length)
, type
, this.encoding
);
};
FB_proto.toString = function() {
return "[object Blob]";
};
return FakeBlobBuilder;
}(view));
return function Blob(blobParts, options) {
var type = options ? (options.type || "") : "";
var builder = new BlobBuilder();
if (blobParts) {
for (var i = 0, len = blobParts.length; i < len; i++) {
builder.append(blobParts[i]);
}
}
return builder.getBlob(type);
};
}(self));
| 5,052 | Common Lisp | .l | 160 | 27.4625 | 127 | 0.631169 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | dbbabfcf8032dcc78701bcd69d7d411105e12a4a5e93801fe0fb7aa4eaa0d556 | 2,598 | [
-1
] |
2,599 | native-sortable.js | inaimathi_cl-notebook/static/js/native-sortable.js | /**
* nativesortable - v0.0.1
*
* Originally based on code found here:
* http://www.html5rocks.com/en/tutorials/dnd/basics/#toc-examples
*
* @example
* var list = document.getElementByID("list");
* nativesortable(list, { change: onchange });
*
* @author Brian Grinstead
* @license MIT License
*/
(function(definition) {
if(typeof exports === 'object') {
module.exports = definition();
} else if(typeof define === 'function' && define.amd) {
define([], definition);
} else {
window.nativesortable = definition();
}
})(function() {
var supportsTouch = ('ontouchstart' in window) || (window.DocumentTouch && document instanceof DocumentTouch);
var supportsDragAndDrop = !supportsTouch && (function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
})();
var CHILD_CLASS = "sortable-child";
var DRAGGING_CLASS = "sortable-dragging";
var OVER_CLASS = "sortable-over";
function hasClassName(el, name) {
return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)").test(el.className);
}
function addClassName (el, name) {
if (!hasClassName(el, name)) {
el.className = el.className ? [el.className, name].join(' ') : name;
}
}
function removeClassName(el, name) {
if (hasClassName(el, name)) {
var c = el.className;
el.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), " ").replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
}
function moveElementNextTo(element, elementToMoveNextTo) {
if (isBelow(element, elementToMoveNextTo)) {
// Insert element before to elementToMoveNextTo.
elementToMoveNextTo.parentNode.insertBefore(element, elementToMoveNextTo);
}
else {
// Insert element after to elementToMoveNextTo.
elementToMoveNextTo.parentNode.insertBefore(element, elementToMoveNextTo.nextSibling);
}
}
function isBelow(el1, el2) {
var parent = el1.parentNode;
if (el2.parentNode != parent) {
return false;
}
var cur = el1.previousSibling;
while (cur && cur.nodeType !== 9) {
if (cur === el2) {
return true;
}
cur = cur.previousSibling;
}
return false;
}
function moveUpToChildNode(parent, child) {
var cur = child;
if (cur == parent) { return null; }
while (cur) {
if (cur.parentNode === parent) {
return cur;
}
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur.nodeType === 11 ) {
break;
}
}
return null;
}
function prevent(e) {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
e.returnValue = false;
}
function dragenterData(element, val) {
if (arguments.length == 1) {
return parseInt(element.getAttribute("data-child-dragenter"), 10) || 0;
}
else if (!val) {
element.removeAttribute("data-child-dragenter");
}
else {
element.setAttribute("data-child-dragenter", Math.max(0, val));
}
}
return function(element, opts) {
if (!opts) {
opts = { };
}
var warp = !!opts.warp;
var stop = opts.stop || function() { };
var start = opts.start || function() { };
var change = opts.change || function() { };
var currentlyDraggingElement = null;
var currentlyDraggingTarget = null;
var handleDragStart = delegate(function(e) {
if (supportsTouch) {
prevent(e);
}
if (e.dataTransfer) {
e.dataTransfer.effectAllowed = 'moving';
e.dataTransfer.setData('Text', ""); // Need to set to something or else drag doesn't start
}
currentlyDraggingElement = this;
addClassName(currentlyDraggingElement, DRAGGING_CLASS);
[].forEach.call(element.childNodes, function(el) {
if (el.nodeType === 1) {
addClassName(el, CHILD_CLASS);
}
});
addFakeDragHandlers();
});
var handleDragOver = delegate(function(e) {
if (!currentlyDraggingElement) {
return true;
}
if (e.preventDefault) {
e.preventDefault();
}
return false;
});
var handleDragEnter = delegate(function(e) {
if (!currentlyDraggingElement || currentlyDraggingElement === this) {
return true;
}
// Prevent dragenter on a child from allowing a dragleave on the container
var previousCounter = dragenterData(this);
dragenterData(this, previousCounter + 1);
if (previousCounter === 0) {
addClassName(this, OVER_CLASS);
if (!warp) {
moveElementNextTo(currentlyDraggingElement, this);
}
}
return false;
});
var handleDragLeave = delegate(function(e) {
// Prevent dragenter on a child from allowing a dragleave on the container
var previousCounter = dragenterData(this);
dragenterData(this, previousCounter - 1);
// This is a fix for child elements firing dragenter before the parent fires dragleave
if (!dragenterData(this)) {
removeClassName(this, OVER_CLASS);
dragenterData(this, false);
}
});
var handleDrop = delegate(function(e) {
if (e.type === 'drop') {
if (e.stopPropagation) {
e.stopPropagation();
}
if (e.preventDefault) {
e.preventDefault();
}
}
if (this === currentlyDraggingElement) {
return;
}
if (warp) {
var thisSibling = currentlyDraggingElement.nextSibling;
this.parentNode.insertBefore(currentlyDraggingElement, this);
this.parentNode.insertBefore(this, thisSibling);
}
change(this, currentlyDraggingElement);
});
var handleDragEnd = function(e) {
currentlyDraggingElement = null;
currentlyDraggingTarget = null;
[].forEach.call(element.childNodes, function(el) {
if (el.nodeType === 1) {
removeClassName(el, OVER_CLASS);
removeClassName(el, DRAGGING_CLASS);
removeClassName(el, CHILD_CLASS);
dragenterData(el, false);
}
});
removeFakeDragHandlers();
};
var handleTouchMove = delegate(function(e) {
if (!currentlyDraggingElement ||
currentlyDraggingElement === this ||
currentlyDraggingTarget === this) {
return true;
}
[].forEach.call(element.childNodes, function(el) {
removeClassName(el, OVER_CLASS);
});
currentlyDraggingTarget = this;
if (!warp) {
moveElementNextTo(currentlyDraggingElement, this);
}
else {
addClassName(this, OVER_CLASS);
}
return prevent(e);
});
function delegate(fn) {
return function(e) {
var touch = (supportsTouch && e.touches && e.touches[0]) || { };
var target = touch.target || e.target;
// Fix event.target for a touch event
if (supportsTouch && document.elementFromPoint) {
target = document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - document.body.scrollTop);
}
if (hasClassName(target, CHILD_CLASS)) {
fn.apply(target, [e]);
}
else if (target !== element) {
// If a child is initiating the event or ending it, then use the container as context for the callback.
var context = moveUpToChildNode(element, target);
if (context) {
fn.apply(context, [e]);
}
}
};
}
// Opera and mobile devices do not support drag and drop. http://caniuse.com/dragndrop
// Bind/unbind standard mouse/touch events as a polyfill.
function addFakeDragHandlers() {
if (!supportsDragAndDrop) {
if (supportsTouch) {
element.addEventListener("touchmove", handleTouchMove, false);
}
else {
element.addEventListener('mouseover', handleDragEnter, false);
element.addEventListener('mouseout', handleDragLeave, false);
}
element.addEventListener(supportsTouch ? 'touchend' : 'mouseup', handleDrop, false);
document.addEventListener(supportsTouch ? 'touchend' : 'mouseup', handleDragEnd, false);
document.addEventListener("selectstart", prevent, false);
}
}
function removeFakeDragHandlers() {
if (!supportsDragAndDrop) {
if (supportsTouch) {
element.removeEventListener("touchmove", handleTouchMove, false);
}
else {
element.removeEventListener('mouseover', handleDragEnter, false);
element.removeEventListener('mouseout', handleDragLeave, false);
}
element.removeEventListener(supportsTouch ? 'touchend' : 'mouseup', handleDrop, false);
document.removeEventListener(supportsTouch ? 'touchend' : 'mouseup', handleDragEnd, false);
document.removeEventListener("selectstart", prevent, false);
}
}
if (supportsDragAndDrop) {
element.addEventListener('dragstart', handleDragStart, false);
element.addEventListener('dragenter', handleDragEnter, false);
element.addEventListener('dragleave', handleDragLeave, false);
element.addEventListener('drop', handleDrop, false);
element.addEventListener('dragover', handleDragOver, false);
element.addEventListener('dragend', handleDragEnd, false);
}
else {
if (supportsTouch) {
element.addEventListener('touchstart', handleDragStart, false);
}
else {
element.addEventListener('mousedown', handleDragStart, false);
}
}
[].forEach.call(element.childNodes, function(el) {
if (el.nodeType === 1) {
el.setAttribute("draggable", "true");
}
});
};
});
| 11,377 | Common Lisp | .l | 286 | 27.587413 | 139 | 0.54116 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 5804ef50328cbb8e72440177980012eabbcce3b832508291d617f82061c7a96a | 2,599 | [
-1
] |
2,601 | rulers.js | inaimathi_cl-notebook/static/js/addons/rulers.js | (function() {
"use strict";
CodeMirror.defineOption("rulers", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearRulers(cm);
cm.off("refresh", refreshRulers);
}
if (val && val.length) {
setRulers(cm);
cm.on("refresh", refreshRulers);
}
});
function clearRulers(cm) {
for (var i = cm.display.lineSpace.childNodes.length - 1; i >= 0; i--) {
var node = cm.display.lineSpace.childNodes[i];
if (/(^|\s)CodeMirror-ruler($|\s)/.test(node.className))
node.parentNode.removeChild(node);
}
}
function setRulers(cm) {
var val = cm.getOption("rulers");
var cw = cm.defaultCharWidth();
var left = cm.charCoords(CodeMirror.Pos(cm.firstLine(), 0), "div").left;
var bot = -cm.display.scroller.offsetHeight;
for (var i = 0; i < val.length; i++) {
var elt = document.createElement("div");
var col, cls = null;
if (typeof val[i] == "number") {
col = val[i];
} else {
col = val[i].column;
cls = val[i].className;
}
elt.className = "CodeMirror-ruler" + (cls ? " " + cls : "");
elt.style.cssText = "left: " + (left + col * cw) + "px; top: -50px; bottom: " + bot + "px";
cm.display.lineSpace.insertBefore(elt, cm.display.cursorDiv);
}
}
function refreshRulers(cm) {
clearRulers(cm);
setRulers(cm);
}
})();
| 1,400 | Common Lisp | .l | 43 | 27.046512 | 97 | 0.585366 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | b40b0844f7e8ce34ba37afb6da15f2b2e0e966b144bfc630a461aab2b58db818 | 2,601 | [
-1
] |
2,602 | match-highlighter.js | inaimathi_cl-notebook/static/js/addons/match-highlighter.js | // Highlighting text that matches the selection
//
// Defines an option highlightSelectionMatches, which, when enabled,
// will style strings that match the selection throughout the
// document.
//
// The option can be set to true to simply enable it, or to a
// {minChars, style, showToken} object to explicitly configure it.
// minChars is the minimum amount of characters that should be
// selected for the behavior to occur, and style is the token style to
// apply to the matches. This will be prefixed by "cm-" to create an
// actual CSS class name. showToken, when enabled, will cause the
// current token to be highlighted when nothing is selected.
(function() {
var DEFAULT_MIN_CHARS = 2;
var DEFAULT_TOKEN_STYLE = "matchhighlight";
var DEFAULT_DELAY = 100;
function State(options) {
if (typeof options == "object") {
this.minChars = options.minChars;
this.style = options.style;
this.showToken = options.showToken;
this.delay = options.delay;
}
if (this.style == null) this.style = DEFAULT_TOKEN_STYLE;
if (this.minChars == null) this.minChars = DEFAULT_MIN_CHARS;
if (this.delay == null) this.delay = DEFAULT_DELAY;
this.overlay = this.timeout = null;
}
CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
var over = cm.state.matchHighlighter.overlay;
if (over) cm.removeOverlay(over);
clearTimeout(cm.state.matchHighlighter.timeout);
cm.state.matchHighlighter = null;
cm.off("cursorActivity", cursorActivity);
}
if (val) {
cm.state.matchHighlighter = new State(val);
highlightMatches(cm);
cm.on("cursorActivity", cursorActivity);
}
});
function cursorActivity(cm) {
var state = cm.state.matchHighlighter;
clearTimeout(state.timeout);
state.timeout = setTimeout(function() {highlightMatches(cm);}, state.delay);
}
function highlightMatches(cm) {
cm.operation(function() {
var state = cm.state.matchHighlighter;
if (state.overlay) {
cm.removeOverlay(state.overlay);
state.overlay = null;
}
if (!cm.somethingSelected() && state.showToken) {
var re = state.showToken === true ? /[\w$]/ : state.showToken;
var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
while (start && re.test(line.charAt(start - 1))) --start;
while (end < line.length && re.test(line.charAt(end))) ++end;
if (start < end)
cm.addOverlay(state.overlay = makeOverlay(line.slice(start, end), re, state.style));
return;
}
if (cm.getCursor("head").line != cm.getCursor("anchor").line) return;
var selection = cm.getSelection().replace(/^\s+|\s+$/g, "");
if (selection.length >= state.minChars)
cm.addOverlay(state.overlay = makeOverlay(selection, false, state.style));
});
}
function boundariesAround(stream, re) {
return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
(stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
}
function makeOverlay(query, hasBoundary, style) {
return {token: function(stream) {
if (stream.match(query) &&
(!hasBoundary || boundariesAround(stream, hasBoundary)))
return style;
stream.next();
stream.skipTo(query.charAt(0)) || stream.skipToEnd();
}};
}
})();
| 3,471 | Common Lisp | .l | 84 | 36.119048 | 94 | 0.671006 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | dd83e307ba7bd4857d23487c087713f53f8cb453e675a70e2e29f628a9e779e0 | 2,602 | [
-1
] |
2,603 | active-line.js | inaimathi_cl-notebook/static/js/addons/active-line.js | // Because sometimes you need to style the cursor's line.
//
// Adds an option 'styleActiveLine' which, when enabled, gives the
// active line's wrapping <div> the CSS class "CodeMirror-activeline",
// and gives its background <div> the class "CodeMirror-activeline-background".
(function() {
"use strict";
var WRAP_CLASS = "CodeMirror-activeline";
var BACK_CLASS = "CodeMirror-activeline-background";
CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
updateActiveLine(cm, cm.getCursor().line);
cm.on("beforeSelectionChange", selectionChange);
} else if (!val && prev) {
cm.off("beforeSelectionChange", selectionChange);
clearActiveLine(cm);
delete cm.state.activeLine;
}
});
function clearActiveLine(cm) {
if ("activeLine" in cm.state) {
cm.removeLineClass(cm.state.activeLine, "wrap", WRAP_CLASS);
cm.removeLineClass(cm.state.activeLine, "background", BACK_CLASS);
}
}
function updateActiveLine(cm, selectedLine) {
var line = cm.getLineHandleVisualStart(selectedLine);
if (cm.state.activeLine == line) return;
cm.operation(function() {
clearActiveLine(cm);
cm.addLineClass(line, "wrap", WRAP_CLASS);
cm.addLineClass(line, "background", BACK_CLASS);
cm.state.activeLine = line;
});
}
function selectionChange(cm, sel) {
updateActiveLine(cm, sel.head.line);
}
})();
| 1,490 | Common Lisp | .l | 40 | 32.825 | 79 | 0.693426 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 53559dbe015c82b9a793a0eeb1e3f6386a00e9dbb14769c3413e3f87027d50e8 | 2,603 | [
-1
] |
2,604 | closebrackets.js | inaimathi_cl-notebook/static/js/addons/closebrackets.js | (function() {
var DEFAULT_BRACKETS = "()[]{}\"\"";
var DEFAULT_EXPLODE_ON_ENTER = "[]{}";
var SPACE_CHAR_REGEX = /\s/;
CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
if (old != CodeMirror.Init && old)
cm.removeKeyMap("autoCloseBrackets");
if (!val) return;
var pairs = DEFAULT_BRACKETS, explode = DEFAULT_EXPLODE_ON_ENTER;
if (typeof val == "string") pairs = val;
else if (typeof val == "object") {
if (val.pairs != null) pairs = val.pairs;
if (val.explode != null) explode = val.explode;
}
var map = buildKeymap(pairs);
if (explode) map.Enter = buildExplodeHandler(explode);
cm.addKeyMap(map);
});
function charsAround(cm, pos) {
var str = cm.getRange(CodeMirror.Pos(pos.line, pos.ch - 1),
CodeMirror.Pos(pos.line, pos.ch + 1));
return str.length == 2 ? str : null;
}
function buildKeymap(pairs) {
var map = {
name : "autoCloseBrackets",
Backspace: function(cm) {
if (cm.somethingSelected() || cm.getOption("disableInput")) return CodeMirror.Pass;
var cur = cm.getCursor(), around = charsAround(cm, cur);
if (around && pairs.indexOf(around) % 2 == 0)
cm.replaceRange("", CodeMirror.Pos(cur.line, cur.ch - 1), CodeMirror.Pos(cur.line, cur.ch + 1));
else
return CodeMirror.Pass;
}
};
var closingBrackets = "";
for (var i = 0; i < pairs.length; i += 2) (function(left, right) {
if (left != right) closingBrackets += right;
function surround(cm) {
var selection = cm.getSelection();
cm.replaceSelection(left + selection + right);
}
function maybeOverwrite(cm) {
var cur = cm.getCursor(), ahead = cm.getRange(cur, CodeMirror.Pos(cur.line, cur.ch + 1));
if (ahead != right || cm.somethingSelected()) return CodeMirror.Pass;
else cm.execCommand("goCharRight");
}
map["'" + left + "'"] = function(cm) {
if (left == "'" && cm.getTokenAt(cm.getCursor()).type == "comment" ||
cm.getOption("disableInput"))
return CodeMirror.Pass;
if (cm.somethingSelected()) return surround(cm);
if (left == right && maybeOverwrite(cm) != CodeMirror.Pass) return;
var cur = cm.getCursor(), ahead = CodeMirror.Pos(cur.line, cur.ch + 1);
var line = cm.getLine(cur.line), nextChar = line.charAt(cur.ch), curChar = cur.ch > 0 ? line.charAt(cur.ch - 1) : "";
if (left == right && CodeMirror.isWordChar(curChar))
return CodeMirror.Pass;
if (line.length == cur.ch || closingBrackets.indexOf(nextChar) >= 0 || SPACE_CHAR_REGEX.test(nextChar))
cm.replaceSelection(left + right, {head: ahead, anchor: ahead});
else
return CodeMirror.Pass;
};
if (left != right) map["'" + right + "'"] = maybeOverwrite;
})(pairs.charAt(i), pairs.charAt(i + 1));
return map;
}
function buildExplodeHandler(pairs) {
return function(cm) {
var cur = cm.getCursor(), around = charsAround(cm, cur);
if (!around || pairs.indexOf(around) % 2 != 0 || cm.getOption("disableInput"))
return CodeMirror.Pass;
cm.operation(function() {
var newPos = CodeMirror.Pos(cur.line + 1, 0);
cm.replaceSelection("\n\n", {anchor: newPos, head: newPos}, "+input");
cm.indentLine(cur.line + 1, null, true);
cm.indentLine(cur.line + 2, null, true);
});
};
}
})();
| 3,495 | Common Lisp | .l | 80 | 36.6375 | 125 | 0.602169 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | a245f373e02aef604609584ca84b6b1ab1b0da2b93d6aea675308af7a0c8ceca | 2,604 | [
-1
] |
2,605 | trailingspace.js | inaimathi_cl-notebook/static/js/addons/trailingspace.js | CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
if (prev == CodeMirror.Init) prev = false;
if (prev && !val)
cm.removeOverlay("trailingspace");
else if (!prev && val)
cm.addOverlay({
token: function(stream) {
for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
if (i > stream.pos) { stream.pos = i; return null; }
stream.pos = l;
return "trailingspace";
},
name: "trailingspace"
});
});
| 528 | Common Lisp | .l | 15 | 29.666667 | 102 | 0.590643 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3923a5955ec8c22e0a5a2e428678d024dfcd69effe2ec03c4ac107e3bb57b2e1 | 2,605 | [
-1
] |
2,606 | fullscreen.js | inaimathi_cl-notebook/static/js/addons/fullscreen.js | (function() {
"use strict";
CodeMirror.defineOption("fullScreen", false, function(cm, val, old) {
if (old == CodeMirror.Init) old = false;
if (!old == !val) return;
if (val) setFullscreen(cm);
else setNormal(cm);
});
function setFullscreen(cm) {
var wrap = cm.getWrapperElement();
cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset,
width: wrap.style.width, height: wrap.style.height};
wrap.style.width = "";
wrap.style.height = "auto";
wrap.className += " CodeMirror-fullscreen";
document.documentElement.style.overflow = "hidden";
cm.refresh();
}
function setNormal(cm) {
var wrap = cm.getWrapperElement();
wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, "");
document.documentElement.style.overflow = "";
var info = cm.state.fullScreenRestore;
wrap.style.width = info.width; wrap.style.height = info.height;
window.scrollTo(info.scrollLeft, info.scrollTop);
cm.refresh();
}
})();
| 1,069 | Common Lisp | .l | 28 | 32.785714 | 96 | 0.668593 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 45005e3bbf8303b75efa8e69c296ece7f73995b171edbc17a2d5652738413c1f | 2,606 | [
-1
] |
2,607 | dialog.js | inaimathi_cl-notebook/static/js/addons/dialog.js | // Open simple dialogs on top of an editor. Relies on dialog.css.
(function() {
function dialogDiv(cm, template, bottom) {
var wrap = cm.getWrapperElement();
var dialog;
dialog = wrap.appendChild(document.createElement("div"));
if (bottom) {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
} else {
dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
}
if (typeof template == "string") {
dialog.innerHTML = template;
} else { // Assuming it's a detached DOM element.
dialog.appendChild(template);
}
return dialog;
}
function closeNotification(cm, newVal) {
if (cm.state.currentNotificationClose)
cm.state.currentNotificationClose();
cm.state.currentNotificationClose = newVal;
}
CodeMirror.defineExtension("openDialog", function(template, callback, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var closed = false, me = this;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
}
var inp = dialog.getElementsByTagName("input")[0], button;
if (inp) {
if (options && options.value) inp.value = options.value;
CodeMirror.on(inp, "keydown", function(e) {
if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
if (e.keyCode == 13 || e.keyCode == 27) {
inp.blur();
CodeMirror.e_stop(e);
close();
me.focus();
if (e.keyCode == 13) callback(inp.value);
}
});
if (options && options.onKeyUp) {
CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
}
if (options && options.value) inp.value = options.value;
inp.focus();
CodeMirror.on(inp, "blur", close);
} else if (button = dialog.getElementsByTagName("button")[0]) {
CodeMirror.on(button, "click", function() {
close();
me.focus();
});
button.focus();
CodeMirror.on(button, "blur", close);
}
return close;
});
CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
closeNotification(this, null);
var dialog = dialogDiv(this, template, options && options.bottom);
var buttons = dialog.getElementsByTagName("button");
var closed = false, me = this, blurring = 1;
function close() {
if (closed) return;
closed = true;
dialog.parentNode.removeChild(dialog);
me.focus();
}
buttons[0].focus();
for (var i = 0; i < buttons.length; ++i) {
var b = buttons[i];
(function(callback) {
CodeMirror.on(b, "click", function(e) {
CodeMirror.e_preventDefault(e);
close();
if (callback) callback(me);
});
})(callbacks[i]);
CodeMirror.on(b, "blur", function() {
--blurring;
setTimeout(function() { if (blurring <= 0) close(); }, 200);
});
CodeMirror.on(b, "focus", function() { ++blurring; });
}
});
/*
* openNotification
* Opens a notification, that can be closed with an optional timer
* (default 5000ms timer) and always closes on click.
*
* If a notification is opened while another is opened, it will close the
* currently opened one and open the new one immediately.
*/
CodeMirror.defineExtension("openNotification", function(template, options) {
closeNotification(this, close);
var dialog = dialogDiv(this, template, options && options.bottom);
var duration = options && (options.duration === undefined ? 5000 : options.duration);
var closed = false, doneTimer;
function close() {
if (closed) return;
closed = true;
clearTimeout(doneTimer);
dialog.parentNode.removeChild(dialog);
}
CodeMirror.on(dialog, 'click', function(e) {
CodeMirror.e_preventDefault(e);
close();
});
if (duration)
doneTimer = setTimeout(close, options.duration);
});
})();
| 4,087 | Common Lisp | .l | 116 | 29.12931 | 95 | 0.632442 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | f3739d3ca3be350373c993386aca6b9f2193a319408a83d661c9543691a329b3 | 2,607 | [
-1
] |
2,608 | mark-selection.js | inaimathi_cl-notebook/static/js/addons/mark-selection.js | // Because sometimes you need to mark the selected *text*.
//
// Adds an option 'styleSelectedText' which, when enabled, gives
// selected text the CSS class given as option value, or
// "CodeMirror-selectedtext" when the value is not a string.
(function() {
"use strict";
CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
cm.state.markedSelection = [];
cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
reset(cm);
cm.on("cursorActivity", onCursorActivity);
cm.on("change", onChange);
} else if (!val && prev) {
cm.off("cursorActivity", onCursorActivity);
cm.off("change", onChange);
clear(cm);
cm.state.markedSelection = cm.state.markedSelectionStyle = null;
}
});
function onCursorActivity(cm) {
cm.operation(function() { update(cm); });
}
function onChange(cm) {
if (cm.state.markedSelection.length)
cm.operation(function() { clear(cm); });
}
var CHUNK_SIZE = 8;
var Pos = CodeMirror.Pos;
function cmp(pos1, pos2) {
return pos1.line - pos2.line || pos1.ch - pos2.ch;
}
function coverRange(cm, from, to, addAt) {
if (cmp(from, to) == 0) return;
var array = cm.state.markedSelection;
var cls = cm.state.markedSelectionStyle;
for (var line = from.line;;) {
var start = line == from.line ? from : Pos(line, 0);
var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
var end = atEnd ? to : Pos(endLine, 0);
var mark = cm.markText(start, end, {className: cls});
if (addAt == null) array.push(mark);
else array.splice(addAt++, 0, mark);
if (atEnd) break;
line = endLine;
}
}
function clear(cm) {
var array = cm.state.markedSelection;
for (var i = 0; i < array.length; ++i) array[i].clear();
array.length = 0;
}
function reset(cm) {
clear(cm);
var from = cm.getCursor("start"), to = cm.getCursor("end");
coverRange(cm, from, to);
}
function update(cm) {
var from = cm.getCursor("start"), to = cm.getCursor("end");
if (cmp(from, to) == 0) return clear(cm);
var array = cm.state.markedSelection;
if (!array.length) return coverRange(cm, from, to);
var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
if (!coverStart || !coverEnd || to.line - from.line < CHUNK_SIZE ||
cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
return reset(cm);
while (cmp(from, coverStart.from) > 0) {
array.shift().clear();
coverStart = array[0].find();
}
if (cmp(from, coverStart.from) < 0) {
if (coverStart.to.line - from.line < CHUNK_SIZE) {
array.shift().clear();
coverRange(cm, from, coverStart.to, 0);
} else {
coverRange(cm, from, coverStart.from, 0);
}
}
while (cmp(to, coverEnd.to) < 0) {
array.pop().clear();
coverEnd = array[array.length - 1].find();
}
if (cmp(to, coverEnd.to) > 0) {
if (to.line - coverEnd.from.line < CHUNK_SIZE) {
array.pop().clear();
coverRange(cm, coverEnd.from, to);
} else {
coverRange(cm, coverEnd.to, to);
}
}
}
})();
| 3,306 | Common Lisp | .l | 94 | 29.808511 | 95 | 0.613196 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | bb8fbac52079df4d01264444b34a0451aca31e3e494527aadb2574059bbe3b90 | 2,608 | [
-1
] |
2,609 | fullscreen.css | inaimathi_cl-notebook/static/css/fullscreen.css | .CodeMirror-fullscreen {
position: fixed;
top: 0; left: 0; right: 0; bottom: 0;
height: auto;
z-index: 9;
}
| 116 | Common Lisp | .l | 6 | 17 | 39 | 0.654545 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 239e6a8c4e30f7274b29b3cb8f1ccbaf25461e1ff0cd9ead3573e6585a7df239 | 2,609 | [
-1
] |
2,610 | dialog.css | inaimathi_cl-notebook/static/css/dialog.css | .CodeMirror-dialog {
position: absolute;
left: 0; right: 0;
background: white;
z-index: 15;
padding: .1em .8em;
overflow: hidden;
color: #333;
}
.CodeMirror-dialog-top {
border-bottom: 1px solid #eee;
top: 0;
}
.CodeMirror-dialog-bottom {
border-top: 1px solid #eee;
bottom: 0;
}
.CodeMirror-dialog input {
border: none;
outline: none;
background: transparent;
width: 20em;
color: inherit;
font-family: monospace;
}
.CodeMirror-dialog button {
font-size: 70%;
}
| 502 | Common Lisp | .l | 28 | 15.5 | 32 | 0.704255 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | d2e6bfbff25b56a0c5a8a0ebc06ab6dfe618625ef5b51e96d9d8e7ebc12ff8ca | 2,610 | [
-1
] |
2,611 | genericons-regular-webfont.svg | inaimathi_cl-notebook/static/css/font/genericons-regular-webfont.svg | <?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
<svg xmlns="http://www.w3.org/2000/svg">
<metadata></metadata>
<defs>
<font id="genericonsregular" horiz-adv-x="2048" >
<font-face units-per-em="2048" ascent="1638" descent="-410" />
<missing-glyph horiz-adv-x="500" />
<glyph unicode="◼" horiz-adv-x="500" d="M0 0z" />
<glyph unicode="" d="M512 512v128h768v-128h-768zM512 768v128h256v-128h-256zM512 1024v128h640v-128h-640zM512 1280v128h1024v-128h-1024zM896 768v128h640v-128h-640zM1280 1024v128h256v-128h-256z" />
<glyph unicode="" d="M256 1024q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM768 1024q0 -106 75 -181t181 -75t181 75t75 181t-75 181t-181 75t-181 -75t-75 -181z" />
<glyph unicode="" d="M128 384v896l512 128l128 256h512l128 -256l512 -128v-896h-1792zM256 1440v160h256v-96zM576 960q0 -185 131.5 -316.5t316.5 -131.5q186 0 317 131.5t131 316.5q0 186 -131 317t-317 131q-185 0 -316.5 -131t-131.5 -317zM704 960q0 133 93.5 226.5t226.5 93.5 t226.5 -93.5t93.5 -226.5q0 -132 -93.5 -226t-226.5 -94t-226.5 94t-93.5 226z" />
<glyph unicode="" d="M128 512v384h384v-384h-384zM128 1024v384h896v-384h-896zM640 512v384h384v-384h-384zM1152 512v896h896v-896h-896z" />
<glyph unicode="" d="M512 384v1280l1152 -640z" />
<glyph unicode="" d="M640 1408q0 159 112.5 271.5t271.5 112.5t271.5 -112.5t112.5 -271.5q0 -124 -71.5 -222t-184.5 -138v-536l-256 -128v664q-113 40 -184.5 138t-71.5 222z" />
<glyph unicode="" d="M256 896v640h640v-640q0 -212 -150 -362t-362 -150v256q106 0 181 75t75 181h-384zM1152 896v640h640v-640q0 -212 -150 -362t-362 -150v256q106 0 181 75t75 181h-384z" />
<glyph unicode="" d="M512 704v384q0 97 53 176.5t139 116.5v-151q-64 -57 -64 -142v-384q0 -80 56 -136t136 -56t136 56t56 136v384q0 85 -64 142v151q86 -37 139 -116.5t53 -176.5v-384q0 -133 -93.5 -226.5t-226.5 -93.5t-226.5 93.5t-93.5 226.5zM768 1088v384q0 133 93.5 226.5 t226.5 93.5t226.5 -93.5t93.5 -226.5v-384q0 -97 -53 -176.5t-139 -116.5v151q64 57 64 142v384q0 80 -56 136t-136 56t-136 -56t-56 -136v-384q0 -85 64 -142v-151q-86 37 -139 116.5t-53 176.5z" />
<glyph unicode="" d="M0 1152v384q0 96 80 176t176 80h1024q96 0 176 -80t80 -176v-384q0 -96 -80 -176t-176 -80h-448l-448 -448v448h-128q-96 0 -176 80t-80 176zM768 640l128 128h384q168 0 276 108t108 276v384q96 0 176 -80t80 -176v-384q0 -96 -80 -176t-176 -80h-128v-448l-448 448 h-320z" />
<glyph unicode="" d="M256 768v512h384l384 384v-1280l-384 384h-384zM1205 843q75 75 75 181t-75 181l91 91q26 -27 46.5 -57.5t35 -65t22.5 -72.5t8 -77q0 -78 -29.5 -148t-82.5 -124zM1386 662q71 71 110.5 164.5t39.5 197.5t-39.5 197.5t-110.5 164.5l91 91q88 -89 137.5 -206t49.5 -247 q0 -87 -23 -170t-64.5 -153.5t-99.5 -129.5z" />
<glyph unicode="" d="M0 1024q0 208 81 398t218.5 327t327 218t397.5 81q209 0 398.5 -81t326.5 -218t218 -326.5t81 -398.5q0 -335 -195.5 -601.5t-504.5 -369.5q-36 -7 -53 8.5t-17 40.5q0 4 0.5 102t0.5 179q0 130 -69 189q77 9 137.5 24.5t124.5 51.5t107 89t70.5 140t27.5 201 q0 161 -105 274q6 15 11 35t9 56t-3.5 83.5t-26.5 96.5q-4 1 -10.5 2t-32 -1t-55.5 -11t-79.5 -33.5t-104.5 -61.5q-118 33 -256 35q-138 -2 -256 -35q-55 37 -104 61.5t-80 33t-54.5 11.5t-33.5 1l-10 -2q-58 -146 -10 -271q-105 -115 -105 -274q0 -114 27.5 -201 t70.5 -140t107 -89t124.5 -52t136.5 -24q-53 -47 -65 -137q-28 -13 -59.5 -20t-75.5 -6.5t-87.5 28.5t-75.5 83q-2 4 -6.5 10.5t-19 24t-31.5 31t-44 25.5t-56 14h-10t-18.5 -3.5t-17 -9t4 -18.5t34.5 -31q3 -1 7.5 -4t19 -14.5t27.5 -27t30 -43.5t30 -61q1 -3 2.5 -7t8 -17 t15.5 -25.5t24.5 -28t33.5 -28t45 -23.5t57.5 -16t71.5 -3.5t87 11.5q0 -50 0.5 -110t0.5 -64q0 -24 -17 -40t-53 -10q-309 103 -504.5 370t-195.5 602z" />
<glyph unicode="" d="M0 1024q0 206 82 395.5t219.5 327t327 219.5t395.5 82t395.5 -82t327 -219.5t219.5 -327t82 -395.5t-82 -395.5t-219.5 -327t-327 -219.5t-395.5 -82t-395.5 82t-327 219.5t-219.5 327t-82 395.5zM128 1024q0 -167 58 -319.5t166 -272.5q125 205 339 360t445 232 q-16 48 -80 176q-282 -86 -481.5 -111t-446.5 -1v-64zM160 1232q194 -22 444 14t388 82q-141 282 -320 528q-194 -85 -329.5 -247.5t-182.5 -376.5zM480 320q216 -192 544 -192q181 0 368 80q-33 300 -208 688q-222 -74 -410 -225.5t-294 -350.5zM832 1904 q102 -166 304 -512q6 2 86 31t118.5 45t108 47t122 64t93.5 69q-126 126 -290.5 199t-349.5 73q-32 0 -96 -8t-96 -8zM1200 1248q22 -29 36.5 -54.5t34 -67.5t25.5 -54q170 33 336 30t288 -30q-26 285 -160 464q-71 -57 -162 -104.5t-214.5 -100.5t-183.5 -83zM1344 928 q14 -27 43 -103t74.5 -231t74.5 -306q156 108 258 278t126 362q-276 46 -576 0z" />
<glyph unicode="" d="M128 465q48 -5 88 -5q256 0 456 157q-119 2 -213 73.5t-130 182.5q39 -7 69 -7q47 0 97 13q-127 26 -211 127t-84 233v5q80 -43 167 -46q-76 50 -120 131t-44 175q0 101 50 185q138 -170 335 -271.5t423 -112.5q-10 39 -10 84q0 152 108 259.5t260 107.5q160 0 268 -116 q128 26 233 89q-42 -132 -161 -203q109 13 211 58q-73 -111 -183 -191q0 -7 0.5 -23t0.5 -24q0 -122 -31 -246t-89.5 -241t-149.5 -218.5t-204 -177.5t-260.5 -119.5t-311.5 -43.5q-305 0 -564 165z" />
<glyph unicode="" d="M128 384v1280q0 106 75 181t181 75h1280q106 0 181 -75t75 -181v-1280q0 -106 -75 -181t-181 -75h-282v711h270l12 260h-282v192v12q0 60 21.5 87.5t87.5 27.5l166 -1l6 242q-78 10 -183 10q-94 0 -167 -27.5t-117 -74.5t-66 -105.5t-22 -126.5v-236h-254v-260h254v-711 h-724q-106 0 -181 75t-75 181z" />
<glyph unicode="" d="M640 969v303h222v258q0 78 26 147t77 124t136.5 87t194.5 32q55 0 108 -3t79 -6l26 -3l-7 -282h-193q-76 0 -101.5 -32t-25.5 -101v-14v-207h329l-14 -303h-315v-841h-320v841h-222z" />
<glyph unicode="" d="M128 1024q0 182 71 348t191 286t286 191t348 71t348 -71t286 -191t191 -286t71 -348t-71 -348t-191 -286t-286 -191t-348 -71t-348 71t-286 191t-191 286t-71 348zM218 1024q0 -236 125 -430.5t330 -294.5l-385 1053q-70 -156 -70 -328zM351 1466h52q37 0 91 2.5t89 4.5 l34 3q21 1 30.5 -14.5t2.5 -32.5t-27 -20q-44 -5 -93 -7l294 -873l176 529l-125 344l-85 7q-20 2 -27.5 19t2.5 33t30 15q133 -10 212 -10q38 0 91.5 2.5t88.5 4.5l35 3q16 1 25.5 -8.5t10 -22t-7 -23.5t-23.5 -13q-43 -5 -92 -7l291 -866l81 268q24 79 32.5 107.5 t18.5 74.5t10 79q0 46 -11.5 90.5t-23.5 71t-32 60.5q-2 4 -11.5 19t-12 20t-10.5 18.5t-11 19t-9 17.5t-8.5 19t-6.5 18t-5.5 19.5t-3 18.5t-1.5 20q0 57 39 100t97 43l10 -1q-110 101 -249.5 156.5t-294.5 55.5q-207 0 -385 -98t-288 -266zM796 251q112 -33 228 -33 q138 0 268 46q-4 6 -6 11l-248 679zM1429 328q183 106 292 291.5t109 404.5q0 207 -99 386q5 -40 5 -82q0 -135 -61 -289z" />
<glyph unicode="" d="M128 486v485q125 -127 330 -127q30 0 59 3q-32 -61 -32 -118q0 -33 13 -63t28.5 -48.5t45.5 -47.5q-18 0 -54.5 -0.5t-55.5 -0.5q-183 0 -334 -83zM128 1599v65q0 106 75 181t181 75h1280q106 0 181 -75t75 -181v-128h-256v256h-128v-256h-256v-128h256v-256h128v256h256 v-1024q0 -106 -75 -181t-181 -75h-507q5 28 5 50q0 143 -46.5 230t-189.5 194q-3 2 -20.5 15t-25 19t-25.5 20t-27.5 22.5t-24 22t-23 23.5t-17 22t-12.5 22.5t-4 20.5q0 52 23 87t99 94q180 141 180 324q0 113 -45 204.5t-128 139.5h160l135 142h-607q-127 0 -241.5 -49 t-194.5 -132zM139 309q57 85 166 137.5t237 51.5q84 -1 158 -26q19 -13 62 -42.5t61 -42t48 -37t44.5 -41.5t29 -41.5t21.5 -49.5q7 -29 7 -66q0 -16 -1 -24h-588q-85 0 -153 50.5t-92 130.5zM228 1307q-21 161 50.5 269.5t194.5 104.5q121 -4 215.5 -118.5t116.5 -277.5 q21 -160 -43 -256t-187 -92q-125 4 -225.5 108t-121.5 262z" />
<glyph unicode="" d="M256 1553q0 -73 50.5 -122t131.5 -49h2q84 0 135 49t51 122q-1 75 -51 123t-133 48t-134.5 -48.5t-51.5 -122.5zM275 256h330v991h-330v-991zM787 256h329v553q0 54 11 81q20 50 63 85t106 35q58 0 96 -29t54.5 -77.5t16.5 -117.5v-530h329v568q0 112 -28.5 198 t-80 139.5t-120 81t-150.5 27.5q-36 0 -69 -5.5t-58.5 -15t-49 -23t-40 -27t-32.5 -31t-26.5 -31.5t-21.5 -31v141h-329q1 -26 1.5 -138t0.5 -252.5t-0.5 -277.5t-1.5 -230v-93z" />
<glyph unicode="" d="M128 384v1280q0 106 75 181t181 75h1280q106 0 181 -75t75 -181v-1280q0 -106 -75 -181t-181 -75h-1280q-106 0 -181 75t-75 181zM384 1422q0 -58 40.5 -97.5t105.5 -39.5h1q67 0 108.5 39.5t41.5 97.5q-2 60 -42 98.5t-106 38.5q-67 0 -108 -39t-41 -98zM400 384h263 v793h-263v-793zM809 384h264v443q0 45 8 64q16 40 50.5 68t85.5 28q133 0 133 -179v-424h264v455q0 175 -83.5 266t-220.5 91q-50 0 -90.5 -12t-68.5 -34t-45 -41t-33 -44v112h-264v-793z" />
<glyph unicode="" d="M171 1260q0 109 35.5 219t110 213t179 182t254 126.5t323.5 47.5q176 0 327.5 -60.5t253.5 -161t160 -231t58 -270.5q0 -246 -85 -443t-241 -309.5t-355 -112.5q-99 0 -186.5 46.5t-121.5 110.5q-73 -290 -89 -347q-34 -123 -127 -270l-149 54q-7 167 22 290l162 688 q-40 81 -40 200q0 139 70.5 232.5t172.5 93.5q83 0 127 -53.5t44 -135.5q0 -51 -18.5 -124t-49 -170t-44.5 -154q-23 -99 37.5 -171t161.5 -72q117 0 209.5 92t142 244.5t49.5 334.5q0 214 -139 349t-387 135q-139 0 -257.5 -49.5t-197 -133t-122.5 -193t-44 -229.5 q0 -147 83 -247q18 -21 21.5 -34t-3.5 -37q-16 -61 -25 -101q-7 -24 -24.5 -32t-39.5 1q-127 51 -192.5 181.5t-65.5 300.5z" />
<glyph unicode="" d="M0 1024q0 208 81 398t218.5 327t327 218t397.5 81q209 0 398.5 -81t326.5 -218t218 -326.5t81 -398.5t-81 -398.5t-218 -326.5t-326.5 -218t-398.5 -81q-147 0 -290 42q74 116 103 219l72 282q28 -53 99 -90.5t151 -37.5q162 0 288.5 91.5t195.5 251t69 359.5 q0 114 -47 220t-130 187.5t-206.5 130.5t-265.5 49q-141 0 -262 -38.5t-205.5 -103t-145.5 -147.5t-89.5 -172.5t-28.5 -178.5q0 -138 53 -243.5t156 -147.5q18 -8 32.5 -1t18.5 26q2 9 10 41t11 41q5 19 2.5 30t-16.5 28q-68 78 -68 200q0 97 35.5 186t99.5 156.5t160 108 t209 40.5q201 0 313.5 -109.5t112.5 -283.5q0 -148 -40 -271.5t-115 -198t-169 -74.5q-82 0 -131.5 58.5t-30.5 138.5q11 46 35.5 125t39.5 138t15 101q0 66 -35.5 109.5t-102.5 43.5q-82 0 -139.5 -76t-57.5 -189q0 -43 8 -83.5t16 -59.5l9 -19q-113 -475 -132 -558 q-24 -97 -18 -235q-275 120 -444 374t-169 564z" />
<glyph unicode="" d="M160 1024q0 -172 122 -294t294 -122t294 122t122 294t-122 294t-294 122t-294 -122t-122 -294zM1056 1024q0 -172 122 -294t294 -122t294 122t122 294t-122 294t-294 122t-294 -122t-122 -294z" />
<glyph unicode="" d="M128 1379l84 -108q121 84 141 84q92 0 173 -287l144 -525q108 -287 265 -287q253 0 619 471q353 451 365 710q16 347 -260 355q-373 12 -505 -417q69 29 133 29q136 0 120 -152q-8 -92 -120 -268q-113 -176 -169 -176q-73 0 -133 271q-20 79 -72 407q-49 303 -258 284 q-89 -8 -265 -160q-127 -113 -262 -231z" />
<glyph unicode="" d="M128 768v512q0 159 112.5 271.5t271.5 112.5h1024q159 0 271.5 -112.5t112.5 -271.5v-512q0 -159 -112.5 -271.5t-271.5 -112.5h-1024q-159 0 -271.5 112.5t-112.5 271.5zM768 640l640 384l-640 384v-768z" />
<glyph unicode="" d="M472 1186h198v-629q0 -121 26 -187q26 -65 92 -122t161 -89q93 -31 218 -31q110 0 201 22q88 20 208 76v282q-134 -88 -271 -88q-76 0 -136 36q-44 25 -61 70q-17 46 -17 200v460h426v281h-426v453h-255q-17 -139 -62 -228q-48 -93 -121 -154q-74 -64 -181 -99v-253z" />
<glyph unicode="" d="M128 384v1280q0 106 75 181t181 75h1280q106 0 181 -75t75 -181v-1280q0 -106 -75 -181t-181 -75h-1280q-106 0 -181 75t-75 181zM256 384q0 -53 37.5 -90.5t90.5 -37.5h1280q53 0 90.5 37.5t37.5 90.5v768h-272q16 -66 16 -128q0 -212 -150 -362t-362 -150t-362 150 t-150 362q0 62 16 128h-272v-768zM640 1024q0 -159 112.5 -271.5t271.5 -112.5t271.5 112.5t112.5 271.5t-112.5 271.5t-271.5 112.5t-271.5 -112.5t-112.5 -271.5zM1408 1536q0 -53 37.5 -90.5t90.5 -37.5h128q53 0 90.5 37.5t37.5 90.5v128q0 53 -37.5 90.5t-90.5 37.5 h-128q-53 0 -90.5 -37.5t-37.5 -90.5v-128z" />
<glyph unicode="" d="M256 790v467q0 31 29 55l702 467q17 11 37 11t37 -11l702 -467q29 -24 29 -55v-467q0 -32 -29 -54l-702 -468q-17 -11 -37 -11q-18 0 -37 11l-702 468q-29 22 -29 54zM388 914l165 110l-165 110v-220zM441 790l517 -344v308l-286 191zM441 1257l231 -154l286 191v307z M791 1024l233 -156l234 156l-234 156zM1090 446l517 344l-231 155l-286 -191v-308zM1090 1294l286 -191l231 154l-517 344v-307zM1495 1024l165 -110v220z" />
<glyph unicode="" d="M128 1024q0 182 71 348t191 286t286 191t348 71t348 -71t286 -191t191 -286t71 -348t-71 -348t-191 -286t-286 -191t-348 -71t-348 71t-286 191t-191 286t-71 348zM208 1024q0 -221 109.5 -409t297.5 -297.5t409 -109.5q236 0 432 123.5t298 327.5q59 136 59 266 q0 117 -43.5 221.5t-118.5 182.5t-175.5 131t-215.5 73q116 -48 204 -145t127 -218q54 -151 17.5 -320t-150.5 -289q-111 -123 -276 -179t-332 -27q-168 27 -307 138t-210 270q-74 156 -67.5 338.5t93.5 335.5q88 155 238.5 260t328.5 135q2 0 35 6q-208 -16 -380.5 -128 t-272.5 -293.5t-100 -392.5zM359 998q17 -148 100 -275.5t207 -200.5q120 -71 264 -78.5t267 49.5q-76 -21 -148 -21q-149 0 -275.5 74t-200.5 201t-74 276q0 214 146 373l3 3l14 14l1 1q98 114 235 178t293 64q163 0 306 -70t241 -193q-36 57 -70 96q-104 126 -250 200.5 t-305 80.5q-157 7 -306.5 -51.5t-258.5 -169.5q-109 -107 -159 -254.5t-30 -296.5zM612 1025q8 -119 85 -217t186 -128q110 -33 221.5 8.5t170.5 134.5q61 91 50 204t-86 187q-70 77 -179.5 87t-188.5 -50q-85 -62 -105 -157q-21 -98 30 -182q50 -84 142 -108q92 -23 172 26 q38 23 64 58.5t34 76.5q17 88 -34 159q-52 72 -136 77q-83 6 -142 -54q-57 -55 -45 -138q6 -37 27.5 -68.5t52.5 -47.5q40 -21 87 -16q-46 1 -82 29t-49 71l-2 3q-14 30 -9.5 67t25.5 66q22 30 56.5 46.5t72.5 14.5t73.5 -23.5t54.5 -55.5q46 -76 8 -158 q-18 -39 -53.5 -66.5t-78.5 -35.5q-43 -9 -88.5 3.5t-78.5 43.5q-74 68 -68 169q2 65 45 118.5t109.5 77t132.5 5.5q68 -16 118.5 -70.5t65 -124.5t-9.5 -144q-37 -107 -150 -158.5t-224 -8.5q-114 43 -170 158q-55 117 -17 238q35 121 152 191t246 47q131 -19 223 -128 t95 -246q6 -142 -81 -257q-86 -115 -225 -157q-114 -35 -234 -7q83 -34 174 -34q195 0 333.5 138.5t138.5 333.5v2q-10 107 -63.5 202.5t-137.5 157.5q-102 77 -236 87t-243 -49q-116 -62 -177 -167q-61 -107 -52 -231z" />
<glyph unicode="" d="M128 464q0 -66 32 -125.5t92.5 -107t159 -75.5t222.5 -28q117 0 218.5 25t174 68t124 99.5t76.5 120.5t25 131q0 40 -6.5 74.5t-22.5 65t-30.5 53t-41.5 50t-45 43t-51 44.5l-85 66q-19 15 -28.5 24.5t-21 31t-11.5 45.5t12 47.5t21.5 34.5t32.5 33q37 29 59 48t52 52 t46 64t28 75.5t12 94.5q0 43 -8 82t-23.5 70.5t-30.5 55.5t-38 47.5t-35 34.5t-32 27h146l151 85h-485q-264 0 -421 -129q-73 -64 -111.5 -147.5t-38.5 -167.5q0 -56 16 -109.5t49.5 -100.5t79.5 -82.5t109 -56.5t136 -21q19 0 75 5q0 -2 -4 -10.5t-4.5 -10.5t-3.5 -9.5 t-4 -11l-3 -10.5t-2.5 -12.5t-1 -13t-0.5 -14.5q0 -26 5 -48t18.5 -45t20.5 -32.5t26 -34.5q-61 -4 -98 -7.5t-107 -14.5t-131.5 -32.5t-112.5 -53.5q-50 -29 -86.5 -66.5t-56.5 -76.5t-29 -74.5t-9 -69.5zM335 514q0 47 17 87.5t38.5 64.5t54 45t50.5 28.5t42 16.5 q35 11 76.5 19.5t77.5 12t58.5 5t34.5 1.5q35 0 54 -3q51 -36 82 -59t63.5 -50.5t50.5 -48.5t33.5 -46t21.5 -50.5t6 -55.5q0 -113 -91 -183.5t-255 -70.5q-187 0 -300.5 80t-113.5 207zM453 1591q0 110 51 174q28 35 73.5 56t91.5 21q56 0 105.5 -28.5t83.5 -74.5 t59 -103.5t36.5 -115.5t11.5 -110q0 -113 -59 -172q-18 -19 -44 -33.5t-56.5 -23.5t-58.5 -9q-58 0 -108 28.5t-83.5 73.5t-57.5 101.5t-34.5 111.5t-10.5 104zM1408 1024v128h256v256h128v-256h256v-128h-256v-256h-128v256h-256z" />
<glyph unicode="" d="M134.5 1267.5q5.5 80.5 41 179.5t102.5 191q70 78 153.5 135t167 86.5t172 45.5t169 15t156.5 -8t137.5 -21t107.5 -26.5t72 -22.5l25 -9q12 -5 32 -14.5t74.5 -45.5t101 -78.5t97 -114.5t78 -153t27.5 -194.5t-40 -238.5q-43 -89 -97 -157.5t-109.5 -110t-115.5 -69 t-115.5 -37t-107.5 -12t-95.5 4t-76 13t-49.5 13.5l-18 6v-277q-1 -3 -2 -9t-6.5 -23t-14 -34t-24.5 -39.5t-36 -42t-51.5 -39.5t-68.5 -33q-52 -19 -107 -20t-97 11.5t-76.5 27.5t-53.5 27l-18 13v280q33 -34 67 -55.5t67.5 -28.5t61.5 11t44 63v946h312v-538l65 -13 q206 -32 329 60q105 78 128 243q2 76 -15.5 141t-49 110.5t-72.5 82.5t-86.5 59.5t-91.5 39t-87.5 24t-73.5 11.5t-52 5h-19l-66 -2q-217 -16 -359 -141q-57 -50 -97 -115q-27 -45 -39.5 -93t-11 -88t10 -78.5t22 -67.5t25.5 -51t21 -33l9 -12l-225 -201q-7 9 -18.5 25 t-40.5 68.5t-49.5 107.5t-34.5 137.5t-8.5 163z" />
<glyph unicode="" d="M141 1431q0 133 65.5 245.5t178 178t245.5 65.5q141 0 260 -75q69 12 144 12q171 0 327 -66.5t269 -179.5t179.5 -269t66.5 -327q0 -96 -19 -181q51 -106 50 -217q0 -133 -65.5 -245.5t-178 -178t-244.5 -65.5q-123 0 -231 58q-79 -14 -155 -14q-171 0 -327 67t-269 180 t-179.5 269t-66.5 327q0 86 17 169q-67 116 -67 247zM537 775q0 -75 54 -153q52 -76 139 -123q119 -63 302 -63q150 0 263 46q111 46 171 130q59 85 59 188q0 88 -34 149q-35 62 -96 100q-58 39 -143 66q-77 25 -187 49q-89 20 -116 28q-35 9 -68 27q-33 15 -50 38 q-17 20 -17 49q0 46 52 80q54 36 146 36q97 0 141 -32q43 -32 75 -94q30 -48 51 -67q25 -22 72 -22q53 0 87 36q34 35 34 81t-25 96q-24 47 -82 92q-57 45 -139 70q-86 26 -197 26q-139 0 -247 -40q-107 -39 -164 -113q-57 -73 -57 -170q0 -102 55 -170q52 -65 144 -105 q95 -40 221 -66q93 -20 154 -38q57 -19 90 -50q33 -30 33 -80q0 -64 -62 -105q-65 -44 -170 -44q-78 0 -123 22q-47 22 -70 54q-27 34 -49 86q-21 49 -49 72q-32 26 -75 26q-52 0 -87 -33q-36 -33 -36 -79z" />
<glyph unicode="" d="M384 384v640h192q49 0 104 47t103.5 127.5t80.5 204.5t32 261q0 5 0.5 13.5t4 31t9.5 39t19 30.5t31 14q33 0 77.5 -42t79.5 -119t35 -159q0 -85 -8 -165t-16 -117l-8 -38h416q53 0 90.5 -37.5t37.5 -90.5q0 -41 -24 -74t-62 -46q22 -33 22 -72q0 -41 -24 -74t-62 -46 q22 -33 22 -72q0 -53 -37.5 -90.5t-90.5 -37.5h-64q53 0 90.5 -37.5t37.5 -90.5t-37.5 -90.5t-90.5 -37.5h-448q-65 0 -123 20t-93.5 44t-80.5 44t-87 20h-128z" />
<glyph unicode="" d="M205 1168q0 83 59 142t142 59q100 0 160 -83q183 97 412 106l92 457q5 22 23 33q18 12 39 7l313 -72q24 41 65.5 65.5t89.5 24.5q74 0 126.5 -52.5t52.5 -126.5t-52.5 -126.5t-126.5 -52.5q-71 0 -122 48.5t-56 119.5l-262 60l-77 -386q222 -12 397 -108q60 86 163 86 q83 0 141.5 -59t58.5 -142q0 -55 -28 -100.5t-74 -72.5q14 -50 14 -99q0 -135 -98.5 -250t-267.5 -181.5t-368 -66.5t-368.5 66.5t-268 181t-98.5 249.5q0 50 16 104q-44 27 -70.5 71.5t-26.5 97.5zM307 1168q0 -47 40 -75q47 75 132 137q-29 36 -73 36q-41 0 -70 -28.5 t-29 -69.5zM388 896q0 -107 85 -198t230.5 -144t317.5 -53q171 0 316.5 53t230.5 143.5t85 197.5q0 108 -85 199t-230.5 144t-316.5 53q-172 0 -317.5 -53t-230.5 -144t-85 -198zM672 982q0 46 32.5 79t78.5 33q47 0 79.5 -33t32.5 -79t-33 -79t-79 -33t-78.5 33t-32.5 79z M737 739.5q0 21.5 15 36.5t36 15t36 -15q56 -56 199 -56q145 0 201 56q15 15 36 15t36 -15t15 -36.5t-15 -36.5q-86 -86 -271 -86q-187 0 -273 86q-15 15 -15 36.5zM1153 982q0 46 32.5 79t79.5 33t79.5 -33t32.5 -79t-33 -79t-79 -33t-79 33t-33 79zM1523 1728 q0 -32 22.5 -54.5t54.5 -22.5t54.5 22.5t22.5 54.5t-22.5 54.5t-54.5 22.5t-54.5 -22.5t-22.5 -54.5zM1567 1227q83 -61 131 -138q43 31 43 79q0 40 -28.5 69t-69.5 29q-45 0 -76 -39z" />
<glyph unicode="" d="M256 849v209h263v-206q0 -33 23.5 -56.5t57.5 -23.5t57.5 23.5t23.5 56.5v487q5 136 104.5 230.5t238.5 94.5t238.5 -95.5t104.5 -231.5v-107l-157 -45l-105 48v92q0 34 -23.5 57t-57.5 23t-57.5 -23t-23.5 -57l-1 -481q-1 -138 -101.5 -235t-241.5 -97q-142 0 -242.5 99 t-100.5 238zM1105 846v210l105 -48l157 46v-212q0 -33 23.5 -56.5t57.5 -23.5t57.5 23.5t23.5 56.5v216h263v-209q0 -139 -100.5 -238t-242.5 -99t-242 97.5t-102 236.5z" />
<glyph unicode="" d="M256 1152v384q0 106 75 181t181 75h1024q106 0 181 -75t75 -181v-384q0 -209 -103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM512 1281q0 -53 38 -91l362 -362l4 4q37 -64 108 -64t108 64l5 -4l362 362q37 38 37 91t-37 90t-91 37 q-53 0 -90 -37l-294 -294l-293 294q-37 37 -91 37t-90 -37q-38 -37 -38 -90z" />
<glyph unicode="" d="M128 930l365 291l531 -328l-369 -308zM128 1513l527 345l369 -308l-531 -329zM497 508v115l158 -103l370 307l370 -307l158 103v-115l-528 -317zM1024 893l532 328l364 -291l-527 -345zM1024 1550l369 308l527 -345l-364 -292z" />
<glyph unicode="" d="M256 896v384q0 106 75 181t181 75h1024q106 0 181 -75t75 -181v-384q0 -106 -75 -181t-181 -75h-448l-448 -448v448h-128q-106 0 -181 75t-75 181z" />
<glyph unicode="" d="M384 512v1024h384l64 -128h448v-128h-640l-128 -256h128l64 128h960l-256 -640h-1024z" />
<glyph unicode="" d="M256 768l768 768h512v-512l-768 -768zM1152 1280q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M256 1088q0 143 55.5 273.5t150 225t225 150t273.5 55.5t273.5 -55.5t225 -150t150 -225t55.5 -273.5t-55.5 -273.5t-150 -225t-225 -150t-273.5 -55.5t-273.5 55.5t-225 150t-150 225t-55.5 273.5zM384 1088q0 -117 45.5 -223.5t123 -184t184 -123t223.5 -45.5 t223.5 45.5t184 123t123 184t45.5 223.5t-45.5 223.5t-123 184t-184 123t-223.5 45.5t-223.5 -45.5t-184 -123t-123 -184t-45.5 -223.5zM896 1062v474h128v-421l298 -298l-90 -91z" />
<glyph unicode="" d="M512 384v256q0 159 112.5 271.5t271.5 112.5h256q159 0 271.5 -112.5t112.5 -271.5v-256h-1024zM768 1408q0 106 75 181t181 75t181 -75t75 -181t-75 -181t-181 -75t-181 75t-75 181z" />
<glyph unicode="" d="M256 384v1280h256v128h128v-128h640v128h128v-128h256v-1280h-1408zM384 640q0 -53 37.5 -90.5t90.5 -37.5h896q53 0 90.5 37.5t37.5 90.5v640q0 53 -37.5 90.5t-90.5 37.5h-896q-53 0 -90.5 -37.5t-37.5 -90.5v-640zM768 1216q0 26 19 45t45 19h128q26 0 45 -19t19 -45 v-512q0 -26 -19 -45t-45 -19t-45 19t-19 45v448h-64q-26 0 -45 19t-19 45z" />
<glyph unicode="" d="M256 384v1280h256v128h128v-128h640v128h128v-128h256v-1280h-1408zM384 640q0 -53 37.5 -90.5t90.5 -37.5h896q53 0 90.5 37.5t37.5 90.5v640q0 53 -37.5 90.5t-90.5 37.5h-896q-53 0 -90.5 -37.5t-37.5 -90.5v-640zM768 1216q0 26 19 45t45 19h256h2h1h3 q22 -2 38.5 -18t19.5 -39v-2v-2v-1v-2q0 -5 -2 -15l-128 -512q-6 -26 -28.5 -40t-48.5 -7q-26 6 -40 28.5t-7 48.5l108 433h-174q-26 0 -45 19t-19 45z" />
<glyph unicode="" d="M256 384v1280h256v128h128v-128h640v128h128v-128h256v-1280h-1408zM384 640q0 -53 37.5 -90.5t90.5 -37.5h896q53 0 90.5 37.5t37.5 90.5v640q0 53 -37.5 90.5t-90.5 37.5h-896q-53 0 -90.5 -37.5t-37.5 -90.5v-640zM512 640v128h128v-128h-128zM512 896v128h128v-128 h-128zM768 640v128h128v-128h-128zM768 896v128h128v-128h-128zM768 1152v128h128v-128h-128zM1024 640v128h128v-128h-128zM1024 896v128h128v-128h-128zM1024 1152v128h128v-128h-128zM1280 896v128h128v-128h-128zM1280 1152v128h128v-128h-128z" />
<glyph unicode="" d="M342 342q12 45 22 71t38 66.5t76 88.5l395 395l-227 227l181 181q37 -37 90.5 -37t91.5 37l181 181q38 38 38 91t-38 90l181 181l543 -543l-181 -181q-37 38 -90 38t-91 -38l-181 -181q-37 -37 -37 -90t37 -91l-181 -181l-227 226l-395 -395q-68 -68 -113.5 -93 t-112.5 -43z" />
<glyph unicode="" d="M256 1216q0 117 45.5 223.5t123 184t184 123t223.5 45.5t223.5 -45.5t184 -123t123 -184t45.5 -223.5q0 -184 -111 -337l495 -495l-128 -128l-495 495q-153 -111 -337 -111q-117 0 -223.5 45.5t-184 123t-123 184t-45.5 223.5zM384 1216q0 -185 131.5 -316.5 t316.5 -131.5q186 0 317 131.5t131 316.5t-131 316.5t-317 131.5q-185 0 -316.5 -131.5t-131.5 -316.5z" />
<glyph unicode="" d="M256 1216q0 117 45.5 223.5t123 184t184 123t223.5 45.5t223.5 -45.5t184 -123t123 -184t45.5 -223.5q0 -184 -111 -337l495 -495l-128 -128l-495 495q-153 -111 -337 -111q-117 0 -223.5 45.5t-184 123t-123 184t-45.5 223.5zM384 1216q0 -185 131.5 -316.5 t316.5 -131.5q186 0 317 131.5t131 316.5t-131 316.5t-317 131.5q-185 0 -316.5 -131.5t-131.5 -316.5zM512 1152v128h640v-128h-640z" />
<glyph unicode="" d="M256 1216q0 117 45.5 223.5t123 184t184 123t223.5 45.5t223.5 -45.5t184 -123t123 -184t45.5 -223.5q0 -184 -111 -337l495 -495l-128 -128l-495 495q-153 -111 -337 -111q-117 0 -223.5 45.5t-184 123t-123 184t-45.5 223.5zM384 1216q0 -185 131.5 -316.5 t316.5 -131.5q186 0 317 131.5t131 316.5t-131 316.5t-317 131.5q-185 0 -316.5 -131.5t-131.5 -316.5zM512 1152v128h256v256h128v-256h256v-128h-256v-256h-128v256h-256z" />
<glyph unicode="" d="M0 1024l506 506q101 103 234.5 160.5t283.5 57.5t283.5 -57.5t233.5 -159.5l507 -507l-506 -507q-101 -103 -234.5 -160t-283.5 -57t-283.5 57.5t-233.5 160.5zM272 1024l370 -371q77 -78 175.5 -119.5t206.5 -41.5t206 41.5t174 118.5l373 372l-371 371 q-158 161 -382 161q-108 0 -206.5 -41t-173.5 -119zM640 1024q0 159 112.5 271.5t271.5 112.5t271.5 -112.5t112.5 -271.5t-112.5 -271.5t-271.5 -112.5t-271.5 112.5t-112.5 271.5zM1024 1152q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5 t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M0 1024l506 506q101 103 234.5 160.5t283.5 57.5q193 0 358 -95l-143 -143q-103 46 -215 46q-108 0 -206.5 -41t-173.5 -119l-372 -372l240 -240l-136 -136zM339 429l90 -90l1280 1280l-90 90zM640 1024q0 159 112.5 271.5t271.5 112.5q44 0 98 -14l-468 -468 q-14 54 -14 98zM666 395l143 143q103 -46 215 -46q108 0 206 41.5t174 118.5l373 372l-241 241l136 135l376 -376l-506 -507q-101 -103 -234.5 -160t-283.5 -57q-193 0 -358 95zM926 654l468 468q14 -54 14 -98q0 -159 -112.5 -271.5t-271.5 -112.5q-44 0 -98 14z" />
<glyph unicode="" d="M640 768l320 320l-320 320l128 128l320 -320l320 320l128 -128l-320 -320l320 -320l-128 -128l-320 320l-320 -320z" />
<glyph unicode="" d="M128 256l832 832l-832 832l128 128l832 -832l832 832l128 -128l-832 -832l832 -832l-128 -128l-832 832l-832 -832z" />
<glyph unicode="" d="M384 1280v128l256 128q0 53 37.5 90.5t90.5 37.5h384q53 0 90.5 -37.5t37.5 -90.5l256 -128v-128h-1152zM512 512v704h128v-704h128v704h128v-704h128v704h128v-704h128v704h128v-704q0 -53 -37.5 -90.5t-90.5 -37.5h-640q-53 0 -90.5 37.5t-37.5 90.5zM768 1472 q0 -26 19 -45t45 -19h256q26 0 45 19t19 45t-19 45t-45 19h-256q-26 0 -45 -19t-19 -45z" />
<glyph unicode="" d="M256 1151l476 -330l-183 -535l475 332l475 -332l-183 535l476 330l-587 -1l-181 535l-180 -535z" />
<glyph unicode="" d="M384 1152l640 512l640 -512l-128 -128v-512h-1024v512zM896 576h256v448h-256v-448z" />
<glyph unicode="" d="M256 512v704l768 -384l768 384v-704h-1536zM256 1408v128h1536v-128l-768 -384z" />
<glyph unicode="" d="M384 384v448l896 896l448 -448l-896 -896h-448zM512 768l256 -256l128 128l-256 256zM685 941l96 -96l595 595l-96 96zM845 781l96 -96l595 595l-96 96z" />
<glyph unicode="" d="M256 640v704l384 384v-704h640v448l640 -640l-640 -640v448h-1024z" />
<glyph unicode="" d="M256 448q0 -80 56 -136t136 -56t136 56t56 136t-56 136t-136 56t-136 -56t-56 -136zM256 1024v256q209 0 398.5 -81t326.5 -218t218 -326.5t81 -398.5h-256q0 209 -103 385.5t-279.5 279.5t-385.5 103zM256 1536v256q209 0 408 -55t367.5 -154t310.5 -241t241 -310.5 t154 -367.5t55 -408h-256q0 260 -101.5 497t-273 408.5t-408.5 273t-497 101.5z" />
<glyph unicode="" d="M21 358q-57 102 31 244l760 1237q57 93 134.5 126.5t155 0t135.5 -126.5l759 -1237q88 -142 31 -244t-224 -102h-1557q-168 0 -225 102zM883 1536l51 -640h179l52 640h-282zM896 640q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5 t-37.5 -90.5z" />
<glyph unicode="" d="M128 1024v256h310q75 172 233.5 278t352.5 106q130 0 246.5 -50t204.5 -139q37 -37 37 -90t-37 -91t-90 -38t-91 38q-116 114 -270 114q-159 0 -271.5 -112.5t-112.5 -271.5h-512zM536 665q0 53 38 90t91 37t90 -37q113 -115 269 -115q159 0 271.5 112.5t112.5 271.5h512 v-256h-310q-75 -172 -233.5 -278t-352.5 -106q-130 0 -246 50t-205 139l1 1q-38 38 -38 91zM832 1024q0 80 56 136t136 56t136 -56t56 -136t-56 -136t-136 -56t-136 56t-56 136z" />
<glyph unicode="" d="M512 832v320h128v-320q0 -133 93.5 -226.5t226.5 -93.5t226.5 93.5t93.5 226.5v640q0 80 -56 136t-136 56t-136 -56t-56 -136v-512q0 -26 19 -45t45 -19t45 19t19 45v452h128v-452q0 -80 -56 -136t-136 -56t-136 56t-56 136v512q0 133 93.5 226.5t226.5 93.5t226.5 -93.5 t93.5 -226.5v-640q0 -185 -131.5 -316.5t-316.5 -131.5t-316.5 131.5t-131.5 316.5z" />
<glyph unicode="" d="M384 1216q0 117 45.5 223.5t123 184t184 123t223.5 45.5t223.5 -45.5t184 -123t123 -184t45.5 -223.5t-44.5 -222.5t-124.5 -185.5l-407 -406l-407 406q-80 80 -124.5 185.5t-44.5 222.5zM640 1216q0 -133 93.5 -226.5t226.5 -93.5t226.5 93.5t93.5 226.5t-93.5 226.5 t-226.5 93.5t-226.5 -93.5t-93.5 -226.5z" />
<glyph unicode="" d="M608 1056l128 128l224 -192l448 512l128 -96l-512 -768h-128z" />
<glyph unicode="" d="M0 256v256h2048v-256h-2048zM0 896v256h2048v-256h-2048zM0 1536v256h2048v-256h-2048z" />
<glyph unicode="" d="M256 1024q0 155 60 294.5t167 246.5l-227 227h640v-640l-232 232q-72 -71 -112 -163.5t-40 -196.5q0 -176 108.5 -313.5t275.5 -180.5v-262q-180 30 -326 137t-230 269.5t-84 349.5zM1152 256v640l19 -19l213 -213q71 71 111.5 164t40.5 196q0 176 -108.5 313.5 t-275.5 180.5v263q180 -31 326 -137.5t230 -269.5t84 -350q0 -155 -60 -294.5t-167 -246.5l227 -227h-640z" />
<glyph unicode="" d="M384 896v256h1152v-256h-1152z" />
<glyph unicode="" d="M384 512v1024h1152v-1024h-1152zM512 640h896v640h-896v-640z" />
<glyph unicode="" d="M83 832l373 671l112 -62l-267 -481h403v-384h-128v256h-493zM768 1024q0 87 43 160.5t116.5 116.5t160.5 43t160.5 -43t116.5 -116.5t43 -160.5t-43 -160.5t-116.5 -116.5t-160.5 -43t-160.5 43t-116.5 116.5t-43 160.5zM896 1024q0 -79 56.5 -135.5t135.5 -56.5 t135.5 56.5t56.5 135.5t-56.5 135.5t-135.5 56.5t-135.5 -56.5t-56.5 -135.5zM1427 832l373 671l112 -62l-267 -481h403v-384h-128v256h-493z" />
<glyph unicode="" d="M256 640v768l384 384h768l384 -384v-768l-384 -384h-768zM883 1536l51 -640h179l52 640h-282zM896 640q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M384 384v1280h256q0 53 37.5 90.5t90.5 37.5h384q53 0 90.5 -37.5t37.5 -90.5h256v-1280h-1152zM512 512h896v1024h-128v-128h-640v128h-128v-1024zM640 704q0 26 19 45t45 19t45 -19t19 -45t-19 -45t-45 -19t-45 19t-19 45zM640 960q0 26 19 45t45 19t45 -19t19 -45 t-19 -45t-45 -19t-45 19t-19 45zM640 1216q0 26 19 45t45 19t45 -19t19 -45t-19 -45t-45 -19t-45 19t-19 45zM768 1600q0 -26 19 -45t45 -19h256q26 0 45 19t19 45t-19 45t-45 19h-256q-26 0 -45 -19t-19 -45zM896 640v128h384v-128h-384zM896 896v128h384v-128h-384z M896 1152v128h384v-128h-384z" />
<glyph unicode="" d="M128 768q0 106 75 181t181 75h7q-7 29 -7 64q0 133 93.5 226.5t226.5 93.5q134 0 228 -96q47 101 140.5 162.5t207.5 61.5q159 0 271.5 -112.5t112.5 -271.5q0 -62 -23 -128h23q106 0 181 -75t75 -181t-75 -181t-181 -75h-1280q-106 0 -181 75t-75 181z" />
<glyph unicode="" d="M384 384v288l455 455l-1 1q-74 74 -74 180t74 181l233 233q75 74 181 74t180 -74l286 -286q74 -75 74 -180.5t-74 -180.5l-233 -233q-74 -73 -178.5 -74t-179.5 71l-455 -455h-288zM1088 1360l256 -256l160 160l-256 256z" />
<glyph unicode="" d="M768 1024q0 106 75 181t181 75t181 -75t75 -181t-75 -181t-181 -75t-181 75t-75 181z" />
<glyph unicode="" d="M384 896v128h896l-343 343l87 86l493 -493l-493 -493l-87 86l343 343h-896z" />
<glyph unicode="" d="M531 960l493 -493l87 86l-343 343h896v128h-896l343 343l-87 86z" />
<glyph unicode="" d="M384 1152l128 128l448 -448l448 448l128 -128l-576 -576z" />
<glyph unicode="" d="M384 768l576 576l576 -576l-128 -128l-448 448l-448 -448z" />
<glyph unicode="" d="M0 0v896l896 -896h-896z" />
<glyph unicode="" d="M1152 0l896 896v-896h-896z" />
<glyph unicode="" d="M384 512l640 640l640 -640h-1280zM384 1280v128h1280v-128h-1280z" />
<glyph unicode="" d="M512 640v128h128v-128h-128zM512 896v128h128v-128h-128zM512 1152v128h128v-128h-128zM512 1408v128h128v-128h-128zM768 640v128h128v-128h-128zM768 896v128h128v-128h-128zM768 1152v128h128v-128h-128zM768 1408v128h128v-128h-128zM1024 640v128h128v-128h-128z M1024 896v128h128v-128h-128zM1024 1152v128h128v-128h-128zM1024 1408v128h128v-128h-128zM1280 640v128h128v-128h-128zM1280 896v128h128v-128h-128zM1280 1152v128h128v-128h-128zM1280 1408v128h128v-128h-128z" />
<glyph unicode="" d="M512 512v1024q0 106 75 181t181 75h512q106 0 181 -75t75 -181v-1024q0 -106 -75 -181t-181 -75h-512q-106 0 -181 75t-75 181zM640 768h768v768h-768v-768zM896 512q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z " />
<glyph unicode="" d="M256 1024v256h512v128l384 -256l-384 -256v128h-512zM512 512v384h128v-128h768v768h-768v-128h-128v128q0 106 75 181t181 75h512q106 0 181 -75t75 -181v-1024q0 -106 -75 -181t-181 -75h-512q-106 0 -181 75t-75 181zM896 512q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5 t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M384 1152h1280q0 -231 -145.5 -406.5t-366.5 -220.5v-269h-256v269q-221 45 -366.5 220.5t-145.5 406.5zM640 1280v384q0 53 37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5v-384h-256zM1152 1280v384q0 53 37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5v-384h-256z" />
<glyph unicode="" d="M128 768q0 106 75 181t181 75h6q-6 32 -6 64q0 133 93.5 226.5t226.5 93.5q134 0 228 -96q47 101 140.5 162.5t207.5 61.5q159 0 271.5 -112.5t112.5 -271.5q0 -62 -23 -128h23q106 0 181 -75t75 -181t-75 -181t-181 -75h-384v256h-512v-256h-384q-106 0 -181 75t-75 181 zM640 384h256v256h256v-256h256l-384 -384z" />
<glyph unicode="" d="M128 768q0 106 75 181t181 75h6q-6 32 -6 64q0 133 93.5 226.5t226.5 93.5q134 0 228 -96q47 101 140.5 162.5t207.5 61.5q159 0 271.5 -112.5t112.5 -271.5q0 -62 -23 -128h23q106 0 181 -75t75 -181t-75 -181t-181 -75h-512v256h256l-384 384l-384 -384h256v-256h-512 q-106 0 -181 75t-75 181z" />
<glyph unicode="" d="M512 512v896h512l-128 -128h-256v-640h640v256l128 128v-512h-896zM896 987l550 549h-422v128h640v-640h-128v422l-550 -550z" />
<glyph unicode="" d="M512 384v1280h640l384 -384v-896h-1024zM640 512h768v640h-384v384h-384v-1024z" />
<glyph unicode="" d="M384 512v1024q0 106 75 181t181 75h1024v-1152h-64q-53 0 -90.5 -37.5t-37.5 -90.5t37.5 -90.5t90.5 -37.5h64v-128h-1024q-106 0 -181 75t-75 181zM512 512q0 -53 37.5 -90.5t90.5 -37.5h818q-50 55 -50 128t50 128h-818q-53 0 -90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M160 747l232 201q-8 67 -8 76q0 8 8 75l-232 201l58 139l305 -21q47 60 107 107l-21 305l139 58l201 -232q67 8 75 8t75 -8l201 232l140 -58l-22 -305q56 -44 107 -107l305 22l58 -139l-232 -201q8 -67 8 -76q0 -8 -8 -75l232 -201l-58 -140l-305 22q-44 -56 -107 -107 l22 -305l-139 -58l-201 232q-67 -8 -76 -8q-8 0 -75 8l-201 -232l-139 58l21 305q-56 44 -107 107l-305 -22zM768 1024q0 -106 75 -181t181 -75t181 75t75 181t-75 181t-181 75t-181 -75t-75 -181z" />
<glyph unicode="" d="M256 1024q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM512 1024q0 -212 150 -362t362 -150q135 0 259 72l-699 699q-72 -126 -72 -259zM765 1464l699 -699 q72 123 72 259q0 212 -150 362t-362 150q-136 0 -259 -72z" />
<glyph unicode="" d="M256 1664v128h384v-256h1152l-256 -640h-896v-128h896v-128h-1024v1024h-256zM512 384q0 53 37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5t-37.5 -90.5t-90.5 -37.5t-90.5 37.5t-37.5 90.5zM1280 384q0 53 37.5 90.5t90.5 37.5t90.5 -37.5t37.5 -90.5t-37.5 -90.5 t-90.5 -37.5t-90.5 37.5t-37.5 90.5z" />
<glyph unicode="" d="M512 384v1280h384v-1280h-384zM1152 384v1280h384v-1280h-384z" />
<glyph unicode="" d="M512 512v1024h1024v-1024h-1024z" />
<glyph unicode="" d="M256 384v1280h384v-1280h-384zM768 1024l1024 640v-1280z" />
<glyph unicode="" d="M256 384v1280l1024 -640zM1408 384v1280h384v-1280h-384z" />
<glyph unicode="" d="M512 384v1280l1024 -640z" />
<glyph unicode="" d="M256 256v1536q0 106 75 181t181 75h1024q106 0 181 -75t75 -181v-1536q0 -106 -75 -181t-181 -75h-1024q-106 0 -181 75t-75 181zM512 512h1024v1280h-1024v-1280zM896 256q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5 t-37.5 -90.5z" />
<glyph unicode="" d="M128 1024v256h512v128l384 -256l-384 -256v128h-512zM256 256v640h256v-384h1024v1280h-1024v-384h-256v384q0 106 75 181t181 75h1024q106 0 181 -75t75 -181v-1536q0 -106 -75 -181t-181 -75h-1024q-106 0 -181 75t-75 181zM896 256q0 -53 37.5 -90.5t90.5 -37.5 t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M256 1024q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM896 1408q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5 t-37.5 -90.5zM928 512h192v640h-192v-640z" />
<glyph unicode="" d="M256 1024q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM883 1536l51 -640h179l52 640h-282zM896 640q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5 t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M256 1024q0 209 103 385.5t279.5 279.5t385.5 103t385.5 -103t279.5 -279.5t103 -385.5t-103 -385.5t-279.5 -279.5t-385.5 -103t-385.5 103t-279.5 279.5t-103 385.5zM720 1442l92 -180q134 71 234 71q38 0 65 -16q26 -17 26 -44q0 -35 -24 -63q-24 -27 -77 -61 q-68 -42 -95 -87q-26 -44 -26 -109v-57h204v34q0 29 17 49q18 21 87 66q83 53 120 111t37 139q0 111 -84 176q-85 65 -232 65q-180 0 -344 -94zM896 640q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M128 384v1280l768 -480v480l1024 -640l-1024 -640v480z" />
<glyph unicode="" d="M128 1024l1024 -640v480l768 -480v1280l-768 -480v480z" />
<glyph unicode="" d="M256 1280h128l86 256h340l86 -256l-256 -768h-128zM533 1280h214l-43 128h-128zM768 512l256 768h128l86 256h340l86 -256h128l-256 -768h-768zM1301 1280h214l-43 128h-128z" />
<glyph unicode="" d="M256 1261q8 -158 120 -264l648 -613l648 613q112 106 120 264t-93 276t-251.5 126.5t-262.5 -97.5l-161 -153l-161 153q-112 106 -262.5 97.5t-251.5 -126.5t-93 -276z" />
<glyph unicode="" d="M102 1024l304 -455l213 142l-209 313l209 313l-213 142zM772 543l248 -62l256 1024l-248 62zM1430 711l213 -142l303 455l-303 455l-213 -142l208 -313z" />
<glyph unicode="" d="M0 512v704l768 -384l256 128v-448h-1024zM0 1408v128h1536v-128l-768 -384zM1152 384v640q0 53 37.5 90.5t90.5 37.5h640q53 0 90.5 -37.5t37.5 -90.5v-640q0 -53 -37.5 -90.5t-90.5 -37.5h-640q-53 0 -90.5 37.5t-37.5 90.5zM1280 640h256v-256h128v256h256v128h-256 v256h-128v-256h-256v-128z" />
<glyph unicode="" d="M0 512v704l768 -384l256 128v-448h-1024zM0 1408v128h1536v-128l-768 -384zM1152 384v640q0 53 37.5 90.5t90.5 37.5h640q53 0 90.5 -37.5t37.5 -90.5v-640q0 -53 -37.5 -90.5t-90.5 -37.5h-640q-53 0 -90.5 37.5t-37.5 90.5zM1280 640h640v128h-640v-128z" />
<glyph unicode="" d="M0 512v704l768 -384l256 128v-448h-1024zM0 1408v128h1536v-128l-768 -384zM1152 384v640q0 53 37.5 90.5t90.5 37.5h640q53 0 90.5 -37.5t37.5 -90.5v-640q0 -53 -37.5 -90.5t-90.5 -37.5h-640q-53 0 -90.5 37.5t-37.5 90.5zM1260 656l272 -272l452 453l-90 90 l-362 -362l-181 181z" />
<glyph unicode="" d="M0 1024l640 640v-320l-320 -320l320 -320v-320zM512 1024l640 640v-384h256q212 0 362 -150t150 -362v-300l-150 150q-74 74 -168 112t-194 38h-256v-384z" />
<glyph unicode="" d="M384 1024l640 640v-384h256q212 0 362 -150t150 -362v-300l-150 150q-74 74 -168 112t-194 38h-256v-384z" />
<glyph unicode="" d="M256 256v1536h256v-1536h-256zM640 896v768q35 0 63.5 13t54 32t56.5 38t85 32t125 13q70 0 125.5 -13t93 -32l75 -38t93 -32t125.5 -13h256v-768h-256q-70 0 -125.5 13t-93 32l-75 38t-93 32t-125.5 13q-71 0 -125 -13t-85 -32t-56.5 -38t-54 -32t-63.5 -13z" />
<glyph unicode="" d="M256 512v768h1536v-768h-256v384h-1024v-384h-256zM640 640v128h768v-128q0 -158 113 -271l112 -113h-768l-112 113q-113 113 -113 271zM640 1408h768v256h-768v-256z" />
<glyph unicode="" d="M384 384v640q0 53 37.5 90.5t90.5 37.5v128q0 212 150 362t362 150t362 -150t150 -362v-128q53 0 90.5 -37.5t37.5 -90.5v-640q0 -53 -37.5 -90.5t-90.5 -37.5h-1024q-53 0 -90.5 37.5t-37.5 90.5zM768 1152h512v128q0 106 -75 181t-181 75t-181 -75t-75 -181v-128z" />
<glyph unicode="" d="M512 512v1024h512q106 0 181 -75t75 -181q0 -87 -57 -159q83 -39 134 -117t51 -172q0 -133 -93.5 -226.5t-226.5 -93.5h-576zM768 640h192q80 0 136 56t56 136t-56 136t-136 56h-192v-384zM768 1152h128q53 0 90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5h-128v-256z" />
<glyph unicode="" d="M640 512l40 128h128l240 768h-128l40 128h448l-40 -128h-128l-240 -768h128l-40 -128h-448z" />
<glyph unicode="" d="M384 384v1280h1280v-1280h-1280zM512 512h1024v576l-128 192l-448 -672l-192 288zM640 1280q0 -53 37.5 -90.5t90.5 -37.5t90.5 37.5t37.5 90.5t-37.5 90.5t-90.5 37.5t-90.5 -37.5t-37.5 -90.5z" />
<glyph unicode="" d="M128 256v384l154 -154l230 154l-154 -230l154 -154h-384zM128 1408v384h384l-154 -154l154 -230l-230 154zM640 768v512h768v-512h-768zM1536 256l154 154l-154 230l230 -154l154 154v-384h-384zM1536 1408l154 230l-154 154h384v-384l-154 154z" />
<glyph unicode="" d="M128 0l960 960l960 -960h-1920z" />
<glyph unicode="" d="M0 128l960 960l-960 960v-1920z" />
<glyph unicode="" d="M128 2048l960 -960l960 960h-1920z" />
<glyph unicode="" d="M1088 1088l960 960v-1920z" />
</font>
</defs></svg> | 40,045 | Common Lisp | .l | 135 | 295.62963 | 1,727 | 0.709278 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 38807eaa1a92c10217f0073063ab812a627c64e67f1e0a50abb92e1ad6b2c3f3 | 2,611 | [
-1
] |
2,626 | anyword-hint.js | inaimathi_cl-notebook/static/js/addons/anyword-hint.js | (function() {
"use strict";
var WORD = /[\w$]+/, RANGE = 500;
CodeMirror.registerHelper("hint", "anyword", function(editor, options) {
var word = options && options.word || WORD;
var range = options && options.range || RANGE;
var cur = editor.getCursor(), curLine = editor.getLine(cur.line);
var start = cur.ch, end = start;
while (end < curLine.length && word.test(curLine.charAt(end))) ++end;
while (start && word.test(curLine.charAt(start - 1))) --start;
var curWord = start != end && curLine.slice(start, end);
var list = [], seen = {};
var re = new RegExp(word.source, "g");
for (var dir = -1; dir <= 1; dir += 2) {
var line = cur.line, endLine = Math.min(Math.max(line + dir * range, editor.firstLine()), editor.lastLine()) + dir;
for (; line != endLine; line += dir) {
var text = editor.getLine(line), m;
while (m = re.exec(text)) {
if (line == cur.line && m[0] === curWord) continue;
if ((!curWord || m[0].lastIndexOf(curWord, 0) == 0) && !Object.prototype.hasOwnProperty.call(seen, m[0])) {
seen[m[0]] = true;
list.push(m[0]);
}
}
}
}
return {list: list, from: CodeMirror.Pos(cur.line, start), to: CodeMirror.Pos(cur.line, end)};
});
})();
| 1,304 | Common Lisp | .ny | 29 | 38.62069 | 121 | 0.573899 | inaimathi/cl-notebook | 85 | 10 | 52 | AGPL-3.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 36ba8ba14f803bcdb7f20a6e748f735792350f4ad9c3560ab9f5da867949dc37 | 2,626 | [
-1
] |
2,627 | package.lisp | brown_swank-client/package.lisp | ;;;; Copyright 2011 Google Inc.
;;;; 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., 51 Franklin Street, Fifth Floor, Boston,
;;;; MA 02110-1301, USA.
;;;; Author: Robert Brown <[email protected]>
(in-package #:common-lisp-user)
(defpackage #:swank-client
(:documentation "A client interface to Swank servers.")
(:use #:common-lisp)
(:import-from #:com.google.base
#:defconst
#:make-octet-vector
#:missing-argument
#:octet
#:string-to-utf8-octets
#:utf8-octets-to-string)
(:import-from #:bordeaux-threads
#:condition-notify
#:condition-wait
#:make-condition-variable
#:make-lock
#:make-thread
#:with-lock-held)
(:import-from #:usocket
#:socket
#:socket-close
#:socket-connect
#:socket-error
#:socket-stream
#:stream-usocket)
(:export #:swank-connection
#:slime-connect
#:slime-close
#:slime-eval
#:slime-eval-async
#:slime-migrate-evals
#:slime-network-error
#:slime-pending-evals-p
#:with-slime-connection))
| 1,929 | Common Lisp | .lisp | 48 | 30.979167 | 70 | 0.601067 | brown/swank-client | 82 | 7 | 0 | GPL-2.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 9f7c19cea585714a13f65d3f7cdf04cb111c340266d6bd467a52b6f7d4737b14 | 2,627 | [
-1
] |
2,628 | swank-client-test.lisp | brown_swank-client/swank-client-test.lisp | ;;;; Copyright 2011 Google Inc.
;;;; 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., 51 Franklin Street, Fifth Floor, Boston,
;;;; MA 02110-1301, USA.
;;;; Author: Robert Brown <[email protected]>
;;;; Swank client unit tests.
(in-package #:common-lisp-user)
(defpackage #:swank-client-test
(:documentation "Test code in the SWANK-CLIENT package.")
(:use #:common-lisp
#:com.google.base
#:hu.dwim.stefil
#:swank-client)
(:export #:test-swank-client))
(in-package #:swank-client-test)
(defsuite (test-swank-client :in root-suite) ()
(run-child-tests))
(in-suite test-swank-client)
(defconst +server-count+ 4)
(defun create-swank-server ()
(setf swank:*configure-emacs-indentation* nil)
(swank:create-server :port 0))
(deftest no-connection ()
(signals swank-client:slime-network-error
(with-slime-connection (connection "localhost" 12345)
(slime-eval 42 connection))))
(deftest simple-eval ()
(with-slime-connection (connection "localhost" (create-swank-server))
(is (= (slime-eval 123 connection) 123))))
(deftest simple-eval-async ()
(with-slime-connection (connection "localhost" (create-swank-server))
(let ((result nil)
(result-lock (bordeaux-threads:make-lock "result lock")))
(slime-eval-async 123
connection
(lambda (x)
(bordeaux-threads:with-lock-held (result-lock)
(setf result x))))
(loop until (bordeaux-threads:with-lock-held (result-lock) result))
(is (= result 123)))))
(deftest several-connections ()
(let* ((server-ports (loop repeat +server-count+ collect (create-swank-server)))
(connections (loop for port in server-ports collect (slime-connect "localhost" port)))
(work (make-array +server-count+
:initial-contents (loop for i from 2 repeat +server-count+ collect i)))
(golden (map 'vector (lambda (x) (* x 2)) work)))
(unwind-protect
(let ((results (make-array +server-count+ :initial-element nil))
(results-lock (bordeaux-threads:make-lock "results lock")))
;; Synchronous
(loop for i below (length work)
for connection in connections
do (setf (aref results i) (slime-eval `(* 2 ,(aref work i)) connection)))
(is (equalp results golden))
;; Reset results.
(loop for i below (length results) do (setf (aref results i) nil))
;; Asynchronous
(loop for i below (length work)
for connection in connections
do (let ((index i))
(slime-eval-async `(* 2 ,(aref work i))
connection
(lambda (result)
(bordeaux-threads:with-lock-held (results-lock)
(setf (aref results index) result))))))
(loop while (bordeaux-threads:with-lock-held (results-lock) (some #'null results)))
(is (equalp results golden)))
(dolist (connection connections)
(slime-close connection)))))
(deftest non-ascii-characters ()
(flet ((create-string (code)
(concatenate 'string "hello " (string (code-char code)) " world")))
(with-slime-connection (connection "localhost" (create-swank-server))
(loop for code from 0 below 2000 by 100 do
(let ((string (create-string code)))
(is (string= (slime-eval string connection) string)))))))
| 4,262 | Common Lisp | .lisp | 85 | 40.635294 | 98 | 0.618269 | brown/swank-client | 82 | 7 | 0 | GPL-2.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 838928d8c08a9f6d56da1b93ac1d262a6ca46718c0c9c4cf03304cdce692b378 | 2,628 | [
-1
] |
2,629 | swank-client.lisp | brown_swank-client/swank-client.lisp | ;;;; Copyright 2011 Google Inc.
;;;; Copyright 2007, 2008, 2009 Helmut Eller, Tobias C. Rittweiler
;;;; Copyright 2004, 2005, 2006 Luke Gorrie, Helmut Eller
;;;; Copyright 2003 Eric Marsden, Luke Gorrie, Helmut Eller
;;;; 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., 51 Franklin Street, Fifth Floor, Boston,
;;;; MA 02110-1301, USA.
;;;; Author: Robert Brown <[email protected]>
;;;; Swank client
(in-package #:swank-client)
(deftype port () "A non-privileged TCP/IP port number." '(integer 1024 65535))
(defconst +abort+ (cons nil nil)
"Unique object used to signal that a computation was aborted on the server.")
(defvar *thread-offset* 0
"Counter used to assign each Swank connection a unique range of thread IDs.")
(defconst +maximum-thread-count+ 10000
"Maximum number of threads per Swank connection.")
(define-condition slime-network-error (error)
()
(:documentation "Network problem while evaluating a form."))
(defclass swank-connection ()
((host-name :reader host-name
:type string
:initarg :host-name
:initform (missing-argument)
:documentation "Name of the host where the Swank server is running.")
(port :reader port
:type port
:initarg :port
:initform (missing-argument)
:documentation "Port number used to make a Swank server connection.")
(usocket :reader usocket
:type stream-usocket
:initarg :usocket
:initform (missing-argument)
:documentation "USOCKET used to communicate with the Swank server.")
(thread-offset :reader thread-offset
:initform (incf *thread-offset* +maximum-thread-count+)
:type (integer 0 *)
:documentation
"All threads for this connection are presented to Emacs with this value added to
their thread ID.")
(continuation-counter :accessor continuation-counter
:initform 0
:type (integer 0 *)
:documentation "Used to associate an ID with each evaluated form.")
(rex-continuations :accessor rex-continuations
:initform '()
:type list
:documentation
"List of (ID, continuation) pairs, one for each evaluation in progress. Used to
match each returned value with the continuation it should be passed to.")
(state :accessor state
:initform :alive
:type (member :alive :closing :dead)
:documentation "State of the connection, either :ALIVE, :CLOSING, or :DEAD.")
(connection-lock :reader connection-lock
:initform (make-lock)
:documentation
"Lock protecting slots of this connection that are read and written by
concurrently running threads."))
(:documentation "A connection to a Swank server."))
(defvar *open-connections* '() "List of all open Swank connections.")
(defvar *connections-lock* (make-lock) "Lock protecting *OPEN-CONNECTIONS*.")
(defun add-open-connection (connection)
"Adds CONNECTION to the set of open Swank connections."
(with-lock-held (*connections-lock*)
(push connection *open-connections*)))
(defun remove-open-connection (connection)
"Removes CONNECTION from the set of open Swank connections."
(with-lock-held (*connections-lock*)
(setf *open-connections* (remove connection *open-connections*))))
(defun find-connection-for-thread-id (thread-id)
"Returns the open Swank connection associated with THREAD-ID."
(with-lock-held (*connections-lock*)
(let ((thread-offset (* (floor thread-id +maximum-thread-count+) +maximum-thread-count+)))
(find thread-offset *open-connections* :key #'thread-offset))))
(defun server-thread-id (thread-id)
"Maps the THREAD-ID in an event that must be forwarded to the thread ID known
by the remote Lisp to which it will be sent."
(mod thread-id +maximum-thread-count+))
(defun forward-event-to-worker (form package thread-id id)
"Determines whether an :emacs-rex event is intended for a remote worker Lisp
and if so forwards it. When forwarding is successful, FORWARD-EVENT-TO-WORKER
returns T; otherwise, it returns NIL.
FORWARD-EVENT-TO-WORKER is called by code in Swank Crew's patch to Slime's
swank.lisp source file. The forwarding it performs is used by Swank Crew
to handle debugging of conditions signalled on remote worker Lisps. See
swank.lisp-patch in https://github.com/brown/swank-crew."
(let ((connection (find-connection-for-thread-id thread-id)))
(when connection
(let ((remote-thread-id (server-thread-id thread-id)))
(slime-send `(:emacs-rex ,form ,package ,remote-thread-id ,id) connection))
t)))
(defvar *io-package*
(let ((package (make-package :swank-client-io-package :use '())))
(import '(nil t quote) package)
package)
"A package used by the Swank client code when printing s-expressions, so that
symbols in the printed output contain their package names.")
(defun slime-net-encode-length (n)
"Encodes an integer as a 6-character, 24-bit hex string."
(format nil "~6,'0,X" n))
(defun slime-net-send (sexp usocket)
"Sends SEXP to a Swank server over USOCKET. The s-expression is read and
evaluated by the remote Lisp."
(let* ((payload (with-standard-io-syntax
(let ((*package* *io-package*))
(prin1-to-string sexp))))
(utf8-payload (string-to-utf8-octets payload))
;; The payload always includes one more octet, an encoded newline character at the end.
(payload-length (1+ (length utf8-payload)))
(utf8-length (string-to-utf8-octets (slime-net-encode-length payload-length)))
;; The encoded length always takes 6 octets.
(message (make-octet-vector (+ (length utf8-length) payload-length))))
(replace message utf8-length)
(replace message utf8-payload :start1 (length utf8-length))
(setf (aref message (1- (length message))) (char-code #\Newline))
;; We use IGNORE-ERRORS here to catch SB-INT:CLOSED-STREAM-ERROR on SBCL and any other
;; system-dependent network or stream errors.
(let ((success (ignore-errors (write-sequence message (socket-stream usocket)))))
(unless success (error 'slime-network-error)))))
(defun slime-send (sexp connection)
"Sends SEXP to a Swank server using CONNECTION. Signals SLIME-NETWORK-ERROR
if there are communications problems."
(let ((usocket (usocket connection)))
(slime-net-send sexp usocket)
;; We use IGNORE-ERRORS here to catch SB-INT:CLOSED-STREAM-ERROR on SBCL and any other
;; system-dependent network or stream errors.
(let ((success nil))
(ignore-errors
(progn (force-output (socket-stream usocket))
(setf success t)))
(unless success (error 'slime-network-error))))
(values))
(defun slime-secret ()
"Finds the secret file in the user's home directory. Returns NIL if the file
doesn't exist; otherwise, returns the first line of the file."
(let ((secret-file (merge-pathnames (user-homedir-pathname) #p".slime-secret")))
(with-open-file (input secret-file :if-does-not-exist nil)
(when input (read-line input nil "")))))
(defun socket-keep-alive (socket)
"Configures TCP keep alive packets for SOCKET. The socket connection will be
considered dead if keep alive packets are lost."
(declare (ignorable socket))
#+allegro
(socket:set-socket-options socket :keepalive t)
#+ccl
(ccl::set-socket-options socket :keepalive t)
#+sbcl
(setf (sb-bsd-sockets:sockopt-keep-alive socket) t)
#+(and linux sbcl)
(setf (sb-bsd-sockets:sockopt-tcp-keepcnt socket) 1
(sb-bsd-sockets:sockopt-tcp-keepidle socket) 30
(sb-bsd-sockets:sockopt-tcp-keepintvl socket) 30))
(defun slime-net-connect (host-name port)
"Establishes a connection to the Swank server listening on PORT of HOST-NAME.
Returns a SWANK-CONNECTION when the connection attempt is successful.
Otherwise, returns NIL. May signal SLIME-NETWORK-ERROR if the user has a Slime
secret file and there are network problems sending its contents to the remote
Swank server."
(let ((usocket (handler-case (socket-connect host-name port :element-type 'octet)
(socket-error ()
(return-from slime-net-connect nil)))))
(socket-keep-alive (socket usocket))
(let ((connection
(make-instance 'swank-connection :host-name host-name :port port :usocket usocket))
(secret (slime-secret)))
(when secret (slime-send secret connection))
connection)))
(defmacro destructure-case (value &body patterns)
"Dispatches VALUE to one of PATTERNS. A cross between CASE and DESTRUCTURING-BIND.
The pattern syntax is: ((HEAD . ARGS) . BODY). The list of patterns is searched
for a HEAD that's EQ to the car of VALUE. If one is found, BODY is executed
with ARGS bound to the corresponding values in the CDR of VALUE."
(let ((operator (gensym "op-"))
(operands (gensym "rand-"))
(tmp (gensym "tmp-")))
`(let* ((,tmp ,value)
(,operator (car ,tmp))
(,operands (cdr ,tmp)))
(case ,operator
,@(mapcar (lambda (clause)
(if (eq (car clause) t)
`(t ,@(cdr clause))
(destructuring-bind ((op &rest rands) &rest body) clause
`(,op (destructuring-bind ,rands ,operands
. ,body)))))
patterns)
,@(if (eq (caar (last patterns)) t)
'()
`((t (error "destructure-case failed: ~S" ,tmp))))))))
(defun send-to-emacs (event)
"Sends EVENT to Emacs."
(swank::send (swank::mconn.control-thread (swank::default-connection)) event))
;;;; Protocol event handler (the guts)
;;; This is the protocol in all its glory. The input to this function is a protocol event that
;;; either originates within Emacs or arrived over the network from Lisp.
;;;
;;; Each event is a list beginning with a keyword and followed by arguments. The keyword identifies
;;; the type of event. Events originating from Emacs have names starting with :emacs- and events
;;; from Lisp don't.
(defun slime-dispatch-event (event connection)
"Handles EVENT for a Swank CONNECTION. Signals SLIME-NETWORK-ERROR if there
are communications problems."
(destructure-case event
((:emacs-rex form package-name thread continuation)
(let ((id nil))
(with-lock-held ((connection-lock connection))
(setf id (incf (continuation-counter connection)))
(push (list id continuation form package-name thread) (rex-continuations connection))
(when (eq (state connection) :dead) (error 'slime-network-error)))
(let ((name (format nil "swank sender for ~A/~D" (host-name connection) (port connection))))
(make-thread (lambda ()
;; Catch network errors so the Swank sender thread exits gracefully if
;; there are communications problems with the remote Lisp.
(handler-case
(slime-send `(:emacs-rex ,form ,package-name ,thread ,id) connection)
(slime-network-error ())))
:name name))))
((:return value id)
(let ((send-to-emacs t))
(with-lock-held ((connection-lock connection))
(let ((rec (assoc id (rex-continuations connection))))
(when rec
(setf send-to-emacs nil)
(setf (rex-continuations connection) (remove rec (rex-continuations connection)))
(funcall (second rec) value))))
;; The value returned is not for us. Forward it to Slime.
(when send-to-emacs
(force-output)
(send-to-emacs `(:return ,(swank::current-thread) ,value ,id)))))
;; When a remote computation signals a condition and control ends up in the debugger, Swank
;; sends these events back to pop up a Slime breakpoint window. Forward the events to Slime.
;; Modify the thread ID of each event to uniquely identify which remote Lisp generated it.
((:debug-activate thread level &optional select)
(incf thread (thread-offset connection))
(send-to-emacs `(:debug-activate ,thread ,level ,select)))
((:debug thread level condition restarts frames continuations)
(incf thread (thread-offset connection))
(send-to-emacs `(:debug ,thread ,level ,condition ,restarts ,frames ,continuations)))
((:debug-return thread level stepping)
(incf thread (thread-offset connection))
(send-to-emacs `(:debug-return ,thread ,level ,stepping)))
((:emacs-interrupt thread)
(slime-send `(:emacs-interrupt ,thread) connection))
((:channel-send id msg)
(print (list :channel-send id msg)))
((:emacs-channel-send id msg)
(slime-send `(:emacs-channel-send ,id ,msg) connection))
((:read-from-minibuffer thread tag prompt initial-value)
(print (list :read-from-minibuffer thread tag prompt initial-value)))
((:y-or-n-p thread tag question)
(print (list :y-or-n-p thread tag question)))
((:emacs-return-string thread tag string)
(slime-send `(:emacs-return-string ,thread ,tag ,string) connection))
;; Ignore remote Lisp feature changes.
((:new-features features)
(declare (ignore features)))
;; Ignore remote Lisp indentation updates.
((:indentation-update info)
(declare (ignore info)))
((:eval-no-wait form)
(print (list :eval-no-wait form)))
((:eval thread tag form-string)
(print (list :eval thread tag form-string)))
((:ed-rpc-no-wait function-name &rest args)
(print (list :ed-rpc-no-wait function-name '&rest args)))
((:ed-rpc thread tag function-name &rest args)
(print (list :ed-rpc thread tag function-name '&rest args)))
((:emacs-return thread tag value)
(slime-send `(:emacs-return ,thread ,tag ,value) connection))
((:ed what)
(print (list :ed what)))
((:inspect what wait-thread wait-tag)
(print (list :inspect what wait-thread wait-tag)))
((:background-message message)
(print (list :background-message message)))
((:debug-condition thread message)
(assert thread)
(print (list :debug-condition thread message)))
((:ping thread tag)
(slime-send `(:emacs-pong ,thread ,tag) connection))
((:reader-error packet condition)
(print (list :reader-error packet condition))
(error "Invalid protocol message"))
((:invalid-rpc id message)
(setf (rex-continuations connection) (remove id (rex-continuations connection) :key #'car))
(error "Invalid rpc: ~S" message))
((:emacs-skipped-packet packet)
(print (list :emacs-skipped-packet packet)))
(t
(error "Unknown event received: ~S" event))))
(defun slime-net-read (connection)
"Reads a Swank message from a network CONNECTION to a Swank server. Returns
the Swank event or NIL, if there was a problem reading data."
(flet ((safe-read-sequence (buffer stream)
;; We use IGNORE-ERRORS here to catch SB-INT:CLOSED-STREAM-ERROR on SBCL and any other
;; system-dependent network or stream errors.
(let ((result (ignore-errors (read-sequence buffer stream))))
(unless result (return-from slime-net-read))
result)))
(let ((stream (socket-stream (usocket connection)))
(length-buffer (make-octet-vector 6)))
(if (/= (safe-read-sequence length-buffer stream) 6)
nil
(let* ((length-string (utf8-octets-to-string length-buffer))
(length (parse-integer length-string :radix 16))
(message-buffer (make-octet-vector length)))
(if (/= (safe-read-sequence message-buffer stream) length)
nil
(let ((message (utf8-octets-to-string message-buffer)))
(with-standard-io-syntax
(let ((*package* *io-package*))
(read-from-string message))))))))))
(defmacro slime-rex ((&rest saved-vars) (sexp connection) &body continuations)
"(slime-rex (VAR ...) (SEXP CONNECTION) CLAUSES ...)
Remote EXecute SEXP.
VARs are a list of saved variables visible in the other forms. Each VAR is
either a symbol or a list (VAR INIT-VALUE).
SEXP is evaluated and the PRIN1-ed version is sent over CONNECTION to a remote
Lisp.
CLAUSES is a list of patterns with same syntax as `destructure-case'. The
result of the evaluation of SEXP is dispatched on CLAUSES. The result is either
a sexp of the form (:ok VALUE) or (:abort CONDITION). CLAUSES is executed
asynchronously.
Signals SLIME-NETWORK-ERROR when there are network problems sending SEXP."
(let ((result (gensym)))
`(let ,(loop for var in saved-vars
collect (etypecase var
(symbol (list var var))
(cons var)))
(slime-dispatch-event (list :emacs-rex
,sexp
"COMMON-LISP-USER"
t
(lambda (,result)
(destructure-case ,result ,@continuations)))
,connection))))
(defun slime-eval-async (sexp connection &optional continuation)
"Sends SEXP over CONNECTION to a Swank server for evaluation, then immediately
returns. Some time later, after the evaluation is finished, CONTINUATION is
called with the result as argument. Signals SLIME-NETWORK-ERROR when there are
network problems sending SEXP."
(slime-rex (continuation)
(sexp connection)
((:ok result)
(when continuation
(funcall continuation result)))
((:abort condition)
(when continuation
(funcall continuation (cons +abort+ condition)))))
(values))
(defun slime-eval (sexp connection)
"Sends SEXP over CONNECTION to a Swank server for evaluation and waits for the
result. When the result is received, it is returned. Signals
SLIME-NETWORK-ERROR when there are network problems sending SEXP."
(let* ((done-lock (make-lock "slime eval"))
(done (make-condition-variable))
(result-available nil)
(result nil))
;; See the Bordeaux Threads documentation for a description of the locking pattern used here.
(slime-eval-async sexp
connection
(lambda (x)
(with-lock-held (done-lock)
(setf result x
result-available t)
(condition-notify done))))
(with-lock-held (done-lock)
;; Do not call CONDITION-WAIT if our result is already available, since we would wait forever
;; on the DONE condition variable, which has already been notified. Also, CONDITION-WAIT can
;; return spuriously before DONE has been notified, so wait again if our result is not yet
;; available.
(loop until result-available
do (condition-wait done done-lock)))
(when (and (consp result) (eq (car result) +abort+))
(error "Evaluation aborted on ~s." (cdr result)))
result))
(defun slime-pending-evals-p (connection)
"Returns T if there are outstanding evaluations pending on CONNECTION;
otherwise, returns NIL."
(not (null (rex-continuations connection))))
(defun slime-migrate-evals (old-connection new-connection)
"Evaluates on NEW-CONNECTION all the work pending on a closed OLD-CONNECTION.
Signals SLIME-NETWORK-ERROR when there are network problems."
(dolist (rec (rex-continuations old-connection))
(destructuring-bind (id continuation form package-name thread)
rec
(declare (ignore id))
(slime-dispatch-event `(:emacs-rex ,form ,package-name ,thread ,continuation)
new-connection)))
(setf (rex-continuations old-connection) '()))
(defun slime-dispatch-events (connection connection-closed-hook)
"Reads and dispatches incoming events for a CONNECTION to a Swank server. If
provided, function CONNECTION-CLOSED-HOOK is called when CONNECTION is closed."
(flet ((close-connection ()
(with-lock-held ((connection-lock connection))
(socket-close (usocket connection))
(setf (state connection) :dead))
(remove-open-connection connection)
(when connection-closed-hook (funcall connection-closed-hook))))
(loop (let ((event (slime-net-read connection)))
(unless event
(close-connection)
(return-from slime-dispatch-events))
;; TODO(brown): Verify that this call to SLIME-DISPATCH-EVENTS will never signal
;; SLIME-NETWORK-ERROR.
(slime-dispatch-event event connection))
(let ((state nil))
(with-lock-held ((connection-lock connection))
(setf state (state connection)))
(ecase state
(:alive)
(:closing
(close-connection)
(return-from slime-dispatch-events))
(:dead
(return-from slime-dispatch-events)))))))
(defun slime-connect (host-name port &optional connection-closed-hook)
"Connects to the Swank server running on HOST-NAME that is listening on PORT.
Returns a SWANK-CONNECTION if the connection attempt is successful. Otherwise,
returns NIL. May signal SLIME-NETWORK-ERROR if the user has a Slime secret file
and there are network problems sending its contents to the remote Swank server.
If provided, function CONNECTION-CLOSED-HOOK is called when the connection is
closed."
(let ((connection (slime-net-connect host-name port)))
(when connection
(add-open-connection connection)
;; Create a thread to handle incoming events from the remote Lisp.
(let ((name (format nil "swank dispatcher for ~A/~D" host-name port)))
(make-thread (lambda ()
(slime-dispatch-events connection connection-closed-hook))
:name name)))
connection))
(defun slime-close (connection)
"Closes CONNECTION to a Swank server."
(with-lock-held ((connection-lock connection))
(setf (state connection) :closing))
(slime-eval-async nil connection)
(values))
(defmacro with-slime-connection ((variable host-name port &optional connection-closed-hook)
&body body)
"Wraps BODY in a LET form where VARIABLE is bound to the value returned by
(SLIME-CONNECT HOST-NAME PORT CONNECTION-CLOSED-HOOK). Arranges for the Swank
connection to be closed when control exits BODY."
`(let ((,variable (slime-connect ,host-name ,port ,connection-closed-hook)))
(unless ,variable (error 'slime-network-error))
(unwind-protect
(progn ,@body)
(slime-close ,variable))))
| 23,545 | Common Lisp | .lisp | 460 | 43.521739 | 99 | 0.667491 | brown/swank-client | 82 | 7 | 0 | GPL-2.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 3ac2fd474e8754404af5628e0efde489c7e0d6d0ab8a474213fd209188de18d8 | 2,629 | [
-1
] |
2,630 | swank-client.asd | brown_swank-client/swank-client.asd | ;;;; Copyright 2011 Google Inc.
;;;; 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., 51 Franklin Street, Fifth Floor, Boston,
;;;; MA 02110-1301, USA.
;;;; Author: Robert Brown <[email protected]>
(defsystem swank-client
:name "Swank Client"
:description "Client side of the Swank protocol."
:long-description "An implementation of the client side of Slime's Swank debugging protocol."
:version "1.7"
:author "Robert Brown <[email protected]>"
:license "GPL version 2. See the copyright messages in individual files."
:depends-on (bordeaux-threads
com.google.base
swank
usocket)
:in-order-to ((test-op (test-op swank-client/test)))
:components
((:file "package")
(:file "swank-client" :depends-on ("package"))))
(defsystem swank-client/test
:name "Swank Client test"
:description "Test code for package SWANK-CLIENT."
:version "1.7"
:author "Robert Brown <[email protected]>"
:license "GPL version 2. See the copyright messages in individual files."
:depends-on (hu.dwim.stefil swank-client)
:components
((:file "swank-client-test")))
(defmethod perform ((operation test-op) (component (eql (find-system 'swank-client/test))))
(symbol-call 'swank-client-test 'test-swank-client))
| 1,911 | Common Lisp | .asd | 40 | 44.45 | 95 | 0.722103 | brown/swank-client | 82 | 7 | 0 | GPL-2.0 | 9/19/2024, 11:25:43 AM (Europe/Amsterdam) | 24aa0305e3ee81514ded425062fdcdc568c6d865d41ff54e7012af2c78e7d4f2 | 2,630 | [
-1
] |
2,653 | package.lisp | phantomics_seed/package.lisp | ;;;; package.lisp
(defpackage #:seed
(:export #:contact-open #:contact-close)
(:use #:cl #:seed.contact #:seed.generate #:seed.platform-model.router.base))
| 161 | Common Lisp | .lisp | 4 | 38 | 79 | 0.698718 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | a5b91a84b340e603e0cd9cbbeca46a9e45ab93b176e97f020f247d71a9c80ded | 2,653 | [
-1
] |
2,654 | install-seed.lisp | phantomics_seed/install-seed.lisp | ;;;; install-seed.lisp
;;; A discrete program to install Seed. If dependencies aren't met, it fails and gives instructions to remedy.
(asdf:load-system 'uiop)
(defpackage #:seed.ui-model.html
(:export #:qualify-build)
(:use #:cl))
(load "./seed.ui-model.html/qualify-build.lisp")
(use-package 'seed.ui-model.html)
(if (not (probe-file #P"~/quicklisp"))
(princ (format nil "~%~%Seed installation failed.~%~%I couldn't find a /quicklisp directory in your home directory; please install Quicklisp. See https://www.quicklisp.org/beta/ for instructions on setting up Quicklisp.~%"))
(let ((success-message (format nil "~%~%Congratulations, Seed is installed and ready to use. ~%~%If you would like to automatically load Seed whenever you load your Common Lisp REPL, please add the following line to your Common Lisp implementation's init file:~%~%(asdf:load-system 'seed)~%~%For example, for SBCL this file is usually located at ~~/.sbclrc.~%~%If you would like Seed to automatically open its Web interface whenever you load your REPL, you should add both of these lines to your init file:~%~%(asdf:load-system 'seed)~%(seed:contact-open)~%~%If you wish to close the Web connection, you can do so by entering (seed:contact-close), and reopen it by entering (seed:contact-open) again.~%~%")))
(qualify-build
((if (not (probe-file #P"~/quicklisp/local-projects/seed"))
;; (multiple-value-bind (1st 2nd error-code)
;; (uiop:run-program (format nil "ln -s \"~a\" ~~/quicklisp/local-projects/seed"
;; (namestring (probe-file "./")))
;; :ignore-error-status t)
;; (declare (ignore 1st 2nd))
;; (if (not (= 0 error-code))
;; (princ (format nil "~%~%Seed installation failed.~%~%I couldn't create a link to this directory in the ~~/quicklisp/local-projects directory. This is needed in order to fetch Seed's dependencies using Quicklisp. Please check the permissions of your ~~/quicklisp and ~~/quicklisp/local-projects folders.~%~%"))
;; (progn (ql:quickload 'seed)
;; (princ success-message))))
(princ (format nil "~%~%Seed installation failed.~%~%I couldn't find Seed's directory in the ~~/quicklisp/local-projects directory. This is needed in order to fetch Seed's dependencies using Quicklisp. Please either copy the Seed directory into ~~/quicklisp/local-projects or create a symlink called ~~/quicklisp/local-projects/seed from that directory to the directory where Seed is located.~%~%"))
(progn (ql:quickload 'seed)
(princ success-message))))
("Seed installation failed."))))
(exit)
| 2,614 | Common Lisp | .lisp | 27 | 91.962963 | 712 | 0.702136 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 638ff64eafe65f38192665b132277bb2d5bf348eee5d38c2fc1534c6204f6a13 | 2,654 | [
-1
] |
2,655 | seed.lisp | phantomics_seed/seed.lisp | ;;;; seed.lisp
(in-package #:seed)
;; the routes below are examples, routing will be fully implemented later
(router base
(grammar-check :host "https://grammar-service.seed"
:system :grammar-check)
(spell-check :host "https://spelling-service.seed"
:system :spell-check))
(let ((contact-list nil))
(contact-create-in contact-list main-contact :port 8055 :root "./")
(defun contact-open ()
(contact-open-in contact-list))
(defun contact-close ()
(contact-close-in contact-list)))
| 516 | Common Lisp | .lisp | 14 | 33.214286 | 73 | 0.702213 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 654e93eae3eb9cad78353c354ea98458057c6fe26af53f0a3bcb2cd946609aa7 | 2,655 | [
-1
] |
2,656 | form.mode-shape-graph.lisp | phantomics_seed/seed.ui-spec.form.mode-shape-graph/form.mode-shape-graph.lisp | ;;;; form.mode-shape-graph.lisp
(in-package #:seed.ui-model.react)
(specify-components
graph-shape-view-mode
(graph-vector-renderer
(:get-initial-state
(lambda () (create point 0))
:container-element nil
:display-format
(lambda (graph index)
(let ((index (if index index 0)))
;; (cl :gr graph)
(chain graph (map (lambda (node)
(setf (@ node children) (@ node links)
(@ node index) index
index (1+ index))
node)))))
;; :permute
;; (lambda (input)
;; (if (and (@ window -drag-source)
;; (@ window -drop-target))
;; (let* ((over-data nil)
;; (collect-source (lambda (connect monitor)
;; (create connect-drag-source (chain connect (drag-source))
;; connect-drag-preview (chain connect (drag-preview))
;; is-dragging (chain monitor (is-dragging)))))
;; (collect-target (lambda (connect) (create connect-drop-target (chain connect (drop-target)))))
;; (item-source (create begin-drag (lambda (props) (cl 908 props))
;; end-drag (lambda (props monitor component)
;; (if (chain monitor (did-drop))
;; (let ((item (chain monitor (get-item)))
;; (drop-result (chain monitor (get-drop-result))))
;; (cl :endd item drop-result))))))
;; (item-target (create can-drop (lambda (props) t)
;; hover (lambda (props monitor) (setq over-data (@ props data data))))))
;; (funcall (chain window (-drop-target "node" item-target collect-target))
;; (funcall (chain window (-drag-source "node" item-source collect-source))
;; input)))))
:component-did-mount
(lambda ()
(let* ((self this)
(faux-container (chain self props (connect-faux-d-o-m "div" "chart")))
(main-display (chain window d3 (select faux-container)
(append "svg")
(attr "class" "vector-interface"))))
(chain self (make-display main-display (lambda (params) (chain subcomponents (effects params)))))))
:extend-model
(let ((last-update 0))
(lambda (original extension)
;;(cl :orr original extension (@ this props meta))
(let* ((self this)
(build-root (lambda (nodes)
(chain window d3 (hierarchy (create name "root" id "root"
children (chain self (display-format nodes))))))))
(if (not original)
(build-root extension)
(if (@ self props meta change)
(if (< last-update (@ self props updated))
(progn (setf last-update (@ self props updated))
(cond ((@ self props meta change node-added)
(let ((object (build-root (list (getprop extension
(1- (@ extension length)))))))
;; get the last node in the new extended node array
(chain original children (push (@ object children 0)))
original))
((@ self props meta change node-changed)
(let ((new-node nil))
(chain extension (map (lambda (node)
(if (= (@ node id)
(@ self props meta change node-id))
(setq new-node node)))))
(chain original children
(map (lambda (node index)
(if (= (@ node data id)
(@ self props meta change node-id))
(chain j-query
(extend t (getprop original "children"
index "data")
new-node))))))
original))
((@ self props meta change link-added)
(let ((new-link nil))
(chain extension
(map (lambda (node)
(if (= (@ node id) (@ self props meta change node-id))
(setq new-link
(build-root (list (getprop node "links"
(1- (@ node
links
length))))))))))
(chain original
(each (lambda (node)
(if (and (= (@ node data id)
(@ self props meta change node-id))
(not (@ node data to)))
(let ((this-link (chain j-query
(extend (create)
(@ new-link children 0)))))
(setf (@ this-link parent) node
(@ this-link depth) (1+ (@ node depth)))
(chain node children (push this-link)))))))
original))
((@ self props meta change link-connected)
(let ((new-link nil))
(chain extension
(map (lambda (node)
(if (= (@ node id) (@ self props meta change node-id))
(loop for link in (@ node links)
when (= (@ link id) (@ self props meta change link-id))
do (setq new-link (build-root (list link))))))))
(chain original
(each (lambda (node)
(if (and (= (@ node data id)
(@ self props meta change node-id))
(not (@ node data to)))
(let ((this-link (chain j-query
(extend (create)
(@ new-link children 0)))))
(setf (@ this-link parent) node
(@ this-link depth) (1+ (@ node depth)))
(if (@ node children)
(loop for lid from 0 to (1- (@ node children length))
when (= (getprop node "children" lid "data" "id")
(@ self props meta change link-id))
do (setf (getprop node "children" lid)
this-link))))))))
original))
((@ self props meta change object-removed)
(if (< 0 (@ self props meta change link-id length))
(chain original
(each (lambda (node)
(if (= (@ node data id)
(@ self props meta change node-id))
(setf (@ node children)
(chain node children
(filter (lambda (link)
(not (= (@ link data id)
(@ self props
meta change
link-id)))))))))))
(progn (setf (@ original children)
(chain original children
(filter (lambda (node)
(not (= (@ node data id)
(@ self props meta
change node-id)))))))
(chain original (each (lambda (node)
(if (and (@ node data to)
(= (@ self props meta
change node-id)
(@ node data to)))
(if (@ node children)
(setf (@ node _children) (list)
(@ node children) null))))))))
original)
(t original)))
original)
original)))))
:id-from-node-class
(lambda (class-string)
(let ((segments (chain class-string (split " ")))
(id ""))
(loop for seg in segments when (= "id-" (chain seg (substr 0 3)))
do (setq id (chain seg (substr 3))))
id))
:find-node-bounds
(lambda (item)
(let ((self this)
(rects (list)))
(chain item parent-node parent-node child-nodes
(map (lambda (g-item index)
(if (and (= "g" (@ g-item node-name)))
(chain g-item child-nodes
(map (lambda (c-item index)
;; (cl :gi g-item)
(if (and (= "g" (@ c-item node-name))
(= "glyph" (@ c-item props class-name)))
(let ((ext (create id (chain self
(id-from-node-class (@ g-item
props
class-name))))))
(chain rects
(push (chain j-query (extend (chain c-item
(get-bounding-client-rect))
ext)))))))))))))
rects))
:confirm-drop-target
(lambda (node callback)
(let* ((self this)
(point (list (@ window d3 event source-event client-x)
(@ window d3 event source-event client-y)))
(targets (chain self (find-node-bounds node)))
(destination-node-id (chain self (id-from-node-class (@ node parent-node props class-name))))
(target-link nil))
(loop for target in targets when (and (not target-link)
(<= (@ target left) (@ point 0) (@ target right))
(<= (@ target top) (@ point 1) (@ target bottom)))
do (setq target-link (@ target id)))
(let* ((segments (chain target-link (split "-")))
(node-id (@ segments 0))
(link-id (@ segments 1)))
;; (cl :drop node-id target-link)
(if link-id (callback node-id link-id destination-node-id)))))
:make-display
(let ((display-model nil))
(lambda (main-display callback)
;; (cl 9000 (@ this props width))
;; (cl :md (@ this props data))
(let* ((self this)
(root (let* ((model (chain self (extend-model display-model (@ self props data)))))
(if (not display-model)
(chain model (each (lambda (d)
(if (= 1 (@ d depth))
(if (@ d children)
(setf (@ d _children) (@ d children)
(@ d children) null)))))))
(setq display-model model)
model))
(from-link (lambda (parent id)
(let ((found nil))
(loop for item in (@ root children)
do (if (= id (@ item data id))
(setf found (chain j-query (extend (create) item))
(@ found data) (@ item data))))
(if (and (@ found _children) (not (= "untitled" (typeof (@ found _children)))))
(setf (@ found children) (@ found _children)
(@ found _children) nil))
(let ((downstream (chain found (copy))))
(setf (@ downstream parent) parent
(@ downstream depth) (1+ (@ parent depth))
(@ downstream _children) (chain downstream children
(map (lambda (item)
(setf (@ item depth)
(+ 2 (@ parent depth))
(@ item children) null)
item)))
(@ downstream children) null)
downstream))))
(params (create width (@ self container-element client-width)
section 32
link-indent 3
link-class "test-link"
duration 600
visualizer-logic (create node-has-children
(lambda (d)
(or (@ d data to)
(and (@ d children) (< 0 (@ d children length)))
(and (@ d _children) (< 0 (@ d _children length)))))
node-expanded (lambda (d) (@ d children)))
interface-actions (create expand-toggle-object
(lambda (d)
(if (not (@ d children))
(if (and (@ d data to) (not (@ d _children)))
(setf (@ d children)
(list (from-link d (@ d data to))))
(setf (@ d children) (@ d _children)
(@ d _children) null))
(setf (@ d _children) (@ d children)
(@ d children) null))
(funcall update d))
set-point-object
(lambda (d)
(chain self props (point-setter (1- (@ d index))
d))))))
(update (lambda (source)
(setq nodes (chain root (descendants))
depth-map (list))
(let ((index 0))
(chain root (each-before (lambda (n)
(setf (@ n x) (- (* index (@ params section))
(/ (@ params section) 2))
(@ n y) (+ 3 (* horizontal-interval
(1- (@ n depth))))
(@ n index) index
(getprop depth-map index) (@ n depth)
index (1+ index))))))
;; (cl :dm2 depth-map (@ self props point) root
;; (@ main-display _groups 0 0 component))
(setq node (chain main-display (select-all ".item")
(data nodes (lambda (d) (@ d id))))
node-enter (chain node (enter)
(append "svg:g")
(attr "class" (lambda (d)
(+ "obj-" (@ d index)
(if (@ d data to)
(+ " id-" (@ d parent data id)
"-" (@ d data id))
(+ " id-" (@ d data id) " "))
" item "
(if (@ d data type)
(+ " type-" (@ d data type) " ")
"")
(if (= (@ d index) (1+ (@ self props point)))
"point" ""))))
(attr "transform" (lambda (d)
(+ "translate(" (@ d y) "," (@ d x) ")")))
(attr "display" (lambda (d) (if (= 0 (@ d depth))
"none" "relative")))
(style "opacity" 1)))
(chain node-enter (transition)
(duration (@ params duration))
(attr "transform" (lambda (d) (if (<= 1 (@ d depth))
(+ "translate(" (@ d y) "," (@ d x) ")"))))
(style "opacity" 1))
(chain node (transition)
(duration (@ params duration))
(attr "transform" (lambda (d) (if (<= 1 (@ d depth))
(+ "translate(" (@ d y) "," (@ d x) ")"))))
(style "opacity" 1))
(chain node (exit) (style "opacity" (lambda (d) (if (= 1 (@ d depth)) 0 1)))
(remove))
;; (chain node (exit) (transition)
;; (duration (@ params duration))
;; (attr "transform" (lambda (d)
;; (if (< 1 (@ d depth))
;; (+ "translate(" (@ source y) "," (@ source x) ")"))))
;; (style "opacity" 0)
;; (remove))
(setq link (chain main-display (select-all "path.link")
(data (chain root (links))
(lambda (d) (@ d target id)))))
(chain link (enter)
(insert "path" "g")
(attr "class" "link")
(transition)
(duration (@ params duration))
(attr "d" (lambda (d) (if (= 0 (@ d source depth))
"" (funcall diagonal d)))))
;; (chain link (transition)
;; (duration (@ params duration))
;; (attr "d" diagonal))
;; (chain link (exit) (transition)
;; (duration (@ params duration))
;; (attr "d" (lambda (d) (let ((o (create x (@ d source x) y (@ d source y))))
;; (diagonal (create source o target o)))))
;; (remove))
(chain link (exit) (remove))
(chain root (each (lambda (d) (setf (@ d x0) (@ d x)
(@ d y0) (@ d y)))))
;; (let ((gg (chain main-display (select-all "g.glyph"))))
;; (cl :gg gg
;; (chain gg (enter))
;; (chain gg (enter) (node))))
(if callback (funcall callback (create node node node-enter node-enter params params)))
(let* ((drag-handler (chain window d3 (drag)
(on "end"
(lambda ()
(chain self
(confirm-drop-target this
(@ self
props
link-connector))))))))
;; (cl :sa g-select (@ g-select _groups 0 0))
;; (if (@ g-select _groups 1)
;; (chain g-select _groups 1 (map (lambda (item index)
;; ;;(chain self props (connect-drag-source item))
;; (if (@ item component)
;; (cl :rect (chain item ;;component
;; (get-bounding-client-rect))))
;; ))))
(drag-handler (chain main-display (select-all ".glyph"))))
(chain self props (animate-faux-d-o-m (@ params duration)))))
(diagonal (chain window d3 (link-horizontal)
(x (lambda (d) (@ d y)))
(y (lambda (d) (@ d x)))))
(max-depth 5)
(horizontal-interval (/ (* 0.6 (@ params width)) max-depth)))
(setf (@ this updated)
(@ this props updated))
(funcall update root)
))))
(let ((self this))
(panic:jsl (:div :class-name "display-holder-inner"
:ref (lambda (ref) (if (not (@ self container-element))
(setf (@ self container-element)
ref)))
(@ self props chart)))))
(graph-shape-view
(:get-initial-state
(lambda ()
(let ((self this))
;; (chain console (log :gshape (@ this props)))
(chain j-query (extend (create point 0
content (create)
point-object (@ this props data data 0)
point-parent nil
meta (chain j-query (extend t (create max-depth 0
confirmed-value nil
invert-axis (list false true))
(@ this props data meta))))
(chain this (initialize (@ this props)))))))
:vector-renderer nil
:subordinate-space (list)
:updated 0
:set-point
(lambda (index object)
(let* ((self this)
(point-element (j-query (+ "#branch-" (@ self props context index)
"-" (@ self props data id)
" .vector-interface .item.obj-" (1+ index)))))
(chain (j-query (+ "#branch-" (@ self props context index)
"-" (@ self props data id)
" .vector-interface .item"))
(remove-class "point"))
(chain point-element (add-class "point"))
(let ((node-id nil))
(chain point-element 0 class-name base-val (split " ")
(map (lambda (string)
(if (= "id-" (chain string (substr 0 3)))
(setq node-id (chain string (substr 3)))))))
(chain self state context methods (grow #() (create set-point true node-id node-id)))
(chain self (set-state (create point index point-object (if object (@ object data))
point-parent (if (and object (@ object data to) (@ object parent))
(@ object parent data) nil)))))))
:initialize
(lambda (props)
(let* ((self this)
(state (funcall inherit self props
(lambda (d) (chain j-query (extend (@ props data) (@ d data))))
(lambda (pd) (@ pd data data)))))
(if (@ self props context set-interaction)
(progn (chain self props context
(set-interaction "addGraphNode"
(lambda () (chain self state context methods
(grow #() (create add-node true
object-type "__option"
object-meta (create title "Untitled"
about "")))))))
(chain self props context
(set-interaction "addGraphLink"
(lambda () (chain self state context methods
(grow #() (create add-link true
node-id
(@ self state point-object id)
object-meta (create title "Untitled"
about "")))))))
(chain self props context
(set-interaction "removeGraphObject"
(lambda () (chain self state context methods
(grow #() (create link-id
(@ self state point-object id)
node-id
(if (@ self state point-parent)
(@ self state point-parent id))
remove-object true))))))))
state))
:container-element nil
:element-specs #()
:modulate-methods
(lambda (methods)
(let* ((self this)
(to-grow (if (@ self props context parent-system)
(chain methods (in-context-grow (@ self props context parent-system)))
(@ methods grow))))
(chain j-query
(extend (create ;;set-delta (lambda (value) (extend-state point-attrs (create delta value)))
set-point (lambda (datum) (chain self (set-point (@ datum index))))
delete-point (lambda (point) (chain self (delete-point point))))
methods
(create grow
(lambda (data meta alternate-branch)
(let ((space (let ((new-space (chain j-query (extend #() (@ self state space)))))
new-space)))
(to-grow (if (= "undefined" (typeof alternate-branch))
(@ self state data id)
alternate-branch)
;; TODO: it may be desirable to add certain metadata to
;; the meta for each grow request, that's what the
;; derive-metadata function below may later be used for
space meta)))
grow-branch
(lambda (space meta callback)
(chain methods (grow (@ self state data id)
space meta callback))))))))
:set-confirmed-value
(lambda (value)
(chain this (set-state (create confirmed-value value))))
:build-sheet-heading
(lambda (data)
(let ((heading (list (panic:jsl (:th :key "a0")))))
(loop for index from 0 to (1- (@ data 0 length))
do (chain heading (push (panic:jsl (:th :key (+ "sheet-header-" index)
(chain -string (from-char-code (+ 65 index))))))))
heading))
;; :interactions
;; (create add-graph-node
;; (create click (lambda (self datum)
;; (cl :add-node))
;; trigger-primary (lambda (self datum) (cl :add-node2))
;; trigger-secondary (lambda (self datum) (cl :add-node3))))
:move
(lambda (vector)
(let* ((self this)
(new-point (max 0 (+ (- (@ vector 1))
(@ vector 0) (@ self state point)))))
;;(cl vector (@ self state point) new-point)
(chain self (set-point new-point))))
:connect-link
(lambda (node-id link-id destination-node-id)
;; (cl :to-target node-id link-id destination-node-id)
(let ((self this))
;; (cl :st (@ self state)
;; (@ self props))
(chain self state context methods
(grow #()
(create connect-link true
node-id node-id
link-id link-id
destination-node-id destination-node-id)))))
:should-component-update
(lambda (next-props next-state)
;;(cl :nxp next-props (@ this state) (@ this updated))
;; (or (not (@ this state data))
;; (not (@ next-props current)))
(or (not (= (@ this updated) (@ next-props updated)))
(not (@ next-state context current))))
:component-will-receive-props
(lambda (next-props)
(defvar self this)
(setf (@ self updated)
(@ next-props updated))
(let ((new-state (chain this (initialize next-props))))
(if (@ self state context is-point)
(setf (@ new-state action-registered)
(@ next-props action)))
(chain this (set-state new-state)))
;; (cl 919 next-props)
;; (cl 919)
(if (= 0 (@ self subordinate-space length))
(setf (@ self subordinate-space)
(@ new-state space)))
(handle-actions
(@ next-props action) (@ self state) next-props
:actions-any-branch
((set-branch-by-id
(if (= (@ params id) (@ self props data id))
(chain self props context methods (set-trace (@ self props context path))))))
:actions-point-and-focus
((move (chain self (move (@ params vector))))
;; (delete-point
;; (if (not (= true (@ next-props data meta locked)))
;; (chain self state context methods (grow-point nil (create)))))
;; (record
;; (if (@ self props context clipboard-id)
;; (chain self state context methods (grow-point (create)
;; (create vector (@ params vector)
;; point (@ self state point)
;; branch (@ self state data id))
;; (@ self props context clipboard-id)))))
(trigger-primary (cl :aaa))
(trigger-secondary (cl :bbb))
(trigger-anti
(chain self state context methods (set-mode "move")))
(commit
(if (not (= true (@ next-props data meta locked)))
(chain self state context methods (grow-branch (@ self state space)
(create save true)))))))
)
;; :should-component-update
;; (lambda (next-props next-state)
;; (or (not (@ next-state context current))
;; (not (= (@ next-state context mode)
;; (@ this state context mode)))
;; (@ next-state action-registered)))
;; :make-display
;; (lambda (main-display callback))
;; :component-did-mount
;; (lambda ()
;; (let* ((self this)
;; (faux-container (chain self props (connect-faux-d-o-m "div" "chart")))
;; (main-display (chain window d3 (select faux-container)
;; (append "svg")
;; (attr "class" "vector-interface"))))
;; (chain window -react-faux-dom (with-faux-d-o-m (@ view-modes graph-shape-view)))
;; ;; (chain self (make-display main-display (lambda (params)
;; ;; (chain subcomponents (effects params)))))
;; ))
)
;(cl "SHR" (@ this state just-updated))
;;(chain console (log :abc (@ self state data) -slate-editor -slate-value))
;(chain console (log :ssp (@ self state space)))
;;(let ((-data-sheet (new -react-data-sheet)))
;; (chain console (log :cc (@ self props action) (@ self state context mode)
;; (@ self state context)))
(let ((self this)
(-renderer (chain window -react-faux-dom (with-faux-d-o-m (@ pairs graph-vector-renderer)))))
;; (cl 555 (@ self state space) (@ self props context updated))
;; (cl :self self (@ self vector-renderer)
;; (not (= "undefined" (typeof (@ self vector-renderer))))
;; (+ "#branch-" (@ self props context index)
;; "-" (@ self props data id))
;; (j-query (+ "#branch-" (@ self props context index)
;; "-" (@ self props data id))))
(panic:jsl (:div :class-name "display-holder-outer"
(:-renderer :point (@ self state point)
:point-setter (@ self set-point)
:link-connector (@ self connect-link)
:updated (@ self props context updated)
:data (@ self state space)
:meta (@ self props data meta)))))))
| 24,254 | Common Lisp | .lisp | 600 | 32.316667 | 106 | 0.542668 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 7c60ba67fbf651be3f40fb18c66349aa6635d06c321fa4aca62a4f430cf4ca4f | 2,656 | [
-1
] |
2,657 | ui-model.color.lisp | phantomics_seed/seed.ui-model.color/ui-model.color.lisp | ;;;; seed.ui-model.color.lisp
(in-package #:seed.ui-model.color)
(defvar *common-lab-palette-lightness-gradient* (list 15 20 45 50 60 65 92 97))
(defun lab-space-gradient (degrees a-origin b-origin a-terminal b-terminal)
(let ((l-degrees *common-lab-palette-lightness-gradient*))
(loop for index from 0 to (1- degrees)
collect (let ((l (nth index l-degrees))
(a (if (< index 2)
a-origin (if (> index (- degrees 2))
a-terminal (floor (* (- a-origin a-terminal)
(/ degrees index))))))
(b (if (< index 2)
b-origin (if (> index (- degrees 2))
b-terminal (floor (* (- b-origin b-terminal)
(/ degrees index)))))))
(multiple-value-bind (r g b)
(multiple-value-call #'dufy:xyz-to-qrgb (dufy:lab-to-xyz l a b))
(format nil "~2,'0x~2,'0x~2,'0x" r g b))))))
(defmacro lab-palette (&rest colors)
`(list ,@(loop for color in colors collect
`(multiple-value-bind (r g b)
(multiple-value-call #'dufy:xyz-to-qrgb (dufy:lab-to-xyz ,@color))
(list r g b)))))
(defun hex-express (color-list)
(flet ((hex-convert (r g b) (format nil "~2,'0x~2,'0x~2,'0x" r g b)))
(if (listp (first color-list))
(loop for color in color-list collect (apply #'hex-convert color))
(apply #'hex-convert color-list))))
(defun palette-list (hex-list)
(if (= 8 (length hex-list))
(let ((keys (list :base03 :base02 :base01 :base00 :base0 :base1 :base2 :base3)))
(loop for index from 0 to 7 append (list (nth index keys)
(concatenate 'string "#" (nth index hex-list)))))
hex-list))
(defmacro setup-palette (palette-argument colors content)
``(let ,(loop for color in ,(cons 'list colors)
collect (list color `(getf ',palette-argument (intern (string-upcase color)
"KEYWORD"))))))
| 1,799 | Common Lisp | .lisp | 38 | 42 | 86 | 0.628848 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 9b34d97d289a610313a829ddc636db0b84549f9c41599dc10c68e11b2345e703 | 2,657 | [
-1
] |
2,658 | graph.garden-path.lisp | phantomics_seed/seed.media.graph.garden-path/graph.garden-path.lisp | ;;;; graph.garden-path.lisp
(in-package #:seed.generate)
(specify-media
media-spec-graph-garden-path
(graph-garden-path-content
(follows reagent graph-id)
`((set-branch-meta branch :change nil)
(cond ((eq :node (caar data))
(labels ((transcribe (target items)
(if (not items)
target (progn (setf (getf (getf target :meta)
(first items))
(second items))
(transcribe target (cddr items))))))
(setf (branch-image branch)
(loop for item in (branch-image branch)
collect (if (eq (getf item :id) (of-branch-meta branch :point))
(transcribe item (cdar data))
item)))
(set-branch-meta branch :change (list :node-changed t
:node-id (string-upcase (of-branch-meta branch :point))))
(branch-image branch)))
((get-param :set-point)
(set-branch-meta branch :point (intern (get-param :node-id) "KEYWORD"))
(branch-image branch))
((get-param :add-node)
(multiple-value-bind (output-data new-node-id)
(add-blank-node (branch-image branch)
(get-param :object-type)
(get-param :object-meta))
(set-branch-meta branch :change (list :node-added t :new-id (string-upcase new-node-id)))
(setf (branch-image branch) output-data)))
((get-param :add-link)
(add-blank-link (branch-image branch)
(intern (get-param :node-id) "KEYWORD")
(get-param :object-meta))
(set-branch-meta branch :change (list :link-added t :node-id (get-param :node-id)))
(branch-image branch))
((get-param :connect-link)
(connect-link (branch-image branch)
(intern (get-param :node-id) "KEYWORD")
(intern (get-param :link-id) "KEYWORD")
(intern (get-param :destination-node-id) "KEYWORD")
(get-param :object-meta))
(set-branch-meta branch :change (list :link-connected t :node-id (string-upcase (get-param :node-id))
:link-id (string-upcase (get-param :link-id))))
(branch-image branch))
((get-param :remove-object)
(setf (branch-image branch)
(remove-graph-element (branch-image branch)
(intern (get-param :node-id) "KEYWORD")
(if (get-param :link-id)
(intern (get-param :link-id) "KEYWORD"))))
(set-branch-meta branch :change (list :object-removed t :node-id (get-param :node-id)
:link-id (if (get-param :link-id)
(get-param :link-id)
"")))
(branch-image branch))
(t (set-branch-meta branch :change nil)
(branch-image branch))))
`((let ((to-return nil))
(loop for item in ,reagent while (not to-return)
do (if (string= (string-upcase ,graph-id)
(string-upcase (second item)))
(setq to-return (cddr item))))
to-return)))
(graph-garden-path-display
(follows reagent)
`((if (not (of-branch-meta branch :point))
(set-branch-meta branch :point (getf (first (branch-image branch))
:id)))
(preprocess-nodes ,(if reagent reagent `(branch-image branch)))))
(graph-garden-path-node-content
(follows reagent point)
`((let ((to-return nil))
;; (print (list :reg reagent ,point))
(loop for item in ,reagent while (not to-return)
do (if (string= (string-upcase ,point)
(string-upcase (getf item :id)))
(setq to-return item)))
`((:node ,@(getf to-return :meta)
,@(if (getf to-return :do)
(list :action (getf to-return :do))))))))
)
| 3,377 | Common Lisp | .lisp | 84 | 34.309524 | 105 | 0.634843 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 2f2d614f204e5945941bf6b1e1290e5149f36902d3494d139ff9022529073c16 | 2,658 | [
-1
] |
2,659 | feed.base.lisp | phantomics_seed/seed.app-model.feed.base/feed.base.lisp | ;;;; seed.app-model.feed.base.lisp
(in-package #:seed.app-model.feed.base)
(defmacro feed-manifest (&rest items)
(let ((content (gensym)))
`(let ((,content (make-hash-table :test #'eq)))
(setf ,@(loop for item in items collect
`((gethash ,(getf item :id) ,content)
,item)))
(lambda (params)
(cond ((getf params :id)
(gethash (getf params :id) ,content)))))))
#|
(feed-manifest
(:id :aa :title "First Post" :date "01-01-2018"))
|#
;; (id (let ((str (make-string-output-stream)))
;; (uuid:format-as-urn str (uuid:make-v1-uuid))
;; (intern (string-upcase (third (split-sequence #\: (get-output-stream-string str))))
;; "KEYWORD")))
| 676 | Common Lisp | .lisp | 19 | 32.315789 | 87 | 0.62634 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 0ddc3a31801f951af591504f96fce561b02761397d5b3f3412234b88d5a97bf3 | 2,659 | [
-1
] |
2,660 | router.base.lisp | phantomics_seed/seed.platform-model.router.base/router.base.lisp | ;;;; router.base.lisp
(in-package #:seed.platform-model.router.base)
(defmacro router (portal-suffix &rest routes)
"Create a portal that serves as a router for requests to local and/or remote systems. Creates contacted systems within the portal as per the routes passed as arguments."
(let ((portal-name (format nil "ROUTES.~a" (string-upcase portal-suffix))))
`(progn (defpackage ,(make-symbol portal-name)
(:export)
(:use #:cl #:seed.generate))
(in-package ,(make-symbol portal-name))
(macrolet ((defvar-portal () `(defvar ,(intern "*PORTAL*" ,portal-name)))
(ispr (&rest args) (cons (intern "SPROUT" ,portal-name)
args)))
(defvar-portal)
(media media-spec-base)
(ispr ,(intern portal-name "KEYWORD")
:system (:description "This is a router."
:license "GPL-3.0")
:package ((:use :common-lisp))
:branches ((systems (in (put-image))
(out (set-type :router))))
:contacts ,(mapcar (lambda (route)
(let ((route-name (first route))
(props (rest route)))
`(ispr ,(intern (format nil "ROUTE.~a" (string-upcase route-name))
"KEYWORD")
:package ((:user :common-lisp :cl-who))
:branches
((main (in (put-image)
,@(if (getf props :host)
`((remote (:host ,(getf props :host)
:name ,(if (getf props :system)
(getf props :system)
(intern route-name
"KEYWORD"))
:branch ,(if (getf props :branch)
(getf props :branch)
:main))))))
(out (set-type :route)))))))
routes)))
(in-package ,(make-symbol (package-name *package*))))))
| 1,787 | Common Lisp | .lisp | 40 | 34.225 | 171 | 0.558688 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | c10a44b2132b0d7779401a0ba29561c4b21c868a35261dc60a6fc733f986d647 | 2,660 | [
-1
] |
2,661 | package.lisp | phantomics_seed/seed.ui-spec.stage-menu.base/package.lisp | ;;;; package.lisp
(defpackage #:seed.ui-spec.stage-menu.base
(:export #:stage-extension-menu-base #:stage-controls-marginal-base
#:stage-controls-base-contextual)
(:use #:cl #:seed.generate))
| 202 | Common Lisp | .lisp | 5 | 37.4 | 69 | 0.723077 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 6459e37ffe0429875580c891e7b5e628cdd80308ec9e03e33db26378eacc4dad | 2,661 | [
-1
] |
2,662 | stage-menu.base.lisp | phantomics_seed/seed.ui-spec.stage-menu.base/stage-menu.base.lisp | ;;;; stage-menu.base.lisp
(in-package #:seed.ui-spec.stage-menu.base)
(defmacro stage-extension-menu-base (meta-symbol)
"A set of menu items for use with Seed interfaces."
`(lambda (menu-params)
(list (mapcar (lambda (item)
(cond ((eq :insert-fibo-points item)
;; `(,',meta-symbol :insert-fibo-points
;; :mode (:interaction :insert)
;; :format (,',meta-symbol
;; (spiral-points 100 100
;; (,',meta-symbol
;; ((,',meta-symbol
;; ((:circle :stroke-width 2 :r 3
;; :fill "#88aa00" :stroke "#e3dbdb"))
;; :mode (:view :item :removable t
;; :title "Small Green Circle")))
;; :mode (:options
;; ((:value
;; (,',meta-symbol
;; ((:circle :stroke-width 2 :r 3
;; :fill "#88aa00"
;; :stroke "#e3dbdb"))
;; :mode (:view :item :removable t
;; :title "Small Green Circle"))
;; :title "Small Green Circle")
;; (:value
;; (,',meta-symbol
;; ((:circle :stroke-width 2 :r 5
;; :fill "#87aade"
;; :stroke "#e3dbdb"))
;; :mode (:view :item :removable t
;; :title "Big Blue Circle"))
;; :title "Big Blue Circle"))
;; :removable nil :fill-by :select
;; :view :list)))
;; :format spiral-points-expand))
nil)
((eq :insert-circle item)
`(,',meta-symbol :insert-circle
:mode (:interaction :insert)
:format (:circle :cx 100
:cy 100
:r 25)))
((eq :insert-rect item)
`(,',meta-symbol :insert-rectangle
:mode (:interaction :insert)
:format (:rect :x 100
:y 100
:height 35
:width 35)))
((eq :insert-add-op item)
`(,',meta-symbol :insert-add-op
:mode (:interaction :insert)
:format (+ 1 2)))
((eq :insert-mult-op item)
`(,',meta-symbol :insert-mult-op
:mode (:interaction :insert)
:format (* 3 4)))))
menu-params))))
(defmacro stage-controls-marginal-base (meta-symbol spec-symbol params-symbol output-symbol)
(declare (ignorable spec-symbol))
`(((eq :save (first ,params-symbol))
(cons `(,',meta-symbol :save :mode (:interaction :commit))
,output-symbol))
((eq :revert (first ,params-symbol))
(cons `(,',meta-symbol :revert :mode (:interaction :revert))
,output-symbol))))
(defmacro stage-controls-base-contextual (meta-symbol spec-symbol params-symbol output-symbol)
(declare (ignorable params-symbol))
`((let ((param-checks (mapcar #'second (find-form-in-spec 'is-param ,spec-symbol))))
(append (if (find :save param-checks)
(list `(,',meta-symbol :save :mode (:interaction :commit))))
(if (find :revert param-checks)
(list `(,',meta-symbol :revert :mode (:interaction :revert)))
,output-symbol)))))
;; (defmacro stage-controls-marginal-base (meta-symbol)
;; `(labels ((process-params (params &optional output)
;; (if (not params)
;; output (process-params (rest params)
;; (cond ((eq :save (first params))
;; (cons `(,',meta-symbol :save :mode (:interaction :commit))
;; output))
;; ((eq :revert (first params))
;; (cons `(,',meta-symbol :revert :mode (:interaction :revert))
;; output))
;; (t output))))))
;; #'process-params))
| 3,621 | Common Lisp | .lisp | 88 | 34.886364 | 94 | 0.522676 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 14049242ba9c2e038caf14fac02ffc2669bda397ecee3b19eb29ee2caf9a59d4 | 2,662 | [
-1
] |
2,663 | glyphs.base.lisp | phantomics_seed/seed.express.glyphs.base/glyphs.base.lisp | ;;;; glyphs.base.lisp
(in-package #:seed.express.glyphs.base)
(specify-glyphs
glyphs-base
:default
(((0 7)) ((2 14) (2 4) (0 2)))
:type-is
(("car"
(((0 12)) ((4 13) (4 4)) ((2 13) (2 10) (0 8))))
("cdr"
(((0 7)) ((4 13) (4 4)) ((2 10) (2 4) (0 2))))
;; ("+"
;; (((0 7)) ((8 12) (8 8)) ((6 10) (6 6)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("-"
;; (((0 7)) ((8 10) (8 6)) ((6 12) (6 8)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("*"
;; (((0 7)) ((8 14) (8 8)) ((6 10) (6 6)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("/"
;; (((0 7)) ((8 10) (8 4)) ((6 12) (6 8)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("expt"
;; (((0 7)) ((12 13) (12 9)) ((10 14) (10 8))
;; ((8 14) (8 8)) ((6 10) (6 6)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("log"
;; (((0 7)) ((12 9) (12 5)) ((10 10) (10 4))
;; ((8 10) (8 4)) ((6 12) (6 8)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
;; ("sqrt"
;; (((0 7)) ((10 10) (10 4)) ((8 10) (8 4)) ((6 12) (6 8)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
("blank"
(((0 8)) ((0 8) (0 0))))
("number"
(((0 8)) ((2 10) (2 5) (0 3))))
("t"
(((0 8)) ((0 7 17/2) (0 9) nil) ((4 10) (4 6)) ((2 10) (2 6) (0 4))))
("nil"
(((0 8)) ((2 4) (0 2))))
("keyword"
(((0 9)) ((0 9/2 19/2) (0 8) nil) ((3 0 4) (0 5) nil)))
("symbol"
(((0 10)) ((3 0 5) (0 5) nil)))
("character"
(((0 8)) ((0 5 15/2) (0 8) nil) ((2 10) (2 6) (0 4))))
("string"
(((0 7)) ((4 14) (4 12)) ((4 11) (4 9)) ((4 8) (4 4))
((0 7 6) (0 10) nil) ((2 14) (2 4) (0 2))))
("form-function"
(((0 7)) ((4 14) (4 6)) ((2 12) (2 4) (0 2))))
("form-macro"
(((0 7)) ((4 12) (4 6)) ((2 14) (2 4) (0 2))))
("form-list"
(((0 7)) ((0 5 5) (0 8) nil) ((2 14) (2 4) (0 2))))
("form-keyword-list"
(((0 7)) ((0 5 15/2) (0 8) nil) ((0 5 5) (0 8) nil)
((2 14) (2 4) (0 2))))))
| 1,852 | Common Lisp | .lisp | 53 | 31.660377 | 99 | 0.348358 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 44c1edb48077f148d72f78510a5f42d913ee1e5364afb73129ab6d64282b60ce | 2,663 | [
-1
] |
2,664 | package.lisp | phantomics_seed/seed.ui-model.keys/package.lisp | ;;;; package.lisp
(defpackage #:seed.ui-model.keys
(:export #:key-ui #:specify-key-ui #:build-key-ui #:portal-action)
(:use #:cl #:parenscript #:symbol-munger))
| 167 | Common Lisp | .lisp | 4 | 39.25 | 68 | 0.677019 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | c657b4edef3cbb03642ee70b0673201a8653be50cf6ef3c59ae6fbd118e63426 | 2,664 | [
-1
] |
2,665 | ui-model.keys.lisp | phantomics_seed/seed.ui-model.keys/ui-model.keys.lisp | ;;;; ui-model.keys.lisp
(in-package #:seed.ui-model.keys)
(defmacro specify-key-ui (name &key (discrete nil) (navigational nil) (keymap nil))
"Define (part of) a key ui specification."
`(defmacro ,name ()
(list ,@(mapcar (lambda (input) (list 'quote input))
(if discrete (mapcar (lambda (category)
(cons (first category)
(macroexpand (cons 'discrete-key-ui (rest category)))))
discrete)))
,@(mapcar (lambda (input) (list 'quote input))
(if keymap (mapcar (lambda (category)
(cons (first category)
(macroexpand (cons 'keymap-ui (rest category)))))
keymap)))
,@(mapcar (lambda (input) (list 'quote input))
(if navigational (mapcar (lambda (category)
(cons (first category)
(macroexpand (cons 'nav-key-ui (rest category)))))
navigational))))))
(defmacro key-ui (name &rest ui-specs)
"Build the complete keystroke UI specification object and assign it to a variable with the given name."
`((setf ,name (create ,@(labels ((functionize (input &optional output)
(if input
(functionize (cddr input)
(append (list (first input)
`(lambda (portal) ,(second input)))
output))
output)))
(functionize (let ((output nil))
(mapcar (lambda (ui-spec)
(mapcar (lambda (ui-mode)
(setf (getf output (first ui-mode))
(append (cons 'list (rest ui-mode))
(rest (getf output
(first ui-mode))))))
(macroexpand (list ui-spec))))
(reverse ui-specs))
output)))))))
(defmacro discrete-key-ui (&rest combos)
"Build a discrete key UI specification from the given key combinations."
(cons 'build-key-ui
;; if a list of keystrokes is given, create duplicate behavior for each keystroke
(loop :for combo :in combos :append (if (listp (first combo))
(mapcar (lambda (combo-element) (cons combo-element (rest combo)))
(first combo))
(list (cons (first combo)
(rest combo)))))))
(defmacro nav-key-ui (direction-aliases &rest combos)
"Build a navigational key UI from the given combinations, combining one or more sets of directional keys
with each given set of combos."
(cons 'build-key-ui
(loop :for combo :in combos :append
(loop :for sub-combo :in (mapcar (lambda (combo-element direction)
(mapcar (lambda (direction-alias)
;; If the combo key string is empty, thus specifying the
;; function of the dirrectional keys when pressed alone,
;; make sure no extra space is added in the string
(cons (concatenate 'string (first combo)
(if (< 0 (length (first combo)))
" " "")
(nth direction direction-alias))
combo-element))
direction-aliases))
(rest combo)
(loop :for direction :from 0 :to (1- (length (first direction-aliases)))
:collect direction))
append sub-combo))))
(defmacro keymap-ui (modifier-key &rest combos)
"Build a specification for a modified keymap."
(cons 'build-keymap
;; if a list of keystrokes is given, create duplicate behavior for each keystroke
(loop :for combo :in combos :append
(let* ((char-string (string-downcase (write-to-string (first combo))))
(modifier-string (string-downcase (write-to-string modifier-key)))
(shifted-char-string (if (third combo)
(string-downcase (write-to-string (third combo)))))
(input-string (if (= 1 (length char-string))
char-string (aref char-string 1)))
(shifted-char-input-string (if shifted-char-string
(if (= 1 (length shifted-char-string))
shifted-char-string (aref shifted-char-string 1)))))
(append (if (fourth combo)
(list `(,(format nil "~a ~a" modifier-string input-string)
(portal-action insert-char char ,(string (fourth combo)))
,(if (and (not shifted-char-string)
(fifth combo))
`("is_solitary" t)))))
(if (fifth combo)
(if shifted-char-string
(list `(,(format nil "~a ~a" modifier-string shifted-char-input-string)
(portal-action insert-char char ,(string (fifth combo)))))
(list `(,(format nil "~a shift ~a" modifier-string input-string)
(portal-action insert-char char ,(string (fifth combo))))))))))))
(defpsmacro portal-action (action-name &rest params)
"This macro is used in key definition files to wrap portal actions in functions for use in response to key commands."
`(lambda () (chain portal (act ,(lisp->camel-case action-name) (create ,@params)))))
(defmacro build-key-ui (&rest combos)
"Format and generate a set of key UI parameters."
(macrolet ((inp (sym)
`(intern (string-upcase (quote ,sym))
(package-name *package*))))
(mapcar (lambda (combo)
(let ((commands (if (listp (first combo))
(first combo)
(list (first combo))))
(options (rest combo)))
;; set standard Keystroke options for the Seed key UI
(if (not (getf options (inp is-exclusive)))
(setf (getf options (inp is-exclusive)) t))
;; (if (not (getf options (inp prevent-default)))
;; (setf (getf options (inp prevent-default)) t))
(append `(create keys ,(first combo))
;; object properties must be converted to underscore_format to work with the
;; Keystroke library
(labels ((underscore (input &optional output)
(if input
(underscore (cddr input)
(append (list (symbol-munger:lisp->underscores (first input))
(second input))
output))
output)))
(underscore options)))))
combos)))
(defmacro build-keymap (&rest combos)
(mapcar (lambda (combo) (append `(create keys ,(first combo)
"on_keydown" ,(second combo)
,@(third combo))))
combos))
| 5,904 | Common Lisp | .lisp | 129 | 38.147287 | 119 | 0.628859 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 1cca37cc33f7a00ff7d751c58bc82bc37195a233c714716fc941e48be024e524 | 2,665 | [
-1
] |
2,666 | utils.lisp | phantomics_seed/demo-image/utils.lisp | ;;;; utils.lisp
(in-package #:demo-image)
(defun raster-process-layers-expand (items)
(let ((output (loop :for item :in items :append
(let ((type (getf (getf (getf (cddr item) :mode) :format-properties) :type)))
(cond ((eq :off (getf (getf (cddr item) :mode) :toggle))
nil)
((eq :load type)
`((:load :path ,(second (caadr item)))))
((eq :apl type)
`((:apl :exp ,(second (caadr item)))))
((eq :output type)
`((:output :path ,(second (caadr item))))))))))
(cons (intern "RASTER-PROCESS-LAYERS" (package-name *package*))
output)))
| 597 | Common Lisp | .lisp | 15 | 34.2 | 82 | 0.581034 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 28109071e276e9104d6974cd5dfcf53dc393abd620b7f1716bc849448854012e | 2,666 | [
-1
] |
2,667 | main.lisp | phantomics_seed/demo-image/main.lisp | (IN-PACKAGE #:DEMO-IMAGE)
(DEFVAR IMAGE-OUTPUT-PATH)
(META
(RASTER-PROCESS-LAYERS (:LOAD :PATH "sample-image.jpg")
(:APL :EXP "0⌈255⌊⌈1.2×input") (:APL :EXP "input[;;1]←100 ◊ 0⌈255⌊⌈input")
(:OUTPUT :PATH "sample-image-out.jpg"))
:MODE
(:MODEL
((META
((META "sample-image.jpg" :MODE
(:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "sample-image.jpg")))
:MODE
(:VIEW :ITEM :TITLE "Load File" :OPEN T :REMOVABLE T :FORMAT-PROPERTIES
(:TYPE :LOAD) :MODEL
((META "sample-image.jpg" :MODE
(:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "sample-image.jpg")))
:VALUE NIL))
(META
((META "0⌈255⌊⌈1.2×input" :MODE
(:TITLE "APL" :VIEW :TEXTFIELD :VALUE "0⌈255⌊⌈1.3×input")))
:MODE
(:VIEW :ITEM :TITLE "APL Mutation" :OPEN T :REMOVABLE T :TOGGLE :ON
:FORMAT-PROPERTIES (:TYPE :APL) :MODEL
((META "0⌈255⌊⌈1.2×input" :MODE
(:TITLE "APL" :VIEW :TEXTFIELD :VALUE "0⌈255⌊⌈1.3×input")))
:VALUE NIL))
(META
((META "input[;;1]←100 ◊ 0⌈255⌊⌈input" :MODE
(:TITLE "APL" :VIEW :TEXTFIELD :VALUE "")))
:MODE
(:VALUE NIL :MODEL
((META "input[;;1]←100 ◊ 0⌈255⌊⌈input" :MODE
(:TITLE "APL" :VIEW :TEXTFIELD :VALUE "")))
:FORMAT-PROPERTIES (:TYPE :APL) :OPEN T :REMOVABLE T :TITLE "APL Mutation"
:TOGGLE :ON :VIEW :ITEM))
(META
((META "sample-image-out.jpg" :MODE
(:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "sample-image-out.jpg")))
:MODE
(:VIEW :ITEM :TITLE "Output to File" :OPEN T :REMOVABLE T
:FORMAT-PROPERTIES (:TYPE :OUTPUT) :MODEL
((META "sample-image-out.jpg" :MODE
(:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "sample-image-out.jpg")))
:VALUE NIL)))
:VIEW :LIST :FILL-BY :SELECT :REMOVABLE NIL :OPTIONS
((:TITLE "Load File" :VALUE
(META ((META "" :MODE (:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "")))
:MODE
(:VIEW :ITEM :TITLE "Load File" :REMOVABLE T :OPEN T :FORMAT-PROPERTIES
(:TYPE :LOAD))))
(:TITLE "APL Mutation" :VALUE
(META ((META "" :MODE (:TITLE "APL" :VIEW :TEXTFIELD :VALUE ""))) :MODE
(:VIEW :ITEM :TITLE "APL Mutation" :REMOVABLE T :OPEN T :FORMAT-PROPERTIES
(:TYPE :APL))))
(:TITLE "Output to File" :VALUE
(META ((META "" :MODE (:TITLE "File Path" :VIEW :TEXTFIELD :VALUE "")))
:MODE
(:VIEW :ITEM :TITLE "Output to File" :REMOVABLE T :OPEN T
:FORMAT-PROPERTIES (:TYPE :OUTPUT)))))
:FORMAT :RASTER-PROCESS-LAYERS-EXPAND :VALUE NIL))
(SETQ IMAGE-OUTPUT-PATH "../demo-image/sample-image-out.jpg")
| 2,594 | Common Lisp | .lisp | 61 | 36.442623 | 79 | 0.613857 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 41e510bae0f94c25301ca2cc0bf386e8017efa891e9fd3d4cd69a8995f73ae55 | 2,667 | [
-1
] |
2,668 | atom.base.lisp | phantomics_seed/seed.modes.atom.base/atom.base.lisp | ;;;; atom.base.lisp
(in-package #:seed.modulate)
(defun subdivide-for-display (symbol)
"Divide a symbol's textual representation into major segments, delineated by periods, and minor segments, delineated by dashes."
(cond ((string= "-" symbol)
'(("-")))
((string= "." symbol)
'((".")))
(t (mapcar (lambda (substring) (split-sequence #\- substring))
(split-sequence #\. symbol)))))
(specify-atom-modes
modes-atom-base
(:predicate
(:enclosed-by (meta))
:decode ((cons (intern "META")
(cons (decode-atom new-item)
(postprocess-structure (getf item :mt))))))
(:predicate
(:enclosed-by (quote quasiquote unquote unquote-splicing)))
(:predicate
(:type-is string)
:type-extension (type-of item)
:view (regex-replace-all "~~" item "~")
:eval (process (regex-replace-all "~" value "~~")))
(:predicate
(:type-is character)
:type-extension (list (type-of item))
:view (concatenate 'string (list item))
:eval (process (aref value 0)))
(:predicate
(:type-is nil)
:view (if item "t" "nil")
:eval (process (equal "t" value)))
(:predicate
(:type-is number)
:type-extension (let ((type (type-of item)))
(if (listp type)
type (list type)))
;; if the type-of function returns a single atom (not a list), push that atom onto an empty list
;; so it can be appended
:view (write-to-string item)
:eval (process (parse-number value)))
(:predicate
(:type-is keyword)
:view (string-downcase item)
:eval (process (intern (string-upcase value) "KEYWORD"))
:display (subdivide-for-display (string-downcase item)))
(:predicate
(:type-is symbol)
:view (string-downcase item)
:eval (if (or (null value)
(string= value ""))
(process :seed-constant-blank)
(process (read-from-string value)))
:display (subdivide-for-display (string-downcase item))
:process (let ((origin (trace-symbol item (of-meta :package))))
(if (and origin (symbolp item))
(setf (getf properties :|pkg|)
(string-downcase (package-name origin))
(getf properties :|pkd|)
(subdivide-for-display (string-downcase (package-name origin))))))))
| 2,131 | Common Lisp | .lisp | 61 | 31.377049 | 130 | 0.668118 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 9ecd51357dec58c48fb560efed9d35e9c2a924229b16793c9420ac12adc1bcf9 | 2,668 | [
-1
] |
2,669 | site.base.lisp | phantomics_seed/seed.app-model.site.base/site.base.lisp | ;;;; seed.app-model.site.base.lisp
(in-package #:seed.app-model.site.base)
(defvar simple-form-facility)
(setq simple-form-facility
`(lambda ()
(chain (j-query ".service-terminal")
(map (lambda (index data)
(let* ((element (j-query data))
(interaction-data (chain element (attr "interaction")
(split " "))))
;; (chain console (log 9091 element interaction-data
;; data
;; (chain element (find "button.submit"))))
(chain (chain element (find "button.submit"))
(on "click" (lambda (event)
(chain event (prevent-default))
(chain j-query
(ajax (create url "../portal"
type "POST"
data-type "json"
content-type "application/json; charset=utf-8"
data (chain -j-s-o-n
(stringify
(chain interaction-data
(concat
(chain
element
(serialize-j-s-o-n))))))
success (lambda (data)
(chain console (log :returned data))
;; (callback stage-data data)
)
error (lambda (data err)
(chain console (log 11 data err)))
))))))))))))
(defvar form-support-effects)
(setq form-support-effects
`(list ,simple-form-facility))
(defmacro standard-form-effects ()
`(lambda (interface)
(chain ,form-support-effects (map (lambda (effect) (funcall effect interface))))))
| 1,470 | Common Lisp | .lisp | 41 | 27.04878 | 87 | 0.562105 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 1cde9025dd17935423001f4fabf4f360b11a2d110f4434bd440130fc1e174618 | 2,669 | [
-1
] |
2,670 | package.lisp | phantomics_seed/seed.contact/package.lisp | ;;;; package.lisp
(defpackage #:seed.contact
(:export #:contact-create-in #:contact-remove-in #:contact-remove-all-in #:contact-open-in #:contact-close-in)
(:use #:cl #:cl-utilities #:jonathan #:symbol-munger #:hunchentoot #:seed.modulate))
| 246 | Common Lisp | .lisp | 4 | 59.25 | 112 | 0.713693 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 8c45e3914913f567e1e23927f37dd605c884f12fc728c18e2bc1920139407e28 | 2,670 | [
-1
] |
2,671 | contact2.lisp | phantomics_seed/seed.contact/contact2.lisp | ;;;; contact.lisp
(in-package #:seed.contact)
(defparameter *my-acceptor*
(make-instance 'hunchentoot:easy-acceptor
;:address
;"localhost"
:port 8085
:document-root
(asdf:system-relative-pathname (intern (package-name *package*) "KEYWORD")
"../")))
;(setq *dispatch-table*
; (cons (hunchentoot:create-static-file-dispatcher-and-handler "/bla"
; #P"/tmp/bla/hi.txt")
; (list 'dispatch-easy-handlers)))
(define-easy-handler (seed-grow :uri "/portal") ()
(setf (hunchentoot:content-type*) "text/plain")
(let ((request-type (hunchentoot:request-method hunchentoot:*request*)))
(cond ((eq :get request-type)
"Not available.")
((eq :post request-type)
(let* ((input (jonathan:parse (hunchentoot:raw-post-data :force-text t)
:keyword-normalizer (lambda (key)
(string-upcase (camel-case->lisp-name key)))
:normalize-all t))
(package-string (string-upcase (first input)))
(function-string (string-upcase (second input)))
(system-string (if (third input) (string-upcase (third input)))))
(print (list :in input))
(jonathan:to-json
;(print
;(coder system-string
(if (and (or (find-package package-string)
(asdf:load-system (intern package-string)))
(find-symbol function-string package-string))
(multiple-value-bind (func-sym locality)
(intern function-string package-string)
(if (eq :external locality)
(apply func-sym
; the package string is always at
; the head of the argument list
(append (list (intern package-string "KEYWORD"))
(mapcar (lambda (param)
(if (stringp param)
(intern (string-upcase param) "KEYWORD")
(if (listp (first param))
(decoder param)
param)))
(cddr input)))))))
;))
;:key-normalizer #'lisp->camel-case
))))))
;symbols above from packages jsown, seed-codec and seed-server
;(jonathan:to-json '(:a 1 :b 2 :c-test 3) :key-normalizer #'lisp->camel-case)
(defun so () (start *my-acceptor*))
(defun sc () (stop *my-acceptor*))
; (asdf:load-system 'seed-interface)(asdf:load-system 'my-portal)(seed-interface::so)(in-package :my-portal)(grow)
; (progn (asdf:load-system 'seed-lib-table) (asdf:load-system 'imago) (load "~/src/lisp/seed-app/test-table2/package.lisp") (load "~/src/lisp/seed-app/test-image/package.lisp"))
; (load "~/src/lisp/seed-app/test-table/package.lisp")
; (encoder '(cons 4 (list 3 4 (list nil 8 "abc" (cons 4 (list 9 9))))))
; (gethash :merged (multiple-value-bind (data breadth depth) (encoder '((+ 1 2 2 3 5))) (encode-meta data (list breadth depth) process-list)))
; (seed.generate::branch-image (seed.generate::find-branch-by-name :main (seed.generate::contact-to (seed.generate::find-contact-by-sprout-name *portal* :test-table2))))
; (main (:form) (in (express :file :-self) (process :eval) (media :table-specs) (contingency :main))
; (main (in (model (table-specs)) (realize (file :-self :eval)) (contingency :main))
; (out (model (table-specs)) (express (file :-self) (form))))
; three actions - express, model, realize
| 3,184 | Common Lisp | .lisp | 65 | 43.4 | 177 | 0.649823 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | e1ceea524341c0b1f8b92c02b7e82d736c339cd73b8098d417fc9dc20611b1cc | 2,671 | [
-1
] |
2,672 | contact.lisp | phantomics_seed/seed.contact/contact.lisp | ;;;; contact.lisp
(in-package #:seed.contact)
(define-easy-handler (seed-grow :uri "/portal") ()
(setf (content-type*) "text/plain")
(let ((request-type (hunchentoot:request-method hunchentoot:*request*)))
(cond ((eq :get request-type)
"Not available.")
((eq :post request-type)
(let* ((input (let ((mime-type (first (split-sequence #\; (rest (assoc :content-type (headers-in*)))))))
(cond ((string= mime-type "application/json")
;; convert JSON Lisp format with jonathan
(jonathan:parse (hunchentoot:raw-post-data :force-text t)
:keyword-normalizer
(lambda (key) (string-upcase (camel-case->lisp-name key)))
:normalize-all t))
((string= mime-type "application/x-lisp")
;; native Lisp code is passed directly through and read
(read-from-string (hunchentoot:raw-post-data :force-text t))))))
(package-string (string-upcase (first input)))
(function-string (string-upcase (second input))))
(jonathan:to-json (if (and (or (find-package package-string)
(asdf:load-system (intern package-string)))
(find-symbol function-string package-string))
(multiple-value-bind (function-symbol locality)
(intern function-string package-string)
;; (print (list :in input))
(if (eq :external locality)
;; only allow the use of functions that are exported in the portal package
(apply function-symbol
;; the package string is always at the head of the argument list
(append (list (intern package-string "KEYWORD"))
(mapcar (lambda (param)
(if (and (stringp param)
(string= "__" (subseq param 0 2)))
(intern (string-upcase (subseq param 2))
"KEYWORD")
param))
(cddr input)))))))))))))
(defmacro contact-create-in (contact-list name &key (port nil) (root nil))
`(setf (getf ,contact-list ,(intern (string-upcase name) "KEYWORD"))
(list :port ,port
:instance (make-instance 'hunchentoot:easy-acceptor
:port ,port
:document-root (asdf:system-relative-pathname
(make-symbol (package-name *package*))
,root)))))
(defmacro contact-remove-in (contact-list name)
`(setf (getf ,contact-list ,(intern (string-upcase name) "KEYWORD"))
nil))
(defmacro contact-remove-all-in (contact-list)
`(setq ,contact-list nil))
(defmacro contact-open-in (contact-list &optional name)
(let ((contact (gensym)))
`(let ((,contact ,(if name `(getf ,contact-list ,(intern (string-upcase name) "KEYWORD"))
;; if no contact name is given, open the first contact instance in the list
`(second ,contact-list))))
(start (getf ,contact :instance))
(princ (format nil "~%[ _ ] Opened Seed contact.~%Port: ~d~%~%" (getf ,contact :port)))
nil)))
(defmacro contact-close-in (contact-list &optional name)
(let ((contact (gensym)))
`(let ((,contact ,(if name `(getf ,contact-list ,(intern (string-upcase name) "KEYWORD"))
;; if no contact name is given, close the first contact instance in the list
`(second ,contact-list))))
(stop (getf ,contact :instance))
(princ (format nil "~%[|||] Closed Seed contact.~%Port: ~d~%~%" (getf ,contact :port)))
nil)))
| 3,277 | Common Lisp | .lisp | 67 | 42.164179 | 108 | 0.640649 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 9988b7132d97c2fdcac494535bead173753329941fa855a98a7866997623e492 | 2,672 | [
-1
] |
2,673 | chart.base.lisp | phantomics_seed/seed.media.chart.base/chart.base.lisp | ;;;; chart.base.lisp
(in-package #:seed.generate)
(specify-media
media-spec-chart-base
(chart-entity
(follows reagent symbol-name)
`((let* ((other-branch (find-branch-by-name reagent sprout))
(other-branch-image (branch-image other-branch))
(generated-data (loop for item in data collect
(cond ((string= "line" (getf item :type))
`(meta
((meta ,(write-to-string (caar (getf item :points)))
:mode (:value ,(write-to-string (caar (getf item :points)))
:view :textfield :title "Start Time"))
(meta ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:view :textfield :title "Start Price"))
(meta ,(write-to-string (caadr (getf item :points)))
:mode (:value ,(write-to-string (caadr (getf item :points)))
:view :textfield :title "End Time"))
(meta ,(write-to-string (coerce (cadadr (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadadr
(getf item :points))
'short-float))
:view :textfield :title "End Price")))
:mode
(:view :item :title "Line" :removable t :open t :toggle :on
:format-properties (:type :load))))
((string= "retraceX" (getf item :type))
`(meta
((meta ,(write-to-string (caar (getf item :points)))
:mode (:value ,(write-to-string (caar (getf item :points)))
:view :textfield :title "Start Time"))
(meta ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:view :textfield :title "Start Price"))
(meta ,(write-to-string (caadr (getf item :points)))
:mode (:value ,(write-to-string (caadr (getf item :points)))
:view :textfield :title "End Time"))
(meta ,(write-to-string (coerce (cadadr (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadadr
(getf item :points))
'short-float))
:view :textfield :title "End Price")))
:mode
(:view :item :title "Time Retracement" :removable t :open t :toggle :on
:format-properties (:type :load))))
((string= "retraceY" (getf item :type))
`(meta
((meta ,(write-to-string (caar (getf item :points)))
:mode (:value ,(write-to-string (caar (getf item :points)))
:view :textfield :title "Start Time"))
(meta ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadar (getf item :points))
'short-float))
:view :textfield :title "Start Price"))
(meta ,(write-to-string (caadr (getf item :points)))
:mode (:value ,(write-to-string (caadr (getf item :points)))
:view :textfield :title "End Time"))
(meta ,(write-to-string (coerce (cadadr (getf item :points))
'short-float))
:mode (:value ,(write-to-string (coerce (cadadr
(getf item :points))
'short-float))
:view :textfield :title "End Price")))
:mode
(:view :item :title "Price Retracement" :removable t :open t :toggle :on
:format-properties (:type :load))))))))
;; (print (list :gg data generated-data))
(setf (branch-image other-branch) ;; other-branch-image
(loop for form in other-branch-image collect
(if (and (string= "META" (string-upcase (first form)))
(cadadr form)
(string= (string-upcase (cadadr form))
(string-upcase ,symbol-name)))
(let ((new-meta (cddr form)))
(setf (getf (getf new-meta :mode) :model)
generated-data)
(append (list (first form)
(second form))
new-meta))
form)))
data
))
;; `((let ((to-return nil))
;; (loop for item in ,reagent while (not to-return)
;; do (if (string= (string-upcase ,graph-id)
;; (string-upcase (second item)))
;; (setq to-return (cddr item))))
;; to-return))
)
)
| 4,258 | Common Lisp | .lisp | 99 | 34.686869 | 78 | 0.577821 | phantomics/seed | 77 | 4 | 3 | GPL-3.0 | 9/19/2024, 11:25:50 AM (Europe/Amsterdam) | 90e5eba0cc1c9e4897cf4d10d660d595cc1dc4f37833b54b21053f70742161ef | 2,673 | [
-1
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.