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
400
example.lisp
joinr_clclojure/examples/example.lisp
(ql:quickload :clclojure) ;;Lame ns call (for now just a ;;wrapper around defpackage) (clclojure.base:ns :clclojure.example) x ;;we have persistent vectors, which will ;;be replaced by bootstrapped variants from ;;clclojure.base... ;;some clojure-0 expressions demonstrating ;;fundamentals of the language primitives... ;;def and defn export by default, ;;also unify the function and symbol ;;namespaces. Working on metadata and ;;reader support... (def v [1 2 3]) ;;some core protocol stuff... (clclojure.base::-conj v 4) ;;=> [1 2 3 4] (clclojure.base::-count v) ;;=> 3 ;;fn - single-arity, no meta, no destructuring (def f (fn [x] (+ x 2))) ;;naive defn (no meta, no destructuring) (defn plus [x y] (+ x y)) (plus 1 2) ;;=> 3 (defprotocol IBlah (blah [obj])) (defprotocol IBlee (blee [obj msg])) (deftype blather [name x] IBlah (blah [this] (str :blaH! name x))) (def the-blather (->blather :joinr "blech!!!")) (blah the-blather) ;;gives us ":BLAH!:JOINRblech!!!" ;;reify works....under current single arity limitations ;;we generate effectively an anonoymous, throwaway ;;CLOS class via deftype, letting deftype do the work.. ;;Note: we get warnings about being unable to find ;;the specializer class for the reified class, ;;need to check that out, may be missing a quote. ;;It works tho! (def the-blither (let [msg "HOHOHO, MEEERRRRYY REIFY"] (reify IBlah (blah [this] msg) IBlee (blee [this custom-msg] (str "custom! " custom-msg) )))) (blah the-blither) ;;gives us "HOHOHO, MEEERRRRYY REIFY" (blee the-blither "Honk!") ;;gives us "custom! Honk!" ;;protocols are just structs.... IBlah ;; #S(CLCLOJURE.PROTOCOLS::PROTOCOL ;; :NAME IBLAH ;; :FUNCTIONS (#S(CLCLOJURE.PROTOCOLS::PROTOCOL-FUNCTION ;; :NAME BLAH ;; :ARGS ([OBJ]) ;; :BODIES 1 ;; :ARITIES ((:ARGS [OBJ] :ARITY 1 :VARIADIC? NIL)) ;; :DOC "not documented")) ;; :SATISFIER #<CLOSURE (LAMBDA (CLCLOJURE.PROTOCOLS::NEWSPEC) ;; :IN ;; CLCLOJURE.PROTOCOLS::MAKE-SATISFIER) {100553992B}> ;; :DOC "Not Documented" ;; :MEMBERS (REIFY1 BLATHER)) ;;On the cusp of greatness, but still ;;debuggin multiple arities! So close.... ;; (defn idx [v n] ;; (-nth v n)) (def x :ecks) ;;quasiquoting of literals now works... (defparameter quasi-form `[,@(list 1 2 ) ,x ,@(list :literal x :hah) [,x ,x ,x [x] {:a 2 :b {:unquote ,x} :c {:quoted x}}]]) ;;[1 2 :ECKS :LITERAL :ECKS :HAH [:ECKS :ECKS :ECKS [X] {:C {:QUOTED X} :B {:UNQUOTE :ECKS} :A 2}]] ;;splicing doesn't work yet, need to work around ;;unquote-splicing requirement that everything be a common lisp ;;sequence type, or coerce to lazy-seq, or override reader macro. ;;WIP ;; (let [x 2 ;; y `[1 ,x 2 [3 4 ,@[1 2]]]] ;; y) ;;coming soon... ;;meta, destrutcturing, core clojure functions ;;per cljs, and more... ;;loop/recur (maybe not necessary since we can compile ;;on most implementations and get TCO) ;;Working on variadic protocol implementations, ;;will be addressed in clclojure.variadic (defprotocol IMany (many [obj] [obj msg])) ;;currently broken, close to fixing... (deftype manytest [] IMany (many [this] :one!) (many [this item] item)) (def mt (->manytest)) (many mt) (many mt :hello) ;;EXAMPLE> (many mt) ;;:ONE! (defn test-my-scope [] (let [hello :hello world :world k 2 inc (fn [x] (+ x 1)) add (fn [x y] (+ x y)) tbl (let [tbl (make-hash-table)] (setf (gethash :hello tbl) "World") (setf (gethash :world tbl) "Hello") (setf (gethash :k tbl) k) tbl)] (list (hello tbl) (world tbl) (add (inc 39) k) (gethash :k tbl) ;;(:k tbl);;WIP ))) ;;EXAMPLE> (test-my-scope) ;;("World" "Hello" 42 2) ;;named functions don't currently parse! ;;This fails too, we have some jank with the ;;reader when we're inside a macro... ;;Need to fix the quasi quoter, should ;;be in backtick.lisp. (defn test-arities [] (let [sum (fn ([x] x) ([x y] (+ x y)) ([x y &rest zs] (reduce #'+ (+ x y) zs)))] (clclojure.pvector:persistent-vector (sum 1) (sum 1 2) (sum 1 2 3 4 5 6)) )) ;;EXAMPLE> (test-arities) ;;[1 3 21] (defn test-arities-literal [] (let [sum (fn ([x] x) ([x y] (+ x y)) ([x y &rest zs] (reduce #'+ (+ x y) zs)))] [(sum 1) (sum 1 2) (sum 1 2 3 4 5 6) ])) (defn test-arities-quasi [] (let [sum (fn ([x] x) ([x y] (+ x y)) ([x y &rest zs] (reduce #'+ (+ x y) zs)))] `[,(sum 1) ,(sum 1 2) ,(sum 1 2 3 4 5 6) ])) (test-my-scope) (test-arities) (test-arities-literal) (test-arities-quasi) ;; EXAMPLE> (test-arities-literal) ;; [1 3 21] (let [x 2] [x]) ;;[2] (let [x 2 y `[,x]] `[,y]) ;;not passing: (let [x 2 y `[,x]] `[,y `[,,y] ]) ;;Function recur (reduce (fn [acc x] (if (odd? x) (recur acc (1+ x)) (+ acc x))) -55 '(1 2 3 4)) ;;Named function (e.g. recur) (reduce (fn accf [acc x] (if (odd? x) (accf acc (1+ x)) (+ acc x))) -55 '(1 2 3 4)) ;;these are cool, but we should be able to ;;eliminate the funcall need. (funcall (fn accf ([x] (list :end x)) ([x & xs] (reduce conj (vector x) xs) )) :beans) (funcall (fn accf ([x] (list :end x)) ([x & xs] (reduce conj (vector :end x) xs) )) 1 2 3 4) (funcall (fn accf ([x] (list :end x)) ([x & xs] (reduce conj [:end x] xs) )) 1 2 3 4) (defn count-to-ten [x] (if (< x 10) (recur (+ x 1)) x)) (count-to-ten 0) (defn count-to-ten-r [x] (if (< x 10) (count-to-ten-r (+ x 1)) x)) (defn lazy-count [init] (when (pos? init) (lazy-seq (cons init (lazy-count (- init 1))))))
6,046
Common Lisp
.lisp
208
24.961538
99
0.575035
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
7dfd677a783752a32364f88123787a55fc52d770ab9de950763746c0536eff03
400
[ -1 ]
401
evaltest.lisp
joinr_clclojure/tests/evaltest.lisp
;;quick test to see if we get compiler support for our ;;eval hack... (ql:quickload :cl-package-locks) (load "eval.lisp") (defstruct blah (x)) (defparameter b (make-blah :x 2)) (defmethod clclojure.eval:custom-eval ((obj blah)) (list :this-is-custom (blah-x obj))) (clclojure.eval:enable-custom-eval) (defparameter custom (eval b)) ;;(:THIS-IS-CUSTOM 2) (clclojure.eval:disable-custom-eval) (defparameter normal (eval b)) ;;#S(BLAH :X 2)
450
Common Lisp
.lisp
15
28.2
54
0.727273
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f8dffb65e55dc823141e65e5873a9ada95d67eea7ba635051c0a690970725b8a
401
[ -1 ]
402
recurtest.lisp
joinr_clclojure/tests/recurtest.lisp
(defpackage common-utils.recurtest (:use :common-lisp :common-utils)) (in-package :common-utils.recurtest) (comment ;;we can call simmary-tails on all these and get nil, ;;or some combination of (t, nil), (t, some-list-of illegal callsites) (defparameter normal-call `(if (= 2 3) :equal (progn (print :otherwise) :inequal))) (defparameter good-tail '(if (= 2 3) (recur 2) (recur 3))) (defparameter bad-tail '(progn (recur 2) 3)) (defparameter gnarly-bad-tail '(lambda (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (recur 44)) 2)))))) (defparameter gnarly-good-tail '(lambda (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (print 44)) 2)))))) ) ;(with-recur (x 2 y 3) (+ x y)) (with-recur (x 0) (if (< x 10) (recur (1+ x)) x)) (with-recur (x 0) (if (> x 9) x (recur (1+ x)))) (defun good-tail () (with-recur (x 2) (if (> x 5) x (if (= x 2) (recur 5) (recur (1+ x)))))) ;;not currently checked! (defun bad-tail () (with-recur () (progn (recur 2) 3))) (defun gnarly-bad-tail (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (recur 44)) 2))))) (defun gnarly-good-tail (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ acc)) (progn (when (< 2 3) (print 44)) 2))))) ;;base case works.... (defparameter test-fn2 (named-fn test-fn (x) (if (< x 2) x (progn (print `(:calling ,x)) (test-fn (- x 2)))))) ;;recur works just fine.... (defparameter test-fn3 (named-fn test-fn (x) (if (< x 2) x (progn (print `(:calling ,x)) (recur (- x 2)))))) (defparameter nftest (named-fn* test-fn ((x) (+ x 1)) ((x y) (+ x y)) ((&rest xs) (reduce #'+ xs)))) (defparameter nf (named-fn* test-fn ((coll) (when-let ((x (first coll))) (progn (pprint x) (recur (rest coll))))) ((c1 c2) (test-fn c2))))
2,710
Common Lisp
.lisp
100
17.69
78
0.427855
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
3c4f0d811c21e5a9c96f70c7be21aa5cbf0a1f25967e53395af4a18b7758cacc
402
[ -1 ]
403
bootstrap.lisp
joinr_clclojure/dustbin/bootstrap.lisp
;;This is the basis for bootstrapping clojure onto common lisp. ;;I figure if I can define the primitive forms that clojure requires, ;;there's already a ton of clojure written in clojure. The clojurescript ;;runtime actually has a significant portion of clojure defined via protocols, ;;which given limited forms, provides a pretty slick way to bootstrap an ;;implementation. ;;A couple of big hurdles: ;;1) Lisp1 vs Lisp2. I'll hack the evaluator for this. ;;2) Persistent structures. Already built Pvector and 1/2 done with Pmap. ;;3) Protocols. Already implemented as generic functions. ;;4) Multimethods. Need to find a way to implement multiple dispatch. ;;5) Reader. CL macros use , and ,@ in place of ~ and ~@ in Clojure. ;; We'll need to either cook the common lisp reader, or ;; build a separate clojure reader that will perform the ;; appropriate replacements. ;; @ is a literal for #'deref in clojure ;; , is whitespace in clojure. ;; [] denote vectors -> already have a reader macro in pvector.lisp ;; {} denote maps -> already have a reader macro in pmap.lisp ;; #{} denote sets ;;6) Destructuring. This may be a bit tricky, although there are a limited number of ;; clojure forms. Since we have reader ;;7)Seq library. This shouldn't be too hard. I already have a lazy list lib prototype ;; as well as generic functions for the basic ops. I think I'll try to ;; use the protocols defined in the clojurescript version as much possible, ;; rather than baking in a lot of the seq abstraction in the host language ;; like clojure does. (defpackage :clclojure.base (:use :common-lisp :common-utils :clclojure.keywordfunc :clclojure.lexical :clclojure.pvector :clclojure.cowmap :clclojure.protocols) (:shadow :let :deftype) (:export :def :defn :fn :meta :with-meta :str :deftype :defprotocol :reify :extend-type :extend-protocol :let)) (in-package clclojure.base) ;;move this later... (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defun eval-vector (v) (clclojure.pvector:vector-map (lambda (x) (eval x)) v)) (defun vector? (x) (typep x 'clclojure.pvector::pvec)) ;;this is a top-down evaluator...once we go CL, we can't ;;go back. Unless we define clj wrappers for all the special forms, ;;and lift the CL eval into clj-eval.... (defmacro clj-eval (expr) (cond ((clclojure.base::vector? expr) (eval-vector expr)) (t (cl:eval expr)))) ;;we probably want clj-defmacro, which uses clj-eval instead of ;;cl:eval. ;;Then we can define our language forms in terms of clj-defmacro... ;;We need to handle evaluation of special forms like vectors and maps ;;that occur on the rhs of the binding forms.... ;;lhs doesn't get eval'd (destructuring may expand the form), ;;but RHS has clojure-style evaluation semantics, i.e. we need ;;to eval any vector/map/set literals and splice them in. ;; (defmacro vec->bindings (v &rest body) ;; (assert (and (vector? v) ;; (evenp (vector-count v)) ) (v) ;; "Expected vector arg with even number of elements") ;; `(unified-let* (,@ (partition! 2 (vector-to-list v))) ,@body)) ;;works with our vector expression... ;; (defmacro vec->bindings (vexpr &rest body) ;; (progn (pprint vexpr) ;; (let ((binds (rest vexpr))) ;; `(unified-let* (,@ (partition! 2 binds)) ,@body)))) ;;We'll redefine this later with an implementation... ;; (defmacro clj-let (bindings &rest body) ;; `(vec->bindings ,bindings ,@body)) ;;Let's hack let to allow us to infer vector-binds ;;as a clojure let definition... (defmacro let (bindings &body body) (if ;(eq (first bindings) 'persistent-vector) (vector? bindings) `(unified-let* (,@(partition! 2 (vector-to-list bindings))) ,@body) `(cl:let ,bindings ,@body))) ;;Lisp1 -> Lisp2 (Somewhat outdated....) ;;============== ;;Unification of Function and Symbol Names (Pending) ;;================================================== ;;My good friend Mr. Hanson pointed out that I could hijack lambda entirely. ;;In common lisp, symbols have a function slot and a value slot. ;;So if we want to have a lisp1, we want to eliminate the partitioning between ;;function and var namespaces. ;;If we want to make a lisp1 style symbol, we just set the symbol-value ;;and the symbol-function to the same thing; i.e. we point the symbol-function ;;to the symbol value. ;;(defmacro unify (symb) ;; `(when (function (symbol-function ,symb) (symbol-value ,symb)))) (defun macro? (s) (when (macro-function s) 't)) (defun function? (s) (fboundp s))) ;;Lisp1 Evaluation ;;================ ;;These are for convenience. CL has a bunch of special operators... ;;Note-> there's a schism over special-form-p, and special-operator-p, ;;special-operator is the accepted nomenclature, although older implementations ;;use special-form... (defparameter special-forms '(quote defmacro lambda apply cl)) (defun special? (x) (and (atom x) (or (when (special-operator-p x) x) (find x special-forms)))) ;;Given an environment, and a symbol (currently expr), uses common lisp to ;;evaluate the expression. (defun resolve (expr &optional env) (if (null env) (handler-case (eval expr) (unbound-variable () (eval `(function ,expr)))) (let ((res (second (assoc expr env)))) (if (null res) (resolve expr) res)))) ;; (defun resolve2 (expr &rest env) ;; (if (null env) (eval (symbol-value expr)) ;; (let ((res (second (assoc expr (first env))))) ;; (if (null res) (resolve2 expr) res)))) ;;Fancy Symbol Resolution ;;======================= ;;Supplemental functions to be used for code analysis and tree walking later. ;;Todo: Change the lamba list for env from rest to optional. Currently requires extraneous ;;first calls. (defun resolve* (xs env) (mapcar (lambda (x) (resolve x env)) xs)) (defun resolve-tree (xs env) (map-tree (lambda (x) (resolve x env)) xs)) ;;Determines if an expression (really a symbol) is self evaluating. (defun self-evaluating? (expr) (or (functionp expr) (or (numberp expr) (stringp expr) (characterp expr) (keywordp expr)) (special? expr))) ;;retrieve the current bindings associated with a symbol. (defmacro current-binding (x) `(list (quote ,x) x)) ;;compose an alist of all the current bindings of each x in xs. (defun lex-bindings (args) (reduce (lambda (acc x) (cons (current-binding x) acc)) args :initial-value '())) ;;Extend the lexical environment with a set of new bindings. (defun push-bindings (env args) (reduce (lambda (x acc) (cons acc x)) args :initial-value env)) ;;Evaluate an alist of binding pairs. Used for forms like let and friends. (defun eval-binds (xs f env) (mapcar (lambda (bind) (list (first bind) (funcall f (second bind) env))) xs)) ;;The base lisp1 environment contains bindings for the arithmetic operators, ;;and will likely include more bindings. Might change the environment from ;;and a-list to a hashtable at some point. (defparameter base-env (list (list '+ #'+) (list '* #'*) (list '/ #'/))) (define-condition not-implemented (error) ()) (define-condition uneven-arguments (error) ()) ;(defun get-funcallable (x); ; (if (symbolp x) ; ((symbol-function x) ;(defun function-form (x) ; (if (fboundp x) (funcall (defgeneric destructure (bindings)) ;;(spec [x y & rest]) ;;(destructure spec) ;;(lambda (args) ;; ((x (first args)) ;; (y (second args)) ;; (rest (cddr args)))) ;;(spec {:keys [x y]}) ;;(lambda (args) ;; ((x (get args :x)) ;; (y (get args :y))) ;(fn [{:keys [x y] :as m}] (+ x y)) ;;(lambda (m) (dbind (({:keys [x y]} args)) ,body)) ;;(fn [[x y]] (+ x y)) ;;a single function definition (defstruct fn-def args body) ;;a macro definition -- later (defstruct macro-def name args body) ;;At compile-time, [x y] -> (persistent-vector x y). ;;This is upsetting us... (defmacro quoted-vec (v) (if (vector? v) `(quote ,v);;`(persistent-vector ,@(mapcar #'quote-sym (vector-to-list v))) `(persistent-vector ,@(mapcar #'quote-sym (rest v))))) (defmacro quoted-hash (h) `(persistent-map ,@(mapcar #'quote-sym (rest h)))) (defun variadic (v) (member '& (vector-to-list v))) ;;Todo: move this out to CLOS? ;;parse a clojure style function definition. (defmacro read-fn (arg-vec body) `(make-fn-def :args (quoted-vec ,arg-vec) :body (quote ,body))) (defgeneric arity (fd)) (defmethod arity ((fd clclojure.pvector::pvec)) (values (vector-count fd) (variadic fd))) (defmethod arity ((fd fn-def)) (arity (slot-value fd 'args))) ;;since clojure allows multiple bodies, with fixed arity for each body, we ;;compose multiple function (arg body) pairs into a list of function definitions. ;;We should then be able to dispatch on the count of args, simply invoking ;;the appropriate function matched to arity. (defmacro fn* (&rest specs) `(list ,@(mapcar (lambda (vb) `(read-fn ,(first vb) ,(second vb))) specs))) (defparameter test-fn '(fn* ([x] x) ([x y] (+ x y)) ([x y & xs] (common-lisp:reduce #'+ xs :initial-value (+ x y))))) (defstruct arg-parse lambda-list outer-let) (define-condition no-matching-function (error) ()) (define-condition multiple-variadic-functions (error) ()) ;;this is going to be somewhat tricky, since we'll probably have a little state ;;machine that parses the args, possibly destructuring recursively. Don't know all ;;the cases yet, but we'll need to be able to destructure vectors and maps into ;;corresponding lambda lists. (defun parse-args (args) (make-arg-parse :lambda-list (substitute '&rest '& (vector-to-list args)))) ;;Compile a clojure fn special form into a common lisp lambda (defgeneric fndef->sexp (fd)) (defmethod fndef->sexp ((fd fn-def)) (with-slots (args body) fd (with-slots (lambda-list outer-let) (parse-args args) (let ((interior (if outer-let `(let* ,outer-let ,body) body))) `(lambda ,lambda-list ,interior))))) ;; (defun dispatch (f) `(apply ,f args)) ;; (defun function-dispatch (fd) ;; (reduce (lambda (acc x) (cons (list (arity x) (dispatch (eval (fndef->sexp x)))) acc)) ;; fd :initial-value (list))) ;;parse a list of function definitions into an n-lambda dispatching function. (defmethod fndef->sexp ((fd cons)) (if (= (length fd) 1) (fndef->sexp (first fd)) ;simple case ;;case with multiple function definitions. `(common-utils:lambda* ,@(mapcar (lambda (body) (rest (fndef->sexp body))) fd)))) ;;weak hack around lack of read-time vector creation. (defun vector-form? (expr) (or (vector? expr) (eq (first expr) 'persistent-vector))) ;;Clojure's anonymous function special form. ;;Todo: support destructuring in the args. (defmacro fn (&rest specs) (if (vector-form? (first specs)) ;; (progn (pprint :single) ;; (fndef->sexp (read-fn (first specs) (second specs)))) (eval `(fndef->sexp (fn* (,@specs)))) ;;TODO get rid of this eval.... (eval `(fndef->sexp (fn* ,@specs))))) ;;A CHEAP implementation of defn, replace this... (defmacro defn (name args &rest body) `(def ,name (fn ,args ,@body))) ;;NOTE: This is not necessary going forward.... ;;We can already mimic a lisp1 without a custom evaluator. ;;There "may" be a need for analyze/eval for some of the more ;;crafty stuff, particularly where clojure macros expose the ;;environment to the macro form... ;;We have a lisp1, sorta! ;;I need to add in some more evaluation semantics, but this might be the ;;way to go. For now, it allows us to have clojure semantics for functions ;;and macros. There's still some delegation to the common lisp evaluator - ;;which is not a bad thing at all! (defun lisp1 (expr &optional (env base-env)) (cond ((atom expr) (if (self-evaluating? expr) expr (resolve expr env))) ((null expr) '()) ((listp expr) (let ((f (first expr))) (case (special? f) ;Special forms evaluate to themselves. (function (eval `(function ,(second expr)))) (quote (second expr)) ;;common-lisp's lambda form (lambda (let* ((args (second expr)) (body (third expr))) (if (atom body) (eval `(lambda ,args ,(resolve body env))) ;simple ;this is currently packing around the lexical environment. ;Note: it's going to get a lot nastier if you include the cases ;that lambda lists cover and such. Right now, i'm assuming a ;simple list of args, lex-bindings will have to process lambda ;lists and other fun corner cases...I'll probably add an analyzer ;that will compile the non-free bits of the lambda down, ala SICP. (let ((lex-env (list 'quote env)) (arg-list (list* 'list args))) (eval `(lambda ,args (lisp1 ,(list 'quote body) (push-bindings ,lex-env (lex-bindings ,arg-list))))))))) ; ((let let*) (let* ((binds (second expr)) ; (body (third expr))) ; (eval `(let* ,(eval-binds binds #'lisp1 env) ; (lisp1 ,(list 'quote body) ; (push-bindings ,lex-env (lex-bindings ))) ;defmacro forms have a name, an args, and a body. (defmacro (error 'not-implemented)) ;;allows common-lisp semantics, this is an escape hatch. (cl (eval (first (rest expr)))) ;Otherwise it's a function call. (otherwise (apply (lisp1 f env) (mapcar (lambda (x) (lisp1 x env)) (rest expr))))))))) ;;Our clojure evaluator uses the lisp1 evaluator, and tags on some extra ;;evaluation rules. More to add to this. (defmacro clojure-eval (exprs) `(lisp1 (quote ,exprs))) ;;this is a top-down evaluator...once we go CL, we can't ;;go back. Unless we define clj wrappers for all the special forms, ;;and lift the CL eval into clj-eval.... (defmacro clj-eval (expr) (cond ((clclojure.base::vector? expr) (eval-vector expr)) (t (cl:eval expr)))) ;(let ((x (+ 2 1))) ; (lambda (y) (+ x y))) ;{:binds '( (x (+ 2 1) ) ; :body (lambda (y) (+ x y))} ;;testing ;;(clojure-eval ((lambda (x) (+ 2 x)) 2)) ;;BASE> 4 ;;Lambda/function call analysis (PENDING) ;;======================================= ;;if we want to build a structure that represents a lambda, then ;;we can worry about evaluating that structure as a cl lambda. ;; (LAMBDA (X) (#<Compiled-function + #x409FFC6> 2 X)) ;;we can kill 2 birds with one stone, if, during resolve, ;;we walk the code and swap out function calls with ;;funcall ;(lambda (x) (the-func obj args)) ;valid lisp1 ;(lambda (x) (funcall the-func-obj args)) ;;desired lisp2 (cl) ;;analyze a lambda expr. (defun function-call? (expr) (functionp (first expr))) ;;this is a cheap way to eval lambdas... ;;we need to change it to a compilation step, but we'll do that later. ;;for ;;everywhere we see (some-function arg) ;;we want to tell cl it's (funcall some-function arg) ;;Clojure Transformations (PENDING) ;;================================ ;;we need some basic transformations.... ;;I guess we can write a simple clojure reader by swapping some symbols around.. ;;maybe even use read macros... ;;Clojure -- Common Lisp ;;@x (deref x) -> used in quasiquoted expression, splice-collection ,@ ;;~x (insert x)? used to escape a quasiquote -> ,x ;;one simple transform is to scan the clojure expression, and change the following: ;;~ -> , ;;~@ -> ,@ ;;@x -> (deref x) ;;need to implement deref ;;[x] -> (pvector x) ;;more or less implemented ;;{x y} -> (hash-map x y) ;;(Blah. x) -> (make-Blah x) ;;CLOS constructor ;;(. obj method args) -> ((slot-value obj method) args) ;;(. obj (method args)) -> ((slot-value obj method) args) ;;(. obj method) -> ((slot-value obj method)) ;;(.method obj args) -> (slot-value obj method) ;;CLOS accessor ;;(def x val) -> (defparameter x val) ;;(let [x y] expr) -> (let* ((x y)) expr) ;;(some-namespace-alias/the-function x) -> (some-package-alias::the-function x) ;;(ns blah) -> (defpackage blah) ;;#"some-regex" -> (make-regex "some-regex") ;;need to use cl-ppre probably... ;;Quasiquoting/macro expansion ;;# means gensym. We have to walk the code tree and detect any #-appended symbols, do ;;a with-gensym for them, and go on. Usually only happens in let bindings. ;;i.e. blah# -> #blah_286_whatever (defun destructure-bind (args body) (list args body)) ;;parse an args input into a compatible CL lambda list ;;(defun args->lambdalist (args) ;; (if ((vector? args) (seq args)) ;; (throw ( ;;let's do a simple fn and see if we can re-use anything... ;;(simple-function ....) ;;(fn [x y z] (+ x y z)) ;;(defmacro fn (args body) ;; (let ((ll (args->lambdalist args))) ;; `(lambda ,args ;;(variadic-function ...) ;;(n-function ...) (defun multiple-arity? (args) (listp args)) ;;we'll deal with loop/recur later... (defun var-args (args) (member '& args)) (defun variadic? (args) (not (null (var-args args)))) (defun spec->lambda (args body) (let ((n (length args))) `((,n ,(var-args args)) (lambda ,args ,body)))) ;;only one function can be variadic in a fn form ;;map destructuring... ;;(fn [&{:keys [x y] :or {x v1 y v2} :as my-map}] ~body) -> ;;(lambda (&keys (x v1) (y v2)) ;; (let* ((my-map (hash-map x v1 y v2))) ;; ,@body ;;(fn [{:keys [x y] :or {x v1 y v2} :as my-map}] ~body) -> ;;(lambda (my-map)) ;; (let* ((x (or (get my-map x) v1)) ;; (y (or (get my-map y) v2))) ;; ,@body) ;;The following forms boil down to ;;(fn [vector-arg arg] body) ;;(fn [& vector-arg] body) ;;(fn [[x y] z] body) -> ;; (lambda (coll z) ;; (let* ((x (first coll)) ;; y (second coll))) ;; ,@body) ;;(fn [& xs] ~body) -> (lambda (&args xs) body) ;;destructuring, in general, is the process of transforming a sequence of ;;args into an appropriate binding. ;;since args are unified to always be in vectors, it's tranforming a vector ;;into something. ;;a binding form may include primitive symbols, with the symbol & delineating ;;list arguments. everything after & is to be bound to a list. ;;note -> further destructuring may occur here... ;;[x y & z] ;;So, we recursively destructure the binding form. ;;We can bifurcate the process more if we split the destructuring into special cases. ;;The first case is that we haven't hit & yet, so we are collecting simple structures. ;;The second case is after we've hit &. ;;If we are in case 1, we traverse the vector of symbols and see if they're compound. ;;The only cases to handle are ;;Symbol -> Symbol ;;Vector -> (destructure vector) ;;recursive call ;;hash-map -> (destructure hash-map) ;;more complex destructuring. ;;(defmacro defn (name &rest args body) ;; (let ((args (mapcar (lambda (x) (if-let ((func (symbol-function x))) (progn (setf (symbol-value x) func))) (defmacro doc (v) `(pprint (rest (assoc 'DOC (meta ,v))))) ;;Meta Data ;;========= ;;I think we want to use persistent maps for meta data, as clojure does. ;;I want to get the stubs in place, and am using property lists with a 'meta ;;entry pointing at an assoc list for now. ;;These should be pulled out into a protocol. (defmacro symbol-meta (symb) `(get (quote ,symb) 'meta)) (defmacro with-symbol-meta (symb m) `(setf (get (quote ,symb) 'meta) ,m)) ;(defgeneric -get-meta (obj)) ;(defgeneric -set-meta (obj m)) ;(defmethod -get-meta ((obj symbol)) (symbol-meta obj)) ;(defmethod -set-meta ((obj symbol) m) (with-symbol-meta obj m)) (defun meta (obj) (-meta obj)) (defun with-meta (obj m) (-with-meta obj m)) (defparameter imp '(symbol (-get-meta (obj) (symbol-meta obj)) (-set-meta (obj m) (with-symbol-meta obj m)))) ;;(defun meta (obj) ;; (cond (symbolp obj) (eval `(get (quote ,obj) 'meta)) ;;One thing about metadata, and how it differs from property lists: ;;You can call meta on datastructures, or objects, and get a map back. ;;Symbols can have meta called on them with (meta #'the-symbol), which ;;uses sharp-quote to get the symbol, vs the symbol-name. ;;Clojure is a lisp-1, so we need to ensure that everything, even ;;functions, gets bound into the a single namespace. ;;another way to do this is to have clojure-specific symbols be actual ;;clos objects, which have meta data fields automatically. Then we ;;lose out on all the built in goodies from common lisp though. (defmacro unify-values (var) `(when (functionp (symbol-value (quote ,var))) (setf (symbol-function (quote ,var)) (symbol-value (quote ,var))))) ;;def ;;=== ;;Experimental. Not sure of how to approach this guy. ;;for now, default to everything being public / exported. ;;that should be toggled via metadata in real implementation. (defmacro def (var &rest init-form) `(progn (defparameter ,var ,@init-form) (with-meta (quote ,var) '((SYMBOL . T) (DOC . "none"))) (when (functionp (symbol-value (quote ,var))) (setf (symbol-function (quote ,var)) (symbol-value (quote ,var)))) (export ',var) (quote ,var) )) (comment ;testing (def the-val 2) (def symbol? #'symbolp) (eval-clojure '(symbol? the-val)) ;=> nil (eval-clojure '(add-two the-val)) ;=> 4 ) ;;Macrology ;;========= ;;if we have a quasiquotation, clojure allows the following: ;;var# -> (with-gensym (var) ...) ;;~expr -> ,expr ;;~@expr -> ,@expr ;;a clojure-style macro.. ;;transform ~ into , for quasiquoting (defun tildes->commas (the-string) (substitute #\, #\~ the-string)) ;;replaces the old ` with a quasiquote symbol, and wraps the expression as a list. ;;We can then parse the list to make (defun explicit-quasiquotes (the-string) (format nil "(quote (~a))" (common-utils::replace-all the-string "`(" "quasi-quote ("))) ;;delayed ;; (defun tilde-transformer ;; (stream subchar arg) ;; (let* ((sexp (read (explicit-quasiquotes (tildes->commas stream)) t)) ;; (fname (car sexp)) ;; (arguments (cdr sexp))) ;; `(map ;; (function ,fname) ;; ,@arguments))) ;;(set-dispatch-macro-character #\# #~ #'tilde-transformer) ;;if there's a @, we want to turn that badboy into a deref... ;;for code-walking later... (defun gensym-stub (x) (let* ((the-string (str x)) (bound (1- (length the-string)))) (when (char-equal #\# (aref the-string bound)) (format nil "~a" (subseq the-string 0 bound))))) ;;given (defun (x) `(let ((x# ,x)) x#)) ;;or ;;(defun (x) ;; (quasi-quote ;; (let ((x# (splice x))) ;; x#))) ;;write a function, quasi-quote, that will traverse its args ;;and produce a compatible common lisp expression ;;(quasiquote '(let ((x# (splice x))) x#)) => ;;'(with-gensyms (x#) ;; (let ((x# (splice x))) x#)) ;;we just need to find-gensyms... ;;'(with-gensyms (scrape-gensyms expr) ;; expr) (defun scrape-gensyms (expr) (filter (lambda (x) (not (null x))) (mapcar #'gensym-stub (common-utils::flatten expr)))) ;;not used (defmacro clojure-mac (name args body) (let ((xs (union (mapcar #'intern (scrape-gensyms body)) '()))) `(with-gensyms ,xs (defmacro ,name ,args ,body)))) ;;a lot of this functionality is related to quasi-quoting... ;;within a quasi quote, ;;on the read-side, we need to flip tildes to commas ;;on the evaluation side, we need to handle defmacro specially ;;(defmacro clojuremacro (name args body) ;; (let (( ;;deref @ ;;we need to process the deref-able symbols (defun deref-symb? (x) (char-equal #\@ (aref (str x) 0))) (defparameter mac-sample `(defmacro the-macro (x) (let ((many-xs (list x x))) `(let ((xs# ~many-xs))) (~x ~@xs)))) ;;given a string... (defparameter mac-string "`(defmacro the-macro (x) (let ((many-xs (list x x))) `(let ((xs# ~many-xs))) (~x ~@xs)))") ;;Clojure Core (PENDING) ;;====================== ;; (comment ;; (defmacro fn (& sigs) ;; (let* ((name (if (symbol? (first sigs)) (first sigs) nil) ;; sigs (if name (next sigs) sigs) ;; sigs (if (vector? (first sigs)) ;; (list sigs) ;; (if (seq? (first sigs)) ;; sigs ;; ;; Assume single arity syntax ;; (throw (IllegalArgumentException. ;; (if (seq sigs) ;; (str "Parameter declaration " ;; (first sigs) ;; " should be a vector") ;; (str "Parameter declaration missing")))))) ;; psig (fn* [sig] ;; ;; Ensure correct type before destructuring sig ;; (when (not (seq? sig)) ;; (throw (IllegalArgumentException. ;; (str "Invalid signature " sig ;; " should be a list")))) ;; (let [[params & body] sig ;; _ (when (not (vector? params)) ;; (throw (IllegalArgumentException. ;; (if (seq? (first sigs)) ;; (str "Parameter declaration " params ;; " should be a vector") ;; (str "Invalid signature " sig ;; " should be a list"))))) ;; conds (when (and (next body) (map? (first body))) ;; (first body)) ;; body (if conds (next body) body) ;; conds (or conds (meta params)) ;; pre (:pre conds) ;; post (:post conds) ;; body (if post ;; `((let [~'% ~(if (< 1 (count body)) ;; `(do ~@body) ;; (first body))] ;; ~@(map (fn* [c] `(assert ~c)) post) ;; ~'%)) ;; body) ;; body (if pre ;; (concat (map (fn* [c] `(assert ~c)) pre) ;; body) ;; body)] ;; (maybe-destructured params body))) ;; new-sigs (map psig sigs)] ;; (with-meta ;; (if name ;; (list* 'fn* name new-sigs) ;; (cons 'fn* new-sigs)) ;; (meta &form)))) ;; ) ;;Most of these will currently break, since the protocols use a clojure vector spec ;;and my defprotocol uses lists. Need to bridge the gap...Still, getting them ;;implemented will be hugely good, as it's the backbone of just about everything ;;else. ;;key eval ;;basic xform to get keywords-as-function compilation pass. ;;we can define an eval that kinda works... ;;if we analyze the form, we should end up with something we ;;can coerce into a CL compatible form.... (comment (defmacro keval (expr) (if (atom expr) `(cl:eval ,expr) (if (keywordp (first expr)) `(gethash ,(first expr) ,@(rest expr)) `(cl:eval ,expr)))) ;;it may be nice to define functional xforms... ;;allow keywords to be functions.... ;;if the thing in fn position is an IFn, ;;rewrite to an invoke call on the IFn... ;;i.e., prepend -invoke ) (defmacro myquote (expr) (if (atom expr) (progn (print :atom) `(quote ,expr)) (case (first expr) (persistent-vector `(clclojure.reader:quoted-children ,expr)) (t (progn (print :list) `(quote ,expr)))))) ;;hacky way to accomodate both forms... ;;we know we're in clojure if the args are vector (defmacro deftype (&rest args) (if (vector? (nth 1 args)) `(clojure-deftype ,@args) `(common-lisp::deftype ,@args))) ;;reify is interesting. ;;we generate an instance of an anonymous class, ;;ala deftype, with protocol implementations. ;;TODO: look at the consequences of having bunches of ;;anonymous classes laying around, say evaluating ;;reify several times...Should we garbage collect this? ;;Or does that cut into dynamicity? (defmacro reify (&rest implementations) (let [classname (gentemp "REIFY") ctor (gensym "CONSTRUCTOR") ] `(let ((,ctor (clojure-deftype ,classname [] ,@implementations))) (funcall ,ctor)))) (defmacro symbolic-bindings (binding-form &rest body) (let ((xs (eval `(quote ,binding-form)))) `(clj-let ,xs ,@body))) ;;;;;;;;;;;;;;;;;;;;;;;;;;; core protocols ;;;;;;;;;;;;; ;;Need to get back to this guy...multiple arity is not yet implemented... ;; (defprotocol IFn ;; (-invoke ;; [this] ;; [this a] ;; [this a b] ;; [this a b c] ;; [this a b c d] ;; [this a b c d e] ;; [this a b c d e f] ;; [this a b c d e f g] ;; [this a b c d e f g h] ;; [this a b c d e f g h i] ;; [this a b c d e f g h i j] ;; [this a b c d e f g h i j k] ;; [this a b c d e f g h i j k l] ;; [this a b c d e f g h i j k l m] ;; [this a b c d e f g h i j k l m n] ;; [this a b c d e f g h i j k l m n o] ;; [this a b c d e f g h i j k l m n o p] ;; [this a b c d e f g h i j k l m n o p q] ;; [this a b c d e f g h i j k l m n o p q s] ;; [this a b c d e f g h i j k l m n o p q s t] ;; [this a b c d e f g h i j k l m n o p q s t rest])) ;;These work (defprotocol ICounted (-count [coll] "constant time count")) (defprotocol IEmptyableCollection (-empty [coll])) (defprotocol ICollection (-conj [coll o])) (defprotocol IOrdinal (-index [coll])) ;;this will break. current implementation of defprotocol doesn't allow for ;;multiple arity functions like this. Need to handle variadic functions... ;; (defprotocol IIndexed ;; (-nth [coll n] [coll n not-found])) ;; (defprotocol ASeq) (defprotocol ISeq (-first [coll]) (-rest [coll])) (defprotocol INext (-next [coll])) ;; (defprotocol ILookup ;; (-lookup [o k] [o k not-found])) (defprotocol IAssociative (-contains-key? [coll k]) (-entry-at [coll k]) (-assoc [coll k v])) (defprotocol IMap (-assoc-ex [coll k v]) (-dissoc [coll k])) (defprotocol IMapEntry (-key [coll]) (-val [coll])) (defprotocol ISet (-disjoin [coll v])) (defprotocol IStack (-peek [coll]) (-pop [coll])) (defprotocol IVector (-assoc-n [coll n val])) (defprotocol IDeref (-deref [o])) (defprotocol IDerefWithTimeout (-deref-with-timeout [o msec timeout-val])) (defprotocol IMeta (-meta [o])) (defprotocol IWithMeta (-with-meta [o meta])) ;; (defprotocol IReduce ;; (-reduce [coll f] [coll f start])) (defprotocol IKVReduce (-kv-reduce [coll f init])) (defprotocol IEquiv (-equiv [o other])) (defprotocol IHash (-hash [o])) (defprotocol ISeqable (-seq [o])) (defprotocol ISequential "Marker interface indicating a persistent collection of sequential items") (defprotocol IList "Marker interface indicating a persistent list") (defprotocol IRecord "Marker interface indicating a record object") (defprotocol IReversible (-rseq [coll])) (defprotocol ISorted (-sorted-seq [coll ascending?]) (-sorted-seq-from [coll k ascending?]) (-entry-key [coll entry]) (-comparator [coll])) ;; (defprotocol ^:deprecated IPrintable ;; "Do not use this. It is kept for backwards compatibility with existing ;; user code that depends on it, but it has been superceded by IPrintWithWriter ;; User code that depends on this should be changed to use -pr-writer instead." ;; (-pr-seq [o opts])) (defprotocol IWriter (-write [writer s]) (-flush [writer])) (defprotocol IPrintWithWriter "The old IPrintable protocol's implementation consisted of building a giant list of strings to concatenate. This involved lots of concat calls, intermediate vectors, and lazy-seqs, and was very slow in some older JS engines. IPrintWithWriter implements printing via the IWriter protocol, so it be implemented efficiently in terms of e.g. a StringBuffer append." (-pr-writer [o writer opts])) ;; (defprotocol IPending ;; (-realized? [d])) ;; (defprotocol IWatchable ;; (-notify-watches [this oldval newval]) ;; (-add-watch [this key f]) ;; (-remove-watch [this key])) ;; (defprotocol IEditableCollection ;; (-as-transient [coll])) ;; (defprotocol ITransientCollection ;; (-conj! [tcoll val]) ;; (-persistent! [tcoll])) ;; (defprotocol ITransientAssociative ;; (-assoc! [tcoll key val])) ;; (defprotocol ITransientMap ;; (-dissoc! [tcoll key])) ;; (defprotocol ITransientVector ;; (-assoc-n! [tcoll n val]) ;; (-pop! [tcoll])) ;; (defprotocol ITransientSet ;; (-disjoin! [tcoll v])) ;; (defprotocol IComparable ;; (-compare [x y])) (defprotocol IChunk (-drop-first [coll])) (defprotocol IChunkedSeq (-chunked-first [coll]) (-chunked-rest [coll])) (defprotocol IChunkedNext (-chunked-next [coll])) ;;Vector implementations...not currenty working! ;;although...extend-protocol works! (extend-type clclojure.pvector::pvec ICounted (-count [c] (vector-count c)) IEmptyableCollection (-empty [c] []) ICollection (-conj [coll itm] (vector-conj coll itm)) IVector (-assoc-n [coll n val] (vector-assoc coll n val)) IStack (-peek [coll] (when (not (zerop (-count coll) )) (nth-vec coll 0))) (-pop [coll] (subvec coll 1)) ISeqable (-seq [coll] (error 'not-implemented)) IHash (-hash [o] (error 'not-implemented)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented)) IReversible (-rseq [coll] (error 'not-implemented)) IChunk (-drop-first [coll] (error 'not-implemented)) IChunkedSeq (-chunked-first [coll] (error 'not-implemented)) (-chunked-rest [coll] (error 'not-implemented)) IChunkedNext (-chunked-next [coll] (error 'not-implemented)) ) (extend-type symbol IMeta (-meta [obj] (symbol-meta obj)) IWithMeta (-with-meta [obj m] (with-symbol-meta obj m) obj)) ;;subvector impls... (extend-type clclojure.pvector::subvector ICounted (-count [c] (vector-count c)) IEmptyableCollection (-empty [c] []) ICollection (-conj [coll itm] (vector-conj coll itm)) IVector (-assoc-n [coll n val] (vector-assoc coll n val)) IStack (-peek [coll] (when (not (zerop (-count coll) )) (nth-vec coll 0))) (-pop [coll] (subvec coll 1)) ISeqable (-seq [coll] (error 'not-implemented)) IHash (-hash [o] (error 'not-implemented)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented)) IReversible (-rseq [coll] (error 'not-implemented)) IChunk (-drop-first [coll] (error 'not-implemented)) IChunkedSeq (-chunked-first [coll] (error 'not-implemented)) (-chunked-rest [coll] (error 'not-implemented)) IChunkedNext (-chunked-next [coll] (error 'not-implemented)) ) ;;list operations. (extend-type cons ICounted (-count [c] (length c)) IEmptyableCollection (-empty [c] '()) ICollection (-conj [coll itm] (cons itm coll)) IStack (-peek [coll] (first coll)) (-pop [coll] (rest coll)) ISeqable (-seq [coll] (error 'not-implemented)) IHash (-hash [o] (sxhash o)) IEquiv (-equiv [o other] (error 'not-implemented)) IMapEntry (-key [coll] (first coll)) (-val [coll] (second coll)) ) (extend-type clclojure.cowmap::cowmap ICounted (-count [c] (map-count c)) IEmptyableCollection (-empty [c] {}) ICollection (-conj [coll itm] (map-assoc coll (first itm) (second itm))) ISeqable (-seq [coll] (map-seq coll)) IAssociative (-contains-key? [coll k] (map-contains? coll k)) (-entry-at [coll k] (map-entry-at coll k)) (-assoc [coll k v] (map-assoc coll k v)) IMap (-assoc-ex [coll k v] (error 'not-implemented)) ;;apparently vestigial (-dissoc [coll k] (map-dissoc coll k)) IHash (-hash [o] (error 'not-implemented)) IEquiv (-equiv [o other] (error 'not-implemented)) IKVReduce (-kv-reduce [coll f init] (error 'not-implemented))) ;; IChunk ;; (-drop-first [coll] (error 'not-implemented)) ;; IChunkedSeq ;; (-chunked-first [coll] (error 'not-implemented)) ;; (-chunked-rest [coll] (error 'not-implemented)) ;; IChunkedNext ;; (-chunked-next [coll] (error 'not-implemented)) ;;friendly map printing (defmethod print-object ((obj hash-table) stream) (common-utils::print-map obj stream)) ;;map printing compatibility (defmethod print-object ((obj clclojure.cowmap::cowmap) stream) (common-utils::print-map (cowmap-table obj) stream))
37,082
Common Lisp
.lisp
903
38.284607
113
0.631733
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
8a057cee8e11e571cef13e3ee6867df520860c1f59cb45c8da4c6ef71c81df4e
403
[ -1 ]
404
literals.lisp
joinr_clclojure/dustbin/literals.lisp
(defpackage clclojure.literals (:use :common-lisp :clclojure.eval :clclojure.pvector :clclojure.cowmap)) (in-package :clclojure.literals) ;;Data Literal Eval Semantics (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (clclojure.eval:enable-custom-eval) ;;(eval [x y z]) => (vector (eval x) (eval y) (eval z)) ;;this is somewhat inefficient since we're not exploiting ;;chunks, but good enough for proof of concept. We do ;;have chunks, fyi. (defmethod custom-eval ((obj pvec)) (vector-map (lambda (x) (eval x)) obj)) (defmethod custom-eval ((obj subvector)) (vector-map (lambda (x) (eval x)) obj)) ;;(map {x y j k} => (persistent-map (eval x) (eval y) (eval j) (eval k)) (defmethod custom-eval ((obj cowmap)) (reduce (lambda (acc kv) (destructuring-bind (k v) kv (map-assoc acc (eval k) (eval v)))) (map-seq obj) :initial-value (empty-map))) )
940
Common Lisp
.lisp
23
36
94
0.649891
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
aefbccba99bf5c64df772d9fc6931aed26c06df22696693aa0b5c7107b5a7804
404
[ -1 ]
405
cowmap.lisp
joinr_clclojure/dustbin/cowmap.lisp
;;A lame copy-on-write implementation of persistent maps ;;useful for bootstrapping. ;;Notably, none of the operations on these guys are ;;lazy. Uses copies for otherwise destructive operations. ;;Wraps a mutable hashtable. (defpackage :clclojure.cowmap (:use :common-lisp) (:export :persistent-map :empty-map? :map-count :map-assoc :map-seq :empty-map :cowmap-table :cowmap) (:shadow :assoc :find)) (in-package clclojure.cowmap) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defstruct cowmap (table (make-hash-table))) ;;From stack overflow. It looks like the compiler needs a hint if we're ;;defining struct/class literals and using them as constants. (defmethod make-load-form ((m cowmap) &optional env) (declare (ignore env)) (make-load-form-saving-slots m))) (defun ->cowmap () "Simple persistent vector builder. Used to derive from other pvectors to share structure where possible." (make-cowmap)) (common-utils::defconstant! +empty-cowmap+ (make-cowmap)) (defun empty-map () +empty-cowmap+) (defun empty-map? (m) (eq m +empty-cowmap+)) (defun map-count (m) (hash-table-count (cowmap-table m))) (defun insert-keys! (tbl xs) (assert (evenp (length xs))) (loop for (k v) in (common-utils::partition! 2 xs) do (setf (gethash k tbl) v)) tbl) (defun persistent-map (&rest xs) "Funcallable constructor for building vectors from arglists. Used for read-macro dispatch as well." (if (null xs) +empty-cowmap+ (progn (assert (evenp (length xs))) (let* ((cm (->cowmap)) (tbl (cowmap-table cm))) (insert-keys! tbl xs) cm)))) (defun map-contains? (m k) (second (values (gethash k (cowmap-table m))))) (defun map-get (m k &optional default) (gethash k (cowmap-table m) default)) (defun map-entry-at (m k) (multiple-value-bind (v present) (map-get m k) (when present (list k v)))) (defun map-assoc (m k v) (let ((tbl (common-utils::copy-hash-table (cowmap-table m)))) (setf (gethash k tbl) v) (make-cowmap :table tbl))) (defun map-dissoc (m k) (if (map-contains? m k) (let ((tbl (common-utils::copy-hash-table (cowmap-table m)))) (remhash k tbl) (make-cowmap :table tbl)) m)) (defun map-seq (m) (common-utils::hash-table->entries (cowmap-table m))) (defmethod print-object ((obj cowmap) stream) (common-utils::print-map (cowmap-table obj) stream))
2,501
Common Lisp
.lisp
71
30.802817
73
0.667081
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
59bfa0b1ba03041e4d86445f870bfa9dcf0327f3a2cb73031ef37e110f40220c
405
[ -1 ]
407
eval.lisp
joinr_clclojure/dustbin/eval.lisp
(defpackage :clclojure.eval (:use :common-lisp :cl-package-locks) (:export :custom-eval :enable-custom-eval :disable-custom-eval :simple-eval-in-lexenv)) (in-package clclojure.eval) (defgeneric custom-eval (obj)) ;;We perform the same thing existing eval does for unknown ;;datums. Just return the data as-is. This is effectively ;;what sbcl does by default. (defmethod custom-eval (obj) obj) ;;another option is to use find-method... ;(find-method #'custom-eval '() '(t) nil) (defvar +original-eval+ (symbol-function 'SB-IMPL::simple-eval-in-lexenv)) ;;This is identical to the default sbcl eval.. ;;with the exception of the hook to our custom method. (unlock-package :sb-impl) (in-package :sb-impl) (defun custom-eval-in-lexenv (original-exp lexenv) (declare (optimize (safety 1))) ;; (aver (lexenv-simple-p lexenv)) (incf *eval-calls*) (sb-c:with-compiler-error-resignalling (let ((exp (macroexpand original-exp lexenv))) (handler-bind ((eval-error (lambda (condition) (error 'interpreted-program-error :condition (encapsulated-condition condition) :form exp)))) (typecase exp (symbol (ecase (info :variable :kind exp) ((:special :global :constant :unknown) (symbol-value exp)) ;; FIXME: This special case here is a symptom of non-ANSI ;; weirdness in SBCL's ALIEN implementation, which could ;; cause problems for e.g. code walkers. It'd probably be ;; good to ANSIfy it by making alien variable accessors ;; into ordinary forms, e.g. (SB-UNIX:ENV) and (SETF ;; SB-UNIX:ENV), instead of magical symbols, e.g. plain ;; SB-UNIX:ENV. Then if the old magical-symbol syntax is to ;; be retained for compatibility, it can be implemented ;; with DEFINE-SYMBOL-MACRO, keeping the code walkers ;; happy. (:alien (sb-alien-internals:alien-value exp)))) (list (let ((name (first exp)) (n-args (1- (length exp)))) (case name ((function) (unless (= n-args 1) (error "wrong number of args to FUNCTION:~% ~S" exp)) (let ((name (second exp))) (if (and (legal-fun-name-p name) (not (consp (let ((sb-c:*lexenv* lexenv)) (sb-c:lexenv-find name funs))))) (%coerce-name-to-fun name) ;; FIXME: This is a bit wasteful: it would be nice to call ;; COMPILE-IN-LEXENV with the lambda-form directly, but ;; getting consistent source context and muffling compiler notes ;; is easier this way. (%simple-eval original-exp lexenv)))) ((quote) (unless (= n-args 1) (error "wrong number of args to QUOTE:~% ~S" exp)) (second exp)) (setq (unless (evenp n-args) (error "odd number of args to SETQ:~% ~S" exp)) (unless (zerop n-args) (do ((name (cdr exp) (cddr name))) ((null name) (do ((args (cdr exp) (cddr args))) ((null (cddr args)) ;; We duplicate the call to SET so that the ;; correct value gets returned. (set (first args) (simple-eval-in-lexenv (second args) lexenv))) (set (first args) (simple-eval-in-lexenv (second args) lexenv)))) (let ((symbol (first name))) (case (info :variable :kind symbol) (:special) (t (return (%simple-eval original-exp lexenv)))) (unless (type= (info :variable :type symbol) *universal-type*) ;; let the compiler deal with type checking (return (%simple-eval original-exp lexenv))))))) ((progn) (simple-eval-progn-body (rest exp) lexenv)) ((eval-when) ;; FIXME: DESTRUCTURING-BIND returns ARG-COUNT-ERROR ;; instead of PROGRAM-ERROR when there's something wrong ;; with the syntax here (e.g. missing SITUATIONS). This ;; could be fixed by hand-crafting clauses to catch and ;; report each possibility, but it would probably be ;; cleaner to write a new macro ;; DESTRUCTURING-BIND-PROGRAM-SYNTAX which does ;; DESTRUCTURING-BIND and promotes any mismatch to ;; PROGRAM-ERROR, then to use it here and in (probably ;; dozens of) other places where the same problem ;; arises. (destructuring-bind (eval-when situations &rest body) exp (declare (ignore eval-when)) (multiple-value-bind (ct lt e) (sb-c:parse-eval-when-situations situations) ;; CLHS 3.8 - Special Operator EVAL-WHEN: The use of ;; the situation :EXECUTE (or EVAL) controls whether ;; evaluation occurs for other EVAL-WHEN forms; that ;; is, those that are not top level forms, or those ;; in code processed by EVAL or COMPILE. If the ;; :EXECUTE situation is specified in such a form, ;; then the body forms are processed as an implicit ;; PROGN; otherwise, the EVAL-WHEN form returns NIL. (declare (ignore ct lt)) (when e (simple-eval-progn-body body lexenv))))) ((locally) (simple-eval-locally (rest exp) lexenv)) ((macrolet) (destructuring-bind (definitions &rest body) (rest exp) (let ((sb-c:*lexenv* lexenv)) (sb-c::funcall-in-macrolet-lexenv definitions (lambda (&optional funs) (simple-eval-locally body sb-c:*lexenv* :funs funs)) :eval)))) ((symbol-macrolet) (destructuring-bind (definitions &rest body) (rest exp) (let ((sb-c:*lexenv* lexenv)) (sb-c::funcall-in-symbol-macrolet-lexenv definitions (lambda (&optional vars) (simple-eval-locally body sb-c:*lexenv* :vars vars)) :eval)))) ((if) (destructuring-bind (test then &optional else) (rest exp) (eval-in-lexenv (if (eval-in-lexenv test lexenv) then else) lexenv))) ((let let*) (%simple-eval exp lexenv)) (t (if (and (symbolp name) (eq (info :function :kind name) :function)) (collect ((args)) (dolist (arg (rest exp)) (args (eval-in-lexenv arg lexenv))) (apply (symbol-function name) (args))) (%simple-eval exp lexenv)))))) (t ;;Unlike the default SBCL eval, we inject our custom-eval here. ;;This allows types to define custom evaluation semantics, e.g. ;;for data literals, otherwise, it behaves exactly like original ;;eval and returns the type. (clclojure.eval:custom-eval exp))))))) ; something dangerous (in-package :clclojure.eval) (lock-package :sb-impl) (defun enable-custom-eval () (with-packages-unlocked (:sb-impl :sb-int) (setf (symbol-function 'SB-IMPL::simple-eval-in-lexenv) (symbol-function 'SB-IMPL::custom-eval-in-lexenv))) ; something dangerous ) (defun disable-custom-eval () (with-packages-unlocked (:sb-impl :sb-int) (setf (symbol-function 'SB-IMPL::simple-eval-in-lexenv) +original-eval+) ; something dangerous t))
8,702
Common Lisp
.lisp
172
33.866279
90
0.506164
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
552b2580bdb55ebdc00632c8061f10c8f4af6a5982fded8912eb1189e84b13eb
407
[ -1 ]
408
variadic.lisp
joinr_clclojure/dustbin/variadic.lisp
(ql:quickload :clclojure) (defpackage :clclojure.variadic (:use :common-lisp :clclojure.base) (:shadowing-import-from :clclojure.base :deftype :let)) (in-package :clclojure.variadic) ;;we need to determine the arity of the function... ;;For single arity, current approach works fine. ;;For multiple/variadic... ;;We need more information. ;;Perhaps a higher level generic function? ;;two-layers of type specialization. ;;Generic function dispatches on ;;arg-count, type of first arg ;; (manytest 1) ;; invokes specialization ;; (many :: manytest args) ;; (manytest 2) ;;protocol -> one or more proto functions. ;; protocol :: proto-fn* ;; proto-fn:: proto-method+ ;; proto-method :: proto-body+ ;; proto-body :: type -> args -> something (arities? proto-fn) ;;should be able to determine concrete arities... ;;functions are registered, along with their arities somewhere... ;;if more than one arity, need a dispatch-fn. ;;dumb solution:: (defun generic-dispatch (obj &rest args) (case (count args) 0 (0-arity obj) 1 (apply 1-arity obj args) 2 (apply 2-arity obj args) ;;variadic? (apply variadic obj ,@args) )) (def sat? (clclojure.protocols::protocol-satisfier IMany)) (def spec '(IMANY (MANY [OBJ] [OBJ MSG]))) ;;our satisfier works.... ;;detects no set difference in the functions implemented. ;;bet we have (def newspec '(IMANY (MANY [THIS] :SINGLE) (MANY [THIS THAT] THAT))) [many {0 many-1 1 many-2 2 many-3 :variadic many-v } ] (defgeneric many (obj &rest args)) ;;need to look at recur as well.. ;;need a named lambda. ;;in the case of recur, the recur point is ;;the named lambda. ;;We make the function name available.... (let ((many-1 (lambda (this) :single)) (many-2 (lambda (this that) that ))) (defmethod many ((obj some-type) &rest args) (case (count args) ;;only valid cases 1 (apply #'many-1 args) 2 (apply #'many-2 args) ;;else we ditch if there's not a variadic form! ) )) (generic-fn* many ((this) ;;1 (this that) ;;2 (this that else &rest args) ;;:variadic )) ;;one quick and dirty way to track information ;;about our generic function, without having to ;;create a wrapper class, is to maintain ;;a registry of info... (defun qualified-name (s) (common-utils::symb (str (package-name *package*) "/" (symbol-name s)))) (defparameter *metabase* (make-hash-table :test 'eq)) ;;register the generic-fn (defun push-meta! (name meta) (let ((k (qualified-name name))) (setf (gethash k *metabase*) meta))) (defun get-meta! (name) (gethash (qualified-name name) *metabase*)) (defun variadic? (arglist) (find '&rest arglist) ) (defun compare-arity (l r) (let ((lv (variadic? l)) (rv (variadic? r))) (if (not (and lv rv)) (< (length l) (length r)) (if lv t nil)))) (define-condition arglist-error (error) ((text :initarg :text :reader text) (data :initarg :data :reader data)) (:report (lambda (condition stream) (format stream "bad arglists: ~a reason: ~a" (data condition) (text condition))))) ;;invariants: ;;only one variadic arg.... ;;unique arities for each other arity... ;;variadic arg must have more concrete args than the largest arglist. (defun validated-arglists (arglists) (labels ((aux (acc remaining) (if (null remaining) acc (let* ((xs (first remaining)) (l (first xs)) (r (second xs))) (cond ((and (second l) ;;vararg lesser arity than nonvar (second r)) (error 'arglist-error :text "only one variadic arity allowed!" :data `(,(first (last l)) ,(first (last r))))) ((= (first l) (first r)) ;;identical nonvar arity (error 'arglist-error :text (if (second r) "identical arities!" "variadic arglist must have most concrete args") :data `(,(first (last l)) ,(first (last r))))) ((and (second l) ;;vararg lesser arity than nonvar (not (second r))) (error 'arglist-error :text "multiple arglists with same arity!" :data `(,(first (last l)) ,(first (last r))))) (t (aux acc (rest remaining)))))))) (let ((sorted (sort arglists #'compare-arity))) (common-utils::->> sorted (mapcar (lambda (args) (let ((var (variadic? args))) (list (- (length args) (if var 1 0)) var args)))) ((lambda (xs) (common-utils::partition! 2 xs :offset 1))) (aux sorted))))) ;;we want to store the arglists for the generic function as meta data ;;{:arities {0 () 1 (x) 2 (x y) :variadic (x y &rest zs)} ;;for now, we'll do an assoc list. (defun arglist-meta (arglists) (mapcar (lambda (args) (list (if (variadic? args) :variadic (length args)) args)) arglists)) ;;constraints: ;;only one variadic body ;;discrete args must be > non-variadic definitions... (defmacro generic-fn* (name &rest args) (let ((gf (gensym "genfun")) (arglists (gensym "arglists"))) `(let ((,arglists (validated-arglists (quote ,args))) (,gf (defgeneric ,name (,'obj &rest ,arglists)))) (progn (push-meta! (quote ,name ) (arglist-meta ,arglists)) ,gf) ))) ;;a, generic function with n bodies. ;;we need to track that information? ;;internal implementation detail.... (generic-methods* many ;gen-fn name some-type ((this) :single) ((this that) that) ((this that else &rest args) else)) ;;we need to lookup the meta for the name. ;;then match the methods to the arities... (defun methods->arities (ms) ) (defmacro generic-methods* (name specializer &rest methods) (let ((obj (gensym "obj")) (args (gensym "args")) (bodies (get-meta! name)) ) `(let ((many-1 (lambda (this) :single)) (many-2 (lambda (this that) that ))) (defmethod ,name ((,obj ,specializer) ,'&rest ,args) (case (count ,args) ;;only valid cases 1 (apply #'many-1 args) 2 (apply #'many-2 args) ;;else we ditch if there's not a variadic form! ) ))) ) ;;moved from base.... ;;Experimentation with function objects... ;;These may be more desireable than the symbol + lambda ;;approach I've been taking, since we can pack info ;;onto the slots... (comment ;;a function object... (defclass fob () ((name :initarg :name :accessor fob-name) (args :initarg :args :accessor fob-args) (body :initarg :body :accessor fob-body) (func :accessor fob-func) (meta :initarg :meta :accessor fob-meta)) (:metaclass sb-mop::funcallable-standard-class)) (defparameter spec nil) (defmethod initialize-instance :after ((f fob) &key) (with-slots (name args body func) f (let ((argvec args ;(apply #'persistent-vector args) )) (setf spec (list argvec body)) (setf func (eval `(fn ,argvec ,body))) (sb-mop::set-funcallable-instance-function f func)))) (setq f1 (make-instance 'fob :name "plus" :meta [] :args '[x y] :body '(+ x y) ))) (comment (defclass constructor () ((name :initarg :name :accessor constructor-name) (fields :initarg :fields :accessor constructor-fields)) (:metaclass sb-mop::funcallable-standard-class)) (setq c1 (make-instance 'constructor :name 'position :fields '(x y)))) (comment ;;clojure-like let... (eval `(let* ((,'f ,(fn [k] (+ k 1))) (,'n 2)) (declare (special ,'f)) (unify-values ,'f) (,'f ,'n))) ;;we have to declare vars special to use them in ;;a let context ala clojure, so that we can unify ;;the symbols. (defun specials (vars) `(,@(mapcar (lambda (v) `(declare (special ,v))) vars))) ;;Our let macro will just defer to this.... (defmacro clj-let (binds &rest body) (let ((bs (vector-to-list binds)) (vars (mapcar ))))) )
9,305
Common Lisp
.lisp
235
29.723404
130
0.538598
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f45944107c7c4457eaa32903a04e6128070cdcde287ab0a2d1639613cd04b2b8
408
[ -1 ]
410
example.lisp
joinr_clclojure/dustbin/example.lisp
(ql:quickload :clclojure) ;;we'll eventually morph this ;;into an ns call somehow.... (defpackage :clclojure.example (:use :common-lisp :clclojure.base) (:shadowing-import-from :clclojure.base :deftype :let)) (in-package :clclojure.example) ;;we have persistent vectors, which will ;;be replaced by bootstrapped variants from ;;clclojure.base... ;;some clojure-0 expressions demonstrating ;;fundamentals of the language primitives... ;;def and defn export by default, ;;also unify the function and symbol ;;namespaces. Working on metadata and ;;reader support... (def v [1 2 3]) ;;some core protocol stuff... (clclojure.base::-conj v 4) ;;=> [1 2 3 4] (clclojure.base::-count v) ;;=> 3 ;;fn - single-arity, no meta, no destructuring (def f (fn [x] (+ x 2))) ;;naive defn (no meta, no destructuring) (defn plus [x y] (+ x y)) (plus 1 2) ;;=> 3 (defprotocol IBlah (blah [obj])) (defprotocol IBlee (blee [obj msg])) (deftype blather [name x] IBlah (blah [this] (str :blaH! name x))) (def the-blather (->blather :joinr "blech!!!")) (blah the-blather) ;;gives us ":BLAH!:JOINRblech!!!" ;;reify works....under current single arity limitations ;;we generate effectively an anonoymous, throwaway ;;CLOS class via deftype, letting deftype do the work.. ;;Note: we get warnings about being unable to find ;;the specializer class for the reified class, ;;need to check that out, may be missing a quote. ;;It works tho! (def the-blither (let [msg "HOHOHO, MEEERRRRYY REIFY"] (reify IBlah (blah [this] msg) IBlee (blee [this custom-msg] (str "custom! " custom-msg) )))) (blah the-blither) ;;gives us "HOHOHO, MEEERRRRYY REIFY" (blee the-blither "Honk!") ;;gives us "custom! Honk!" ;;protocols are just structs.... IBlah ;; #S(CLCLOJURE.PROTOCOLS::PROTOCOL ;; :NAME IBLAH ;; :FUNCTIONS (BLAH) ;; :SATISFIER #<CLOSURE (LAMBDA (CLCLOJURE.PROTOCOLS::NEWSPEC) ;; :IN ;; CLCLOJURE.PROTOCOLS::MAKE-SATISFIER) {10074575AB}> ;; :MEMBERS (REIFY1 BLATHER)) ;;On the cusp of greatness, but still ;;debuggin multiple arities! So close.... ;; (defn idx [v n] ;; (-nth v n)) ;;quasiquoting of literals now works... (defparameter quasi-form `[,@(list 1 2 ) ,x ,@(list :literal x :hah) [,x ,x ,x [x] {:a 2 :b {:unquote ,x} :c {:quoted x}}]]) ;;[1 2 2 :LITERAL 2 :HAH [2 2 2 [X] {:C {:QUOTED X} :B {:UNQUOTE 2} :A 2}]] (let [x 2 y `[1 ,x 2 [3 4 ,@[1 2]]]] y) ;;coming soon... ;;meta, destrutcturing, core clojure functions ;;per cljs, and more... ;;loop/recur (maybe not necessary since we can compile ;;on most implementations and get TCO) ;;Working on variadic protocol implementations, ;;will be addressed in clclojure.variadic (defprotocol IMany (many [obj] [obj msg])) ;;currently broken, close to fixing... (deftype manytest [] IMany (many [this] :one!) (many [this item] item)) ;;error in vector, vector args aren't being evaluated. (defn test-my-scope [] (let [hello :hello world :world k 2 inc (fn [x] (+ x 1)) add (fn [x y] (+ x y)) tbl (let [tbl (make-hash-table)] (setf (gethash :hello tbl) "World") (setf (gethash :world tbl) "Hello") (setf (gethash :k tbl) k) tbl)] (list (hello tbl) (world tbl) (add (inc 39) k) (gethash :k tbl) ;;(:k tbl);;WIP ))) ;;EXAMPLE> (test-my-scope) ;;("World" "Hello" 42 2) ;;named functions don't currently parse! ;;This fails too, we have some jank with the ;;reader when we're inside a macro... ;;Need to fix the quasi quoter, should ;;be in backtick.lisp. (defn test-arities [] (let [sum (fn ([x] x) ([x y] (+ x y)) ([x y &rest zs] (reduce #'+ zs :initial-value (+ x y))))] (clclojure.pvector:persistent-vector (sum 1) (sum 1 2) (sum 1 2 3 4 5 6))))
3,958
Common Lisp
.lisp
128
27.460938
79
0.634448
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
761535bbd9501f8b395aaff7eaf80864ee990d8203251ed9c70e794d548d5dfb
410
[ -1 ]
411
lexical.lisp
joinr_clclojure/dustbin/lexical.lisp
;;Defining lexically scoped, unified variables and ;;functions with keyword access. (defpackage :clclojure.lexical (:use :common-lisp :clclojure.keywordfunc :common-utils) (:export :unified-let*)) (in-package :clclojure.lexical) ;;if the arg can be construed as a function, ;;the lexical symbol should be unified.. ;; (defmacro unify-binding (var) ;; `(cond ((functionp ,var) ;; (setf (symbol-function (quote ,var)) ;; ,var)) ;; ((keywordp ,var) ;; (if (not (keyfn? ,var)) ;; (progn (pprint (format nil "adding keyword access for: ~a " k )) ;; (eval (key-accessor ,var))))))) ;;we need to use let and flet instead of this... ;; (defmacro unify-binding (var) ;; `(cond ((functionp ,var) ;; (setf (symbol-function (quote ,var)) ;; ,var)) ;; ((keywordp ,var) ;; (if (not (keyfn? ,var)) ;; (progn (pprint (format nil "adding keyword access for: ~a " ,var )) ;; ;;(eval (key-accessor ,var)) ;; (setf (symbol-function (quote ,var)) ;; (->keyaccess ,var)) ;; ))))) ;;a couple of notes on evaluation and symbol/function namespaces, ;;including lexical scope.... ;;we have a few cases to cover... ;;if we want to cover every possible case and get a lisp1, ;;in the lexical case, we are relegated to using a combination ;;of let and flet on all the symbols ;; (let* ((g (->keyaccess :a)) ;; (lookup (->keyaccess :b))) ;; (labels ((g (arg) (funcall (keyaccess-func g) arg)) ;; (lookup (arg) (funcall (keyaccess-func lookup) arg))) ;; ;;(mapcar f (list keyfns keyfns)) ;; (pprint (list :obj lookup :fn (g keyfns))))) ;;this is an example of how we can play with lexical binds... ;;In the extreme case, we may not know what any types are, ;;which means they're functions or objects.... ;; (defun some-fn (z) ;; (let* ((g (lambda (x) (+ x 5))) ;;an actual function object... ;; (lookup (->keyaccess :b)) ;; (z (if (keywordp z) ;; (->keyaccess z) ;; z))) ;;keyword access function object... ;; (labels (;;general implementation of fn ;; (g (&rest args) (apply g args)) ;; ;;specific implementation for kw lookup.. ;; (lookup (arg) (funcall (keyaccess-func lookup) arg)) ;; (z (&rest args) (apply z args)) ;; ) ;; (pprint (list :obj g :fn (g 2) :keyaccess lookup ;; :z z :z-lookup (z keyfns) ;; (mapcar (lambda (x) (list :type x (type-of x))) ;; (list g lookup z))))))) ;;the only things that we know... are keywords, or fn forms bindings ;;are already in pairs... ;;Scrape the bindings to let*, and if we find keywords, ;;create an alist that associates the keyword to an ;;expression that defines a labels lexical function ;;for the keyword accessor. We compute/construct ;;a keyaccessor at compile time, and though it's ;;funcallable, we lookup its associated function ;;for use (and efficiency). We then provide ;;a simple function wrapper that invokes the keyword ;;fn (bear in mind, this is setfable). (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) (defun keyword-accessors (bindings) (let ((arg (gensym "lookup"))) (mapcar (lambda (lr) (destructuring-bind (l r) lr (let ((f (keyaccess-func (->keyaccess r)))) (list r `(,l (,arg) (funcall (->keyaccess ,r) ,arg)))))) (filter (lambda (lr) (keywordp (second lr))) bindings)))) ;;we use a generic apply here... collect all the args into a list and ;;apply. In clojure, there's some cost to that. Dunno what the ;;overhead is in CL. Also, if we "know" anything about the function, ;;we may be able to do some analysis and compile a more efficient ;;binding form (i.e. known number of args in the lambda. or simple ;;funcall... ;;There's some question about how much we know about the parameters at ;;runtime (specifically for let bindings). For certain classes of ;;lexical environments, we may be a-okay doing significant analysis of ;;what's involved in the let (case in point: if it's a lambda or a ;;known function we have meta on, we can derive types / args). Thats ;;a future optimization... ;;Note: if we don't refer to the lexical vars (NOT fns) for the ;;keywords, we end up with a slew of style warnings, since they don't ;;appear to be used (they are used for the lexical keyaccessors ;;though). To prevent this, we define a dummy function (never ;;invoked) that builds a list composed from the symbol-values. For ;;now, it's convenient. I may revisit this to see if we can detect if ;;the symbols aren't validly used... ;;we get compiler complaints with this if we don't... (defun functionize-bindings (bindings) (let* ((kwalist (keyword-accessors bindings)) (vars (mapcar (lambda (lr) (first (second lr))) kwalist)) (dummy (gensym "dummyfn"))) (cons `(,dummy () (list :this-prevents-warnings-nothing-else ,@vars)) (mapcar (lambda (lr) (destructuring-bind (l r) lr (if (keywordp r) (second (assoc r kwalist)) `(,l (,'&rest ,'args) (apply ,l ,'args))))) bindings))))) ;;so at the lexical level, we need to analyze the bindings. ;;determine if an item is a function (or an applicable object like ;;a keyword), and create matching labels for them... ;;this acts like let*, except it allows bindings that may be functions ;;or things that can act like functions -> keywords. Everything else ;;should be covered by a funcallable object... We unify the ;;symbol-value and symbol-function namespaces in the lexical context, ;;detecting the need to generate keyword accessors. (defmacro unified-let* (bindings &rest body) `(let* (,@bindings) (labels (,@ (functionize-bindings bindings) ) ,@body))) ;;a simple test function to tie everything together. (defun test-my-scope () (unified-let* ((hello :hello) ;;we create (or lookup cached) keyaccess funcallable objects (world :world) ;;when we have literal keywords bound to symbols. (k 2) (inc (lambda (x) (+ x 1))) (add (lambda (x y) (+ x y))) (tbl (unified-let* ((tbl (make-hash-table))) (setf (gethash :hello tbl) "World") (setf (gethash :world tbl) "Hello") (setf (gethash :k tbl) k) tbl))) (list (hello tbl) (world tbl) (add (inc 39) k) ;;(:k tbl) ;;doesn't work without some extra macro magic... (funcall (->keyaccess :k) tbl) ;;it will look like this behind the scenes. ))) ;;LEXICAL> (test-my-scope) ;;("World" "Hello" 42 2) ;;works!
7,375
Common Lisp
.lisp
144
44.993056
96
0.578181
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
b7209526c29c9c9ca5c02bf6a523f285374b9072c32e8f4f3efe7b3fc5e24e95
411
[ -1 ]
412
reader.lisp
joinr_clclojure/dustbin/reader.lisp
;;A package for defining read table extensions ;;for clojure data structures. ;;Pending.................. (defpackage :clclojure.reader (:use :common-lisp :common-utils :named-readtables :clclojure.pvector :clclojure.cowmap) (:export :*literals* :*reader-context* :quoted-children :quote-sym :literal?)) (in-package :clclojure.reader) (comment (defconstant +left-bracket+ #\[) (defconstant +right-bracket+ #\]) (defconstant +left-brace+ #\{) (defconstant +right-brace+ #\}) (defconstant +comma+ #\,) (defconstant +colon+ #\:) (defconstant +at+ #\@) (defconstant +tilde+ #\~)) (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;;Problem right now is that, when we read using delimited-list, ;;we end up losing out on the reader literal for pvecs and the like... ;;When we have quoted ;;we can use a completely custom reader...perhaps that's easiet.. ;;Have to make this available to the compiler at compile time! ;;Maybe move this into a clojure-readers.lisp or something. ;;alist of literals... (defparameter *literals* '(list) ; '(list cons) ) (defparameter *reader-context* :read) ;;default quote...o ;; (comment ;; (set-macro-character #\' ;; #'(lambda (stream char) ;; (declare (ignore char)) ;; `(quote ,(read stream t nil t))))) (defun quote-sym (sym) (list 'quote sym)) ;`(quote ,sym) ;; (defmacro quoted-children (c) ;; `(,(first c) ,@(mapcar #'quote-sym (rest c)))) (defun dotted-pair? (xs) (and (listp xs) (not (listp (cdr xs))))) (defun literal? (s) (or (and (listp s) (find (first s) *literals*)) (and (symbolp s) (find s *literals*)))) (defmacro quoted-children (c) `(,(first c) ,@(mapcar (lambda (s) (cond ((literal? s) ;;we need to recursively call quoted-children.. `(quoted-children ,s)) ((dotted-pair? s) `(quote ,s)) ((listp s) `(quoted-children ,(cons (quote list) s))) (t (funcall #'quote-sym s)))) (rest c)))) ;;Enforces quoting semantics for literal data structures.. (defmacro clj-quote (expr) (cond ((literal? expr) `(quoted-children ,expr)) ((dotted-pair? expr) `(quote ,expr)) ((listp expr) `(quoted-children ,(cons (quote list) expr))) (t (quote-sym expr)))) (defun as-char (x) (cond ((characterp x) x) ((and (stringp x) (= 1 (length x))) (char x 0)) ((symbolp x) (as-char (str x))) (t (error (str (list "invalid-char!" x) )))) ) ;;Gives us clj->cl reader for chars... (set-macro-character #\\ #'(lambda (stream char) (declare (ignore char)) (let ((res (read stream t nil t))) (as-char res))) ) ;;Doesn't work currently, since we can't redefine ;;print-method for chars... (defun print-clj-char (c &optional (stream t)) "Generic char printer for clojure-style syntax." (format stream "\~c" c)) (defun print-cl-char (c &optional (stream t)) "Generic char printer for common lisp syntax." (format stream "#\~c" c)) (comment (defmethod print-object ((obj standard-char) stream) (print-clj-char obj stream))) (defun quoted-read (stream char) (declare (ignore char)) (let ((res (read stream t nil t))) (if (atom res) `(quote ,res) `(clj-quote ,res)))) ;;This should be consolidated... (set-macro-character #\' #'quoted-read) ;;need to define quasiquote extensions... ;;quasiquoting has different behavior for literal datastructures.. ;;in the case of clojure, we provide fully-qualified symbols vs. ;;standard CL-symbols. We have reader support for them, ;;that is, blah/x vs x. ;;so, clojure resolves the symbol in the current ns, at read-time. (defun resolved-symbol (s) (let* ((this-package (package-name *package*))) (multiple-value-bind (x y) (find-symbol (symbol-name s)) (if x ;;symbol exists `(,(package-name (symbol-package x)) ,(symbol-name x)) `(,this-package ,(symbol-name s)) )))) (defun qualify (s) (apply #'common-utils::symb (let ((res (resolved-symbol s))) (list (first res) "::" (second res))))) (defun quasi-quoted-read (stream char) (declare (ignore char)) (let ((res (read stream t nil t))) (cond ((symbolp res) (let ((resolved ))) `(quote ,res)) (t `(clj-quote ,res))))) ;;Additionally, for dataliterals, quasiquote serves as a template ;;for building said datastructure, as if by recursively quasiquoting ;;elements in the expression. ;;Additionally, clojure ;;we can get package-qualified symbols via: ;;`(common-lisp-user::x) ;;but they print as 'x ;;s.t. `[x y] ;;namespace-qualified symbols are kind of out of bounds at the ;;moment... (defun push-reader! (literal ldelim rdelim rdr) (progn (setf *literals* (union (list literal) *literals*)) (set-macro-character ldelim rdr) (set-syntax-from-char rdelim #\)))) (defun quoting? () (> sb-impl::*backquote-depth* 0)) ;;This now returns the actual pvector of items read from ;;the stream, versus a quoted form. Should work nicely ;;with our protocol definitions now! ;;The issue we run into with our EDN forms is this: ;;(defparameter x 2) ;;(eval [x]) ;;should yield [2] ;;we don't currently. ;;So, ;;Quasiquoting custom data literals.. ;;=================================== ;;THis is way janky... ;;I'm not afraid to say I don't know how I pulled this off. ;;The key is that the quasiquoting mechanism in backq.lisp ;;has a sb-int:comma struct to denote 3 kinds of commas: ;;0 -> ,x ;;1 -> ,.x ;;2 -> ,@x ;;We ignore the dot version for now, although it's probably simple ;;enough to get working. ;;So we just manually build the expression. ;;If it's not a comma, we quasiquote it and let the macroexpander ;;figure it out. (defun quasify (xs) (nreverse (reduce (lambda (acc x) x (if (sb-int:comma-p x) (let ((expr (sb-int:comma-expr x))) (case (sb-int:comma-kind x) (0 (cons expr acc)) (2 (reduce (lambda (a b) (cons b a)) (eval expr) :initial-value acc)) (1 (error "comma-dot not handled!")))) (cons (list 'sb-int:quasiquote x) acc))) xs :initial-value '()))) ;;Original from Stack Overflow, with some slight modifications. ;;Have to make this available to the compiler at compile time! ;;Maybe move this into a clojure-readers.lisp or something. ;;We need to modify this. It implicity acts like quote for ;;symbols, since we're using read-delimited-list. (defun |bracket-reader| (stream char) "A reader macro that allows us to define persistent vectors inline, just like Clojure." (declare (ignore char)) (if (not (quoting?)) (apply #'persistent-vector (read-delimited-list #\] stream t)) (eval `(persistent-vector ,@(quasify (read-delimited-list #\] stream t)))))) ;;Original from Stack Overflow, with some slight modifications. (defun |brace-reader| (stream char) "A reader macro that allows us to define persistent maps inline, just like Clojure." (declare (ignore char)) (if (not (quoting?)) (apply #'persistent-map `(,@(read-delimited-list #\} stream t))) (eval `(persistent-map ,@(quasify (read-delimited-list #\} stream t)))))) (set-macro-character #\{ #'|brace-reader|) (set-syntax-from-char #\} #\)) ;;this is for not just reading, but evaluating as well... ;;in theory, the default reader function will suffice for ;;quoted or unevaluated forms. We will need to evaluate ;;our args otherwise.... ;; (defun |bracket-reader| (stream char) ;; "A reader macro that allows us to define persistent vectors ;; inline, just like Clojure." ;; (declare (ignore char)) ;; (eval `(apply #'persistent-vector (list ,@(read-delimited-list #\] stream t))))) ;;TODO move to named-readtable (push-reader! 'persistent-vector #\[ #\] #'|bracket-reader|) ;;TODO move to named-readtable (push-reader! 'clclojure.pvector:persistent-vector #\[ #\] #'|bracket-reader|) (comment (set-macro-character #\[ #'|bracket-reader|) (set-syntax-from-char #\] #\)) ;;This should be consolidated... (set-macro-character #\' #'(lambda (stream char) (let ((res (read stream t nil t))) (if (atom res) `(quote ,res) (case (first res) (persistent-vector `(quoted-children ,res))) )))))) (comment ;;WIP, moving to more elegant solution from named-readtables.... ;; (defreadtable clojure:syntax ;; (:merge :standard) ;; (:macro-char #\[ #'|bracket-reader| t) ;; (:case :preserve)) ) ;; (comment (defun |brace-reader| (stream char) ;; "A reader macro that allows us to define persistent vectors ;; inline, just like Clojure." ;; (declare (ignore char)) ;; `(persistent-vector ,@(read-delimited-list #\] stream t))) ;; (set-macro-character #\{ #'|brace-reader|) ;; (set-syntax-from-char #\} #\)) ;; ;;standard quote dispatch ;; (set-macro-character #\' #'(lambda (stream char) ;; (list 'quote (read stream t nil t)))) ;; (set-macro-character #\' #'(lambda (stream char) ;; (let ((res (read stream t nil t))) ;; (case (first res) ;; ('persistent-vector 'persistent- )) ;; (list 'quote ))))) ;;https://gist.github.com/chaitanyagupta/9324402 ;;https://common-lisp.net/project/named-readtables/
10,619
Common Lisp
.lisp
234
37.423077
95
0.571512
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
252d036d9d3bb20280220be3347063649164d23b24bc5ac120e29690e19f0f5b
412
[ -1 ]
413
clclojure.lisp
joinr_clclojure/dustbin/clclojure.lisp
;;DEPRECATED ;;========= ;;see boostrap.lisp for current effort! ;;Retained for possible pedagogical/historical value.... ;;this is a simple set of utils I'd like to have around ;;to further my knowledge, I'll stick it in a package ;;using common lisp parlance. (load "pvector.lisp") (load "protocols.lisp") (defpackage :clojurecl (:use :common-lisp :clojure.protocol :clojure.pvector) (:export :take :drop :ndrop :take-while :drop-while :ndrop-while :filter :fold :partition :partition-offset :interleave :->> :-> :lazy :force :lazy-null :lazy-nil :lazy-car :lazy-cdr :lazy-cons :make-lazy :iterate) (:shadow :first :rest :cons)) ;:export -> names of stuff to export. (in-package :clojurecl) (defgeneric seq (x) (:documentation "Basic constructor for lazy sequences.") ;using protocols to implement library functionality ;now. ;; clojure.lang.ISeq ;; (first [self] (first a)) ;; (next [self] (next a)) ;; (more [self] (rest a)) ;; ;Ported from clojurescript compiler. Fundamental protocols. (defprotocol ICounted (-count [coll] "constant time count")) (defprotocol IEmptyableCollection (-empty [coll])) (defprotocol ICollection (-conj [coll o])) (defprotocol IOrdinal (-index [coll])) (defprotocol IIndexed (-nth [coll n] [coll n not-found])) (defprotocol ASeq) (defprotocol ISeq (-first [coll]) (-rest [coll])) (defprotocol INext (-next [coll])) (defprotocol ILookup (-lookup [o k] [o k not-found])) (defprotocol IAssociative (-contains-key? [coll k]) #_(-entry-at [coll k]) (-assoc [coll k v])) (defprotocol IMap #_(-assoc-ex [coll k v]) (-dissoc [coll k])) (defprotocol IMapEntry (-key [coll]) (-val [coll])) (defprotocol ISet (-disjoin [coll v])) (defprotocol IStack (-peek [coll]) (-pop [coll])) (defprotocol IVector (-assoc-n [coll n val])) (defprotocol IDeref (-deref [o])) (defprotocol IDerefWithTimeout (-deref-with-timeout [o msec timeout-val])) (defprotocol IMeta (-meta [o])) (defprotocol IWithMeta (-with-meta [o meta])) (defprotocol IReduce (-reduce [coll f] [coll f start])) (defprotocol IKVReduce (-kv-reduce [coll f init])) (defprotocol IEquiv (-equiv [o other])) (defprotocol IHash (-hash [o])) (defprotocol ISeqable (-seq [o])) (defprotocol ISequential "Marker interface indicating a persistent collection of sequential items") (defprotocol IList "Marker interface indicating a persistent list") (defprotocol IRecord "Marker interface indicating a record object") (defprotocol IReversible (-rseq [coll])) (defprotocol ISorted (-sorted-seq [coll ascending?]) (-sorted-seq-from [coll k ascending?]) (-entry-key [coll entry]) (-comparator [coll])) ;; (defprotocol ^:deprecated IPrintable ;; "Do not use this. It is kept for backwards compatibility with existing ;; user code that depends on it, but it has been superceded by IPrintWithWriter ;; User code that depends on this should be changed to use -pr-writer instead." ;; (-pr-seq [o opts])) ;; (defprotocol IWriter ;; (-write [writer s]) ;; (-flush [writer])) ;; (defprotocol IPrintWithWriter ;; "The old IPrintable protocol's implementation consisted of building a giant ;; list of strings to concatenate. This involved lots of concat calls, ;; intermediate vectors, and lazy-seqs, and was very slow in some older JS ;; engines. IPrintWithWriter implements printing via the IWriter protocol, so it ;; be implemented efficiently in terms of e.g. a StringBuffer append." ;; (-pr-writer [o writer opts])) (defprotocol IPending (-realized? [d])) (defprotocol IWatchable (-notify-watches [this oldval newval]) (-add-watch [this key f]) (-remove-watch [this key])) (defprotocol IEditableCollection (-as-transient [coll])) (defprotocol ITransientCollection (-conj! [tcoll val]) (-persistent! [tcoll])) (defprotocol ITransientAssociative (-assoc! [tcoll key val])) (defprotocol ITransientMap (-dissoc! [tcoll key])) (defprotocol ITransientVector (-assoc-n! [tcoll n val]) (-pop! [tcoll])) (defprotocol ITransientSet (-disjoin! [tcoll v])) (defprotocol IComparable (-compare [x y])) (defprotocol IChunk (-drop-first [coll])) (defprotocol IChunkedSeq (-chunked-first [coll]) (-chunked-rest [coll])) (defprotocol IChunkedNext (-chunked-next [coll])) (defprotocol ISeq (first (s) "Returns the first element of a sequence.") (next (s) "Returns the next element of the sequence or nil") (more (s) "Returns the rest of sequence s as a lazy seq.")) ;(defprotocol IReduce...) ;Include lists and arrays.... (extend-protocol ISeq null (first (s) nil) (next (s) nil) (more (s) nil) cons (first (s) (common-lisp:first s)) (next (s) (common-lisp:rest s)) (more (s) (seq (common-lisp:rest s))) clojure.pvector::pvec (first (s) (nth-vec s 0)) (next (s) (subvec s 1)) (more (s) (seq (subvec s 1)))) ;; clojure.lang.IPersistentCollection ;; (seq [self] (if (seq a) self nil)) ;; (cons [self o] (Foo. a (conj b o))) ;; (empty [self] (Foo. [] [])) ;; (equiv ;; [self o] ;; (if (instance? Foo o) ;; (and (= a (.a o)) ;; (= b (.b o))) ;; false)) (defprotocol IPersistentCollection (seq (x) "Returns a lazy sequence of the input.") (cons (x y) "Returns a lazy sequence constructed from x and s.") (empty (x) "Determines if x is empty.") (equiv (x y) "Equality comparison between x and y.")) ;;borrowed shamelessly from Conrad Barksi's excellent ;;Land of Lisp....the definitive work on building lisp ;;games and being a better person! (defmacro lazy (&body body) "Creates a lazy value from v, returning a thunk'd function that, upon evaluation, caches the result." (let ((forced? (gensym)) (val (gensym))) `(let ((,forced? nil) (,val nil)) (lambda () (unless ,forced? (setf ,val (progn ,@body)) (setf ,forced? 't)) ,val)))) (defun force (lazy-value) "Ensures that any thunks are evaluated, thus providing the rich, tender values underneath. I added a quick function check to allow non-thunked values to be forced, for consistency...." (if (functionp lazy-value) (funcall lazy-value) lazy-value)) (defmacro lazy-cons (x y) "Creates a lazy cons-cell from x and y." `(lazy (cons ,x ,y))) (defun lazy-car (x) "Lazified version of car...note that since I generalized force, we can use it on either lazy or non-lazy lists." (car (force x))) (defun lazy-cdr (x) "Lazified version of cdr...again, since force can handle eager values, this works for any list." (cdr (force x))) (defun lazy-nil () (lazy nil)) (defun lazy-null (x) (not (force x))) (defprotocol ILazySeq (make-lazy (coll) "Converts collection into a lazy sequence.")) ;IChunkedSeq is a lot like subvec, in that it works in chunks. ;Basically, as we pull elements out of our chunked sequence, ;we return light wrapper objects that refer to the chunk. (defprotocol IChunkedSeq (chunked-first (coll) "Get the first lazy chunk") (chunked-next (coll) "Get the next lazy chunk") (chunked-more (coll) "Get the next lazy chunk")) (extend-protocol ILazySeq null (make-lazy (coll) nil) cons (make-lazy (coll) (lazy (when coll (cons (first coll) (make-lazy (rest coll))))))) ;; clojure.pvector:pvec ;; (make-lazy (coll) ;; (fn ;; (defgeneric make-lazy (lst)) ;; (defmethod make-lazy ((lst cons)) ;; "Converts a normal list into a lazy list." (defmacro ->> (x form &rest more) "Threading operator, identical to Clojure. Threads x as the last argument through form. If more forms are passed in, nests the threading, so that each preceding form is evaluated as the last form in next form." (if (null more) (if (atom form) (list form x) `(,(first form) ,@(rest form) ,x)) `(->> (->> ,x ,form) ,@more))) (defmacro -> (x form &rest more) "Threading operator, identical to Clojure. Threads x as the second argument through form. If more forms are passed in, nests the threading, so that each preceding form is evaluated as the second form in next form." (if (null more) (if (atom form) (list form x) `(,(first form) ,x ,@(rest form))) `(->> (->> ,x ,form) ,@more))) (defgeneric conj (x coll)) ;;(defmethod conj (x ;(defgeneric take (n l)) ;; (defmethod take (n (l cons)) ;; "Takes n elements from a list" ;; (do ((remaining l (rest remaining)) ;; (acc (list)) ;; (i n (decf i))) ;; ((or (= 0 i) (null remaining)) (nreverse acc)) ;; (push (first remaining) acc))) (defun take (n coll) "Takes n elements from a sequence." (do ((remaining l (rest remaining)) (acc [] () (i n (decf i))) ((or (= 0 i) (null remaining)) acc) (push (first remaining) acc))) (defun drop (n coll) "Drops the first n elements from a sequence." (do ((remaining l (rest remaining)) (acc nil) (i n (decf i))) ((null remaining) acc) (when (zerop i) (progn (setf acc (copy-list remaining)) (setf remaining nil))))) ;(defgeneric drop (n l)) ;; (defmethod drop (n (l cons)) ;; "Drops the first n elements from a list" ;; (do ((remaining l (rest remaining)) ;; (acc nil) ;; (i n (decf i))) ;; ((null remaining) acc) ;; (when (zerop i) ;; (progn (setf acc (copy-list remaining)) ;; (setf remaining nil))))) (defun ndrop (n l) "Drops the first n elements from a list. Returns the sublist of the inputlist, rather than accumulate a copy." (do ((remaining l) (i n (decf i))) ((or (= 0 i) (null remaining)) remaining) (when (not (zerop i)) (setf remaining (rest remaining))))) (defgeneric filter (f l)) (defmethod filter (f (l cons)) "Returns a new list l, for all elements where applications of f yield true." (do ((remaining l (rest remaining)) (acc (list))) ((null remaining) (nreverse acc)) (when (funcall f (first remaining)) (push (first remaining) acc)))) (defgeneric take-while (f l)) (defmethod take-while (f (l cons)) "Draws elements from a list while f yields true. Returns the resulting list." (do ((remaining l (rest remaining)) (acc (list))) ((null remaining) (nreverse acc)) (if (funcall f (first remaining)) (push (first remaining) acc) (setf remaining nil)))) (defgeneric drop-while (f l)) (defmethod drop-while (f (l cons)) "Draws elements from a list while f yields true. Returns the resulting list." (do ((remaining l (rest remaining)) (acc (list))) ((null remaining) acc) (when (not (funcall f (first remaining))) (progn (setf acc (copy-list remaining)) (setf remaining nil))))) (defun ndrop-while (f l) "Draws elements from a list while f yields true. Returns the resulting list. Impure." (do ((remaining l (rest remaining)) (acc nil)) ((null remaining) acc) (when (not (funcall f (first remaining))) (progn (setf acc remaining) (setf remaining nil))))) (defun fold (f init l) "A simple wrapper for reduce." (reduce f l :initial-value init)) (defgeneric partition (n l &key offset)) (defmethod partition (n (l cons) &key (offset n)) "Akin to partition from clojure. Builds a list of lists, where each list is size n elements." (do ((remaining l (ndrop offset remaining)) (acc (list))) ((null remaining) (nreverse acc)) (let ((nxt (take n remaining))) (if (= (length nxt) n) (push nxt acc) (setf remaining nil))))) (defun partition-offset (n offset l) "A form of partition, with adjustable offsetting that is friendly to the ->> threading macro." (partition n l :offset offset)) (defgeneric interleave (xs ys)) (defmethod interleave ((xs cons) (ys cons)) "Returns a list composed of interwoven values drawn from input lists xs and ys. Stops the interleaving process when either list is exhausted." (do ((left xs (rest left)) (right ys (rest right)) (acc nil)) ((or (null left) (null right)) (nreverse acc)) (progn (push (first left) acc) (push (first right) acc)))) (defun iterate (f init) "Produces a lazy sequence of results, where f is applied repeatedly, first to init, then to the result (f (f (f init)))" (let ((res (funcall f init))) (if res (lazy-cons res (iterate f res)) nil))) ;(lazy-cons 2 nil) ;(lazy-list 2) ;(lazy-list 2 3 4) -> (lazy-cons 2 (lazy-cons 3 (lazy-cons 4))) ;;(->> (list) ;; (mapcar #'1+)) ;;(mapcar #'1+ (list))
12,767
Common Lisp
.lisp
402
28.211443
80
0.660789
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
adf160c1082e58ad44f03a6c05e9ce0ab50d71685b5ce259c8d6a29fd5794da0
413
[ -1 ]
414
recurtest.lisp
joinr_clclojure/dustbin/recurtest.lisp
(defpackage common-utils.recurtest (:use :common-lisp :common-utils)) (in-package :common-utils.recurtest) ;;can we implement (recur ...) ? ;; (block some-name ;; (tagbody some-point ;; :dostuff ;; (when :recur ;; (progn (update-vars) ;; (go some-point)) ;; ) ;; ) ;; result) ;; (defun custom-loop (x) ;; (let ((res)) ;; (macrolet ((recur (xnew) ;; `(progn (setf ,'x ,xnew) ;; (pprint ,'x) ;; (go ,'recur-from)))) ;; (tagbody recur-from ;; (setf res ;; (if (= x 10) ;; x ;; (recur (1+ x))))) ;; res))) ;; (defmacro with-recur (args &rest body) ;; (let* ((recur-sym (intern "RECUR")) ;HAVE TO CAPITALIZE! ;; (local-args (mapcar (lambda (x) ;; (intern (symbol-name x))) args)) ;; (res (gensym "res")) ;; (recur-from (gentemp "recur-from")) ;; (recur-args (mapcar (lambda (x) (gensym (symbol-name x))) local-args ;; )) ;; (bindings (mapcar (lambda (xy) ;; `(setf ,(car xy) ,(cdr xy))) (pairlis local-args recur-args)))) ;; `(let ((,res)) ;; (tagbody ,recur-from ;; (flet ((,recur-sym ,recur-args ;; (progn ,@bindings ;; (go ,recur-from)) ;; )) ;; (setf ,res ,@body))) ;; ,res))) ;; (defmacro with-recur (args &rest body) ;; (let* ((recur-sym (intern "RECUR")) ;HAVE TO CAPITALIZE! ;; (local-args (mapcar (lambda (x) ;; (intern (symbol-name x))) args)) ;; (res (gensym "res")) ;; (recur-from (gentemp "recur-from")) ;; (recur-args (mapcar (lambda (x) (gensym (symbol-name x))) local-args ;; )) ;; (update-binds (gentemp "update-binds")) ;; (bindings (mapcar (lambda (xy) ;; `(setf ,(car xy) ,(cdr xy))) (pairlis local-args recur-args)))) ;; `(let ((,res)) ;; (flet ((,update-binds ,recur-args ;; (progn ,@bindings))) ;; (macrolet ((,recur-sym ,args ;; `(progn (,,update-binds ,,@args) ;; (go ,,recur-from))))) ;; (tagbody ,recur-from ;; (setf ,res ,@body))) ;; ,res))) ;; (with-recur (x 2) ;; (if (< x 4) ;; (recur (1+ x)) ;; x)) ;; (let ((continue? t) ;; (x 2) ;; (res) ;; (continue? nil)) ;; (flet ((recur (x) ;; (setf x x) ;; (setf continue? t))) ;; (tagbody recur-from ;; (progn ;; (setf res ;; (if (< x 4) ;; (recur (1+ x)) ;; x)) ;; (when continue? ;; (setf continue? nil) ;; (go recur-from)))) ;; res)) (comment ;;we can call simmary-tails on all these and get nil, ;;or some combination of (t, nil), (t, some-list-of illegal callsites) (defparameter normal-call `(if (= 2 3) :equal (progn (print :otherwise) :inequal))) (defparameter good-tail '(if (= 2 3) (recur 2) (recur 3))) (defparameter bad-tail '(progn (recur 2) 3)) (defparameter gnarly-bad-tail '(lambda (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (recur 44)) 2)))))) (defparameter gnarly-good-tail '(lambda (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (print 44)) 2)))))) ) ;(with-recur (x 2 y 3) (+ x y)) (with-recur (x 0) (if (< x 10) (recur (1+ x)) x)) (with-recur (x 0) (if (> x 9) x (recur (1+ x)))) (defun good-tail () (with-recur (x 2) (if (> x 5) x (if (= x 2) (recur 5) (recur (1+ x)))))) ;;not currently checked! (defun bad-tail () (with-recur () (progn (recur 2) 3))) (defun gnarly-bad-tail (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ x)) (progn (when (< 2 3) (recur 44)) 2))))) (defun gnarly-good-tail (x) (with-recur (acc x) (let ((blah 5) (blee 3)) (if (<= acc blah) (recur (1+ acc)) (progn (when (< 2 3) (print 44)) 2))))) ;;test function for sussing out the correct way to ;;handle recur forms with varargs... (defun tst () (flet ((blah (&rest args) (pprint :hobart) nil)) (macrolet ((recur (&whole whole-form &rest args) (let* ((frm (list* 'apply (list 'function 'blah) args))) (progn (pprint (list :expanding whole-form :to frm)) frm)))) (labels ((blah (x &rest xs) (pprint (list x xs)) (if (null xs) x (progn (pprint (macroexpand-1 `(recur (+ ,x (first ,xs)) (rest ,xs)))) (recur (+ x (first xs)) (rest xs)))))) #'blah)))) ;; ;;looking at using with-recur... ;; ;;possible naive way to inline using with-recur... ;; (defun blah (&rest xs) ;; (labels ((aux (&rest xs) ;; (macrolet ((blah (&rest args) ;; `(apply #'aux ,args))) ;; (case (length xs) ;; (1 (with-recur (x (first xs)) ;; (pprint x))) ;; (2 (with-recur (acc (first xs) ;; bound (second xs)) ;; (if (< acc bound) ;; (blah (+ acc 3) bound) ;; acc))) ;; (otherwise (with-recur ((x y &rest zs) xs) ;; (+ x y (apply #'+ zs)))))))) ;; (apply #'aux xs))) ;; (with-recur (x 2) ;; (if (< x 10) (recur (1+ x)) x)) ;; (LET ((#:|continuex764| T) (#:|res763|) (X 2)) ;; (FLET ((RECUR (#:X765) ;; (PROGN (SETF X #:X765) (SETF #:|continuex764| T)))) ;; (TAGBODY ;; |recur-from2| ;; (PROGN ;; (SETF #:|res763| ;; (IF (< X 10) ;; (RECUR (1+ X)) ;; X)) ;; (WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-from2|)))) ;; #:|res763|)) ;; (with-recur ((x &rest xs) xs) ;; (if (null zs) ;; (+ x y) ;; (recur (+ x y) ;; (first zs) ;; (rest zs)))) ;; (destructuring-bind (x y &rest zs) xs ;; (LET ((#:|continuex764| T) ;; (#:|res763|) ;; (arg-X x) ;; (arg-y y) ;; (rest-zs zs)) ;; (FLET ((RECUR (x y &rest zs) ;; (PROGN (SETF arg-X x) ;; (setf arg-y y) ;; (setf rest-zs zs) ;; (SETF #:|continuex764| T)))) ;; (TAGBODY ;; |recur-fromvar| ;; (PROGN ;; (SETF #:|res763| ;; (IF (< X 10) ;; (RECUR (1+ X)) ;; X)) ;; (WHEN #:|continuex764| (SETF #:|continuex764| NIL) (GO |recur-fromvar|)))) ;; #:|res763|))) ;;let's construct one from scratch.. (comment (defun blah (&rest xs) (let* ((blah-1 (named-fn blah-1 (x) (pprint x))) (blah-2 (named-fn blah-2 (acc bound) (if (< acc bound) (blah (+ acc 3) bound) acc))) (blah-variadic (named-fn blah-variadic (x y &rest zs) (+ x y (apply #'+ zs))))) (case (length xs) (1 (funcall blah-1 (first xs))) (2 (funcall blah-2 (first xs) (second xs))) (otherwise (apply blah-variadic xs) )))) ;;shouldn't blow the stack..but it does unless compiled. (defun blah (&rest xs) (let* ((blah-1 (named-fn blah-1 (x) (pprint x))) (blah-2 (named-fn blah-2 (acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc))) (blah-variadic (named-fn blah-variadic (x y &rest zs) (+ x y (apply #'+ zs))))) (case (length xs) (1 (funcall blah-1 (first xs))) (2 (funcall blah-2 (first xs) (second xs))) (otherwise (apply blah-variadic xs) )))) ) (comment ;;testing -this works. (defparameter f (named-fn* blah ((x) (pprint (list x)) x) ((x &rest xs) (if (null xs) (blah x) (recur (+ x (first xs)) (rest xs)))))) ) ;; (defmacro named-fn* (name &rest args-bodies) ;; (if (= (length args-bodies) 1) ;; (let ((args-body (first args-bodies))) ;; `(named-fn ,name ,(first args-body) ,(second args-body))) ;regular named-fn, no dispatch. ;; (destructuring-bind (cases var) (parse-dispatch-specs args-bodies) ;; (let* ((args (gensym "args")) ;; (funcspecs (mapcar (lambda (xs) ;; (destructuring-bind (n (args body)) xs ;; (let* ((fname (func-name name n)) ;; (fbody `(named-fn ,fname ,args ,body))) ;; (if (= n 0) ;; `(,n ,fname ,fbody) ;; `(,n ,fname ,fbody))))) cases)) ;; (varspec (when var ;; (let* ((fname (func-name name :variadic)) ;; (fbody `(named-fn ,fname ,(first var) ,(second var)))) ;; `(:variadic ,fname ,fbody)))) ;; (specs (if var (append funcspecs (list varspec)) funcspecs)) ;; (aux (gensym "aux")) ;; (dummy (gensym "stupid-var"))) ;; `(let ((,dummy nil) ) ;; (declare (ignore ,dummy)) ;; (macrolet ((,name (,'&rest ,'args) ;; (list 'apply (list 'function (quote ,aux)) (list* 'list ,'args)))) ;; (let (,@(mapcar (lambda (xs) `(,(second xs) ,(third xs))) ;; specs)) ;; (labels ((,aux (,'&rest ,args) ;; (case (length ,args) ;; ,@(mapcar (lambda (xs) (let ((n (first xs)) ;; (name (second xs))) ;; (if (= n 0) ;; `(,n (funcall ,name)) ;; `(,n (apply ,name ,args))))) funcspecs) ;; (otherwise ,(if var `(apply ,(second varspec) ,args) ;; `(error 'no-matching-args)))))) ;; (function ,aux))))))))) ;;testing (comment (defparameter e (named-fn* blah ((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc)) )) (defparameter f (named-fn* blah ((acc bound) (if (< acc bound) (recur (+ acc 3) bound) acc)) ((x &rest xs) (if (null xs) x (recur (+ x (first xs)) (rest xs)))) )) ;;we shouldn't need progn... (defparameter g (named-fn* blah ((x) (progn (pprint (list :blah-1 :result x)) x)) ((acc bound) (progn (pprint (list :blah-2 :counting acc :to bound)) (if (< acc bound) (recur (+ acc 3) bound) acc))) ((x &rest xs) (progn (pprint (list :blah-variadic :adding x :to xs)) (if (null xs) x (recur (+ x (first xs)) (rest xs))))))) (defparameter h (named-fn* blah ((x) (progn (pprint (list :blah-1 :result x)) x)) ((acc bound) (progn (pprint (list :blah-2 :counting acc :to bound)) (if (< acc bound) (blah (+ acc 3) bound) acc))) ;; ((x &rest xs) ;; (progn (pprint (list :blah-variadic :adding x :to xs)) ;; (if (null xs) x (recur (+ x (first xs)) (rest xs))))) )) ) ;; (defmacro named-fn* (name &rest args-bodies) ;; (if (= (length args-bodies) 1) ;; (let ((args-body (first args-bodies))) ;; `(named-fn ,name ,(first args-body) ,(second args-body))) ;regular named-fn, no dispatch. ;; (destructuring-bind (cases var) (parse-dispatch-specs args-bodies) ;; (let* ((recur-sym (intern "RECUR")) ;; (args (gensym "args")) ;; (funcspecs (mapcar (lambda (xs) ;; (destructuring-bind (n (args body)) xs ;; (let* ((fname (func-name name n)) ;; (fbody `(named-fn ,fname ,args ,body))) ;; (if (= n 0) ;; `(,n ,fname ,fbody) ;; `(,n ,fname ,fbody))))) cases)) ;; (varspec (when var ;; (let* ((fname (func-name name :variadic)) ;; (fbody `(named-fn ,fname ,(first var) ,(second var)))) ;; `(:variadic ,fname ,fbody)))) ;; (specs (if var (append funcspecs (list varspec)) funcspecs)) ;; (aux (gensym "aux"))) ;; `(let ((,name)) ;; (macrolet ((,name (,'&rest ,args) ;; (list* 'funcall ',name ,args) ;; )) ;; (let* (,@(mapcar (lambda (xs) `(,(second xs) ,(third xs))) specs)) ;; (labels ((,aux (,'&rest ,args) ;; (case (length ,args) ;; ,@(mapcar (lambda (xs) (let ((n (first xs)) ;; (name (second xs))) ;; (if (= n 0) ;; `(,n (funcall ,name)) ;; `(,n (apply ,name ,args))))) funcspecs) ;; (otherwise ,(if var `(apply ,(second varspec) ,args) ;; `(error 'no-matching-args)))))) ;; (setf ,name (lambda (&rest ,args) (apply ,aux ,args))) ;; (labels ((,name (,'&rest ,args) (apply ,name ,args))) ;; (function ,aux)))))))))) ;;testing (comment (defparameter the-func (lambda* (() 2) ((x) (+ x 1)) ((x y) (+ x y)) ((&rest xs) (reduce #'+ xs)))) )
15,321
Common Lisp
.lisp
388
33.829897
104
0.39687
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
cac525f281a88d1bd96e37e274afb04cf64d370ae13b7d257dc268061a84415f
414
[ -1 ]
415
methoderr.lisp
joinr_clclojure/dustbin/methoderr.lisp
(defgeneric blah (obj)) (defparameter *global-msg* "global!") (let ((local-msg "local1!")) (progn (defclass test1 () ()) (defmethod blah ((obj test1)) local-msg))) (blah (make-instance 'test1)) (let [local-msg "local2!"] (progn (defclass test2 () ()) (defmethod blah ((obj test2)) local-msg))) (def x (let [local-msg "local3!"] (progn (defclass test3 () ()) (defmethod blah ((obj test3)) local-msg)))) (blah (make-instance 'test3)) (defprotocol IBlee (blee [this])) (def result (let [local-msg "local4!"] (progn (defclass test4 () ()) (eval '(DEFMETHOD BLEE ((THIS TEST4)) LOCAL-MSG))))) (defgeneric blah (obj)) (defclass test () ()) (let ((local-msg "local1!")) (DEFMETHOD BLAH ((THIS TEST)) LOCAL-MSG)) ;;=>(blah (make-instance 'test)) ;;"local1!" (let ((local-msg "local2!")) (eval (list 'DEFMETHOD 'BLAH '((THIS TEST4)) LOCAL-MSG)))
931
Common Lisp
.lisp
31
26
60
0.608794
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
79da147858c951036844002e5e2c03fe5042ab307958cef2b0b28b61fb07c3a2
415
[ -1 ]
417
protocols.lisp
joinr_clclojure/dustbin/protocols.lisp
;;a simple implementation of clojure protocols, and deftype. ;;this will help with building libraries, particularly ;;the seq libraries. ;;If we can bolt on a few fundamental operations, we can take ;;advantage of the bulk of the excellent bootstrapped clojure ;;defined in the clojurescript compiler. (defpackage :clclojure.protocols (:use :common-lisp :common-utils :clclojure.reader :clclojure.pvector) (:export :defprotocol :extend-protocol :extend-type :satisfies? :protocol-exists? :list-protocols :clojure-deftype)) (in-package :clclojure.protocols) ;;aux ;;bootstrapping hack! (defun vector? (x) (typep x 'clclojure.pvector::pvec)) (defun vector-expr (x) (and (listp x) (eq (first x) 'persistent-vector))) ;;this keeps args in order....we nreverse all over the place. ;;Since we prototyped using lists, and now the vector ;;reader is working well, we're in the middle of migrating ;;to vectors. For now, we allow backwards compat with both ;;(perhaps allowing CL to define protocols in their native ;;tongue, I dunno). In the future, we'll enforce ;;vectors.... (defun as-list (xs) (if (vector? xs) (nreverse (vector-to-list xs)) (if (vector-expr xs) (rest xs) xs))) ;;changed this since we have lists now... (defun drop-literals (xs) (nreverse (filter (lambda (x) (not (or (literal? x) (stringp x)))) (as-list xs)))) ;;Note-> we need to add support for variadic functions, ;;and variadic protocols members. ;;protocols are used extensively, as is deftype. There are a ;;few additional data types that we need to provide. ;Protocol specifications take on the form below: ;(protocolname ; (function-name1 (args) &optional doc) ; function-name2 (args) &optional doc)) ;; (defparameter samplespec ;; '(ISeq ;; (next (coll) ;; "Gets the next element from the sequence") ;; (more (coll) ;; "Gets the rest of the sequence."))) (defun spec-name (protocolspec) (car protocolspec)) (defun spec-functions (protocolspec) (remove-if-not #'listp (as-list protocolspec))) ;;bombing out since we can't extend SEQUENCE to ;;our own types (thanks hyperspec!) ;;We can, however, enforce that one must use persistent ;;vectors....or....we can coerce the vectors to lists, which ;;are acceptable sequences.... (defun function-names (protocolspec) (mapcar #'first (spec-functions protocolspec))) (defun make-satisfier (protocolspec) "From a list of function specs, builds a function that compares a list of function specs to ensure both specifications have the same function names. If no function specs are provided, the identity function is returned." (let ((names (function-names protocolspec))) (if (null names) (lambda (x) (declare (ignore x)) t) (lambda (newspec) (null (set-difference names (function-names newspec))))))) ;a sample implementation for ISeqs... (comment (defparameter sampleimp '(ISeq (next (coll) (car coll)) (more (coll) (cdr coll))))) ;;From stack overflow. It looks like the compiler needs a hint if we're ;;defining struct/class literals and using them as constants. (EVAL-WHEN (:compile-toplevel :load-toplevel :execute) ;;A protocol is a name, a set of generic functions, and a set of ;;types that implement the protocol. (defstruct protocol name functions satisfier (members (list))) (defmethod make-load-form ((v protocol) &optional env) (declare (ignore env)) (make-load-form-saving-slots v))) (defun ->protocol (name functions &optional satisfier) (make-protocol :name name :functions functions :satisfier satisfier)) (defun protocol-to-spec (p) (with-slots (name functions) p (list name functions))) ;;We won't keep a central listing of protocols. They'll be first class objects, ;;as in Clojure on the JVM. ;Debating whether to keep this around, ;I may not need it... (defparameter *protocols* (make-hash-table :test #'eq)) ;Probably deprecated soon... (defun get-protocol (name) (gethash name *protocols*)) ;;we can replace this using CLOS. We just add a generic function that ;;tells us if an object satisfies a protocol. ;;like (satisfies-protocol? (protocol obj)) ;;Since protocols are actual objects (structs in this case), we call ;;(satisfies? the-protocol-obj the-obj) ;;which delegates to ;;((get-slot 'satisfier the-protocol-obj) the-obj) ;;So we let the protocol tell us if an object satisfies its protocol. ;;When we do defprotocol then, we add an implementation of (defun add-protocol-member (pname membername) "Identifies membername as an implementor of protocol pname" (multiple-value-bind (p exists?) (get-protocol pname) (when exists? (push membername (protocol-members p))))) ;Probably deprecated soon... (defun protocol-exists? (name) (not (null (get-protocol name)))) (defun drop-protocol (name) "Eliminates any bindings to the quoted protocol name, including generic functions." (if (protocol-exists? name) (let ((p (get-protocol name))) (progn (unintern (protocol-name p)) (dolist (n (protocol-functions p)) (unintern n)) (remhash name *protocols*))))) (defun list-protocols () "Lists all known protocols." (loop for k being the hash-keys in *protocols* collect k)) ;;we should cache this.... (defgeneric satisfies? (p x)) (defmethod satisfies? ((p protocol) x) (not (null (find (type-of x) (protocol-members p))))) (defmethod satisfies? ((p protocol) x) (not (null (find (type-of x) (protocol-members p))))) (define-condition protocol-exists (error) ((text :initarg :text :reader text))) (define-condition malformed-protocol (error) ((text :initarg :text :reader text))) (define-condition missing-implementations (error) ((text :initarg :text :reader text))) (define-condition name-collision (error) ((text :initarg :text :reader text))) ;when we add protocols, we just want to ensure that the ;right generic functions are implemented. ;We let Common Lisp sort out whether the generic functions ;are actually correct. (defun add-protocol (p) (with-slots (name) p (if (null (get-protocol name)) (setf (gethash name *protocols*) p) ; (error 'protocol-exists)))) (progn (print (format nil "Overwriting existing protocol ~A" name)) (drop-protocol `(quote ,name)) (setf (gethash name *protocols*) p))))) ;;We need to add the multiple-dispatch function that's in bootstrap at the moment. ;;A multiple-body protocol implementation could be... (defparameter proto-spec '(defprotocol ITough (get-toughness [x] [x y] "gets the toughness of x, or if x is compared to y, the relative toughness"))) ;;If we want to use generic functions to mirror single-dispatch implementations of ;;protocols, we have to allow for multiple-body functions. ;;So, there's probably a protocol dispatch function.. ;;Just like our fn macro... ;;If we have multiple specs, [x] [x y], in this case, we need a generic function ;;that dispatches based on the first arg of the spec. ;;Alternately....we can just use the fn body from before... ;;This only ever matters if there are multiple function bodies. If there's only one, ;;we're golden (that's the current situation). ;;note: dealing with reader-literals and how macros parse stuff, like pvectors, ;;so we're just filtering them out of arglists. ;; (defun build-generic (functionspec) ;; (let* ((args (drop-literals (second functionspec))) ;; (name (first functionspec)) ;; (docs (if (= (length functionspec) 3) ;; (third functionspec) ;; "Not Documented"))) ;; `(progn (defgeneric ,name ,args (:documentation ,docs)) ;; ;;lets us use protocol fns as values... ;; (defparameter ,name (function ,name)) ;; (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ;; ,name))) (defun build-generic (functionspec) (let* ((args (drop-literals (rest functionspec))) (name (first functionspec)) (docs (if (stringp (last functionspec)) (last functionspec) "Not Documented"))) (case (length args) (1 (let ((args (drop-literals (first args)))) `(progn (defgeneric ,name ,args (:documentation ,docs)) ;;lets us use protocol fns as values... (defparameter ,name (function ,name)) (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ,name))) (otherwise `(progn (defgeneric ,name (,'this ,'&rest ,'args) (:documentation ,docs)) ;;lets us use protocol fns as values... (defparameter ,name (function ,name)) (setf (symbol-function (quote ,name)) (symbol-value (quote ,name))) ,name)) ))) (defun quoted-names (xs) (mapcar (lambda (x) (list 'quote x)) (function-names xs))) (defun spec-to-protocol (protocolspec) `(progn ,@(mapcar #'build-generic (spec-functions protocolspec)) (->protocol (quote ,(spec-name protocolspec)) (list ,@(mapcar (lambda (x) (list 'quote x)) (function-names protocolspec))) (make-satisfier (quote ,protocolspec))))) ;;we'll have to update this guy later, but for now it's okay. ;;Added that a symbol gets created in the current package. (defmacro defprotocol (name &rest functions) (let ((p (gensym)) (spec (cons name functions))) `(let ((,p (eval (spec-to-protocol (quote ,spec))))) (progn (add-protocol ,p) (defparameter ,name ,p))))) ;extends protocol defined by name to ;each type in the typespecs, where typespecs ;are of the form... ;(typename1 (func1 (x) (body)) ; (func2 (x) (body)) ; typename2 (func1 (x) (body)) ; (func2 (x) (body))) ;bascially converts the implementations into a ;defmethod.. ;;takes a list of (defun parse-implementations (x) (labels ((get-spec (acc specs) (if (null specs) acc (let ((arg (first specs))) (if (symbolp arg) (get-spec (cons (list arg) acc) (rest specs)) (let ((currentspec (first acc))) (get-spec (cons (cons arg currentspec) (rest acc)) (rest specs)))))))) (mapcar #'nreverse (get-spec (list) x)))) ;; (defparameter samplext ;; '(pvec ;; (next (coll) (nth coll 0)) ;; (more (coll) (subvec coll)) ;; cons ;; (next (coll) (first coll)) ;; (more (coll) (rest coll)))) (defun implement-function (typename spec) (let* ((args (cond ((vector? (second spec)) (vector-to-list (second spec))) ;this is a crappy hack. ((vector-expr (second spec)) (rest (second spec))) (t (drop-literals (second spec))))) (newargs (cons (list (first args) typename) (rest args))) (body (third spec))) `(defmethod ,(first spec) ,newargs ,body))) ;; (defmacro implement-function (typename spec) ;; (let* ((args (if (vector? (second spec)) ;; (vector-to-list (second spec)) ;; (drop-literals (second spec)))) ;; (newargs (cons (list (first args) typename) (rest args))) ;; (body (third spec))) ;; ;(print spec) ;; `(defmethod ,(first spec) ,newargs ,body))) (defmacro emit-method (name typename imp) `(progn (add-protocol-member (quote ,name) (quote ,typename)) ,@(mapcar (lambda (spec) (implement-function typename spec)) (rest imp)))) (defun emit-implementation (name satvar imp) (let ((quoted-imp (gensym "quotedimp"))) `(let ((,quoted-imp (quote ,imp))) (if (funcall ,satvar ,quoted-imp) (emit-method ,name ,(first imp) ,imp) (error 'missing-implementations (str `(,,name ,,quoted-imp))))))) (defmacro extend-protocol (name &rest typespecs) (let ((imps (parse-implementations typespecs)) (satisfies? (gensym))) `(let ((,satisfies? (protocol-satisfier (get-protocol (quote ,name))))) ,@(mapcar (lambda (imp) (emit-implementation name satisfies? imp)) imps)))) ;Extend-type is also particularly useful. ;;Pending -> implement deftype. (comment ;Testing.... (defprotocol INamed (get-name (thing) "gets the name of the thing!") (say-name (thing) "Says the name of the thing!")) (extend-protocol INamed cons (get-name (thing) (car thing)) (say-name (thing) (pprint (format nil "The name is: ~A" (get-name thing))))) (defun test () (let ((data '(:tom))) (when (satisfies? INamed data) (pprint (get-name data))) (say-name data)) (defmacro cljmacro (name argvec & body) (let ((args (if (vector? argvec argvec) (eval `(clclojure.reader/quoted-children ,argvec))))) `(,@body))) ) ;;Deftype implementation. ;;Once we have protocols, deftype is pretty easy. ;;deftype is a hook into the type definition or object system of ;;the host environment. We'll use it to generate CLOS classes via ;;defclass. I may include an option to use deftype to build structs ;;which would likely kick ass for performance. ;;A deftype form is pretty easy: ;;(deftype name-of-type (field1 field2 ... fieldn) ;; Protocol1 ;; (function1 (args) body1) ;; Protocol2 ;; (function2 (args) body2)) ;; ;;Should expand into: ;;(progn ;; (defclass name-of-type ;; ((field1 :init-arg :field1) ;; (field2 :init-arg :field2))) ;; (extend-protocol Protocol1 name-of-type ;; (function1 (args) body1)) ;; (extend-protocol Protool2 name-of-type ;; (function2 (args) body2))) ) (defun symbolize (x) (read-from-string x)) (defun emit-class-field (nm s) `(,s :initarg ,(make-keyword s) :accessor ,(symbolize (str nm "-" s)))) (defun emit-protocol-extension (proto-name type-name imps) `(extend-protocol ,proto-name ,type-name ,@imps)) ;;impl has protocol (pfn ...) (pfn ...) (defmacro extend-type (typename &rest impls) (let ((imps (parse-implementations impls)) ;(name (gensym)) ;(the-imp (gensym)) ) `(progn ,@(mapcar (lambda (the-imp) (let ((expr `(emit-protocol-extension (quote ,(first the-imp)) (quote ,typename) (quote ,(rest the-imp))))) (eval expr))) imps)) ;; (if (funcall ,satisfies? imp) ;; (progn (add-protocol-member (quote ,name) typename) ;; (dolist (spec (rest imp)) ;; (eval (implement-function ,typename spec)))) ;; (error 'missing-implementation)) )) ;;the goal here is to define "instance-local" operations ;;at the method level, where fields refer to slots on the object. ;;so, we may have a object like {:a 2 :b 3} ;;fields [a b], ;;our implementations could be ;;(blah [obj] a) ;;undefined! ;;(blee [a] a) ;;defined, shadowing, poor form, but meh. ;;we need to extend the lexcial environment to include ;;field access... ;;(blah [obj] a) => ;;(blah [obj] ;; (with-slots ((a obj)) ; a)) ;;we can be more efficient if we walk the implementations ;;to detect field usage. For NOW, we'll just ;;bind all the fields in the lexical environment ;;of body, less the field names that are shadowed ;;by protocol args. ;;TODO: walk the body and collect fields to determine ;;the final set of fields to use (tailored). (defun with-fields (fields method args &rest body) (let* ((arglist (as-list args)) (var (first arglist)) (flds (set-difference (as-list fields) arglist))) ;;naive implementation is just bind all the slots.... (if flds `(,method ,args (with-slots ,flds ,var ,@body)) `(,method ,args ,@body)))) ;;we need to mod this. If the implementations refer to a field (and ;;the field is NOT shadowed as an argument to their method impl), we ;;need a call to with-slots to pull the referenced fields out to ;;mirror clojure's behavior. (defmacro clojure-deftype (name fields &rest implementations) (let* ((flds (cond ((vector? fields) (vector-to-list fields)) ((vector-expr fields) (rest fields)) (t fields))) (impls (mapcar (lambda (impl) (if (atom impl) impl (apply #'with-fields (cons flds impl)))) implementations))) `(progn (defclass ,name () ,(mapcar (lambda (f) (emit-class-field name f) ) flds)) ;;we need to parse the implementations to provide ;;instance-level fields... (extend-type ,name ,@impls) ;;debugging (defun ,(symbolize (str "->" name)) ,flds (make-instance ,`(quote ,name) ,@(flatten (mapcar (lambda (f) `(,(make-keyword f) ,f)) flds )))) ))) ;;Deftype exists in common lisp. (comment ;;An experimental class-bassed approach; putting this on ice for now. ;;This is our interface, which is a base class all protocols will ;;derive from. ;; (defclass IProtocol () ;; (name ;; functions ;; satisfier ;; (members ;; :initform (list)))) ;;Defining a protocol is just a matter of defining a new class that inherits ;;from IProtocol. ;; (defmacro defprotocol-1 (name functions &optional satisifer) ;; `(defclass ,name (IProtocol) ;; ((name :initform ,name) ;; (functions :initform functions) ;; ( ;; ) )
17,897
Common Lisp
.lisp
424
36.761792
107
0.639873
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f022bba4636f57fd68df98e175952fc8f4fb350a991823fc6c4b004b58488bb2
417
[ -1 ]
418
wrappers.lisp
joinr_clclojure/dustbin/wrappers.lisp
;;Defining classes that can help us to wrap ;;built-in classes to allow things like ;;attaching meta to arbitrary objects... ;;this isn't that special.... ;;storage and wrapper for our functions... (defclass function-object () ((name :initarg :name :accessor function-object-name) (args :initarg :args :accessor function-object-args) (body :initarg :body :accessor function-object-body) (func :accessor function-object-func) (meta :initarg :meta :accessor function-object-meta)) (:metaclass sb-mop::funcallable-standard-class)) ;; (defmethod initialize-instance :after ((f function-object) &key) ;; (with-slots (name args body func) f ;; (setf func ;; (eval `(fn ,args ;; ,body))) ;; ;;note: this is not portable...SBCL specific, ;; ;;may be able to work around this with closer-mop. ;; (sb-mop::set-funcallable-instance-function f func))) ;; (def f1 (make-instance 'function-object :name "plus" ;; :meta [] ;; :args '[x y] ;; :body '(+ x y) ;; )) (defun make-function (f &key (name nil) (args nil) (body nil) (meta {})) (let ((obj (make-instance 'function-object :name name :meta meta :args args :body body))) (sb-mop::set-funcallable-instance-function obj f) obj)) ;;funcallable is not invokable. ;;original idea for metadata, particularly ;;to capture argument ;;this is a pretty terrible way to attach meta ;;to objects... ;;A better way would be to define object-wrappers ;;the inherit from the wrappee, providing ;;slots for meta and hash... ;;(defparameter *wrapped-meta* (make-hash-table ))
1,884
Common Lisp
.lisp
42
39.738095
72
0.58156
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
f85b32b6e79383ae373a543571514a3717ffd5c18544f1b06dc151cdf5ad6674
418
[ -1 ]
419
keywordfunc.lisp
joinr_clclojure/dustbin/keywordfunc.lisp
(defpackage :clclojure.keywordfunc (:use :common-lisp ;:clclojure.base :common-utils) ;; (:shadowing-import-from :clclojure.base ;; :deftype :let) (:export :keyfn? :key-accessor :->keyaccess :keyaccess-func :keyaccess-key :with-keyfn)) (in-package :clclojure.keywordfunc) (defparameter keyfns (make-hash-table)) (defun keyfn? (k) (gethash k keyfns)) ;;this is the general template for implementing ;;keyword access... ;; (defun :a (m) (gethash :a m)) ;; (defun (setf :a) (new-value m) ;; (setf (gethash :a m) ;; new-value)) (defun key-accessor (k) (let ((m (gensym "map")) (v (gensym "newval"))) `(progn (defun ,k (,m) (gethash ,k ,m)) (defun (,'setf ,k) (,v ,m) (,'setf (,'gethash ,k ,m) ,v)) ;(,'setf (gethash ,k keyfns) ,k) ))) ;;for localized keyaccess, i.e. inside ;;lets and friends.... (defclass keyaccess () ((key :initarg :key :accessor keyaccess-key) (func :accessor keyaccess-func)) (:metaclass sb-mop::funcallable-standard-class)) (defmethod initialize-instance :after ((obj keyaccess) &key) (with-slots (key func) obj (setf func (lambda (ht) (gethash key ht))) (sb-mop::set-funcallable-instance-function obj func) (eval (key-accessor key)) (setf (gethash key keyfns) obj) )) ;;keyaccessors print like keywords. (defmethod print-object ((obj keyaccess) stream) (prin1 (keyaccess-key obj) stream)) (defun ->keyaccess (k) (or (gethash k keyfns) (make-instance 'keyaccess :key k))) ;;now, to get the last step of "real" keyword access, we need to ;;detect when keyword literals used, and create keyword accessors for ;;them. One dirty way of doing that, is to use a reader macro for ;;keywords, and ensure that every single keyword that's read has a ;;commensurate keyaccess obj created. ;;That's effective, maybe not efficient, since we're duplicating our ;;keywords everywhere. A more efficient, but harder to implement, ;;technique is to macroexpand and walk the code inside a unified-let*. In ;;theory, we can detect any forms used in the function position, and ;;if they're keywords, compile them into keyword accessors. (defmacro with-keyfn (expr) (let ((k (first expr)) ) (if (keywordp k) (if (not (keyfn? k)) (progn (format nil "adding keyword access for: ~a " k ) (eval (key-accessor k)) `,expr)) `,expr))) ;;dumb testing ;; (defparameter ht (make-hash-table)) ;; (with-keyfn (:a ht)) ;; (with-keyfn (:b ht)) ;; (setf (:a ht) :bilbo) ;; (setf (:b ht) :baggins) ;; (with-keyfn (:a ht)) ;; (with-keyfn (:b ht))
2,729
Common Lisp
.lisp
73
32.958904
90
0.638499
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
dd28d680fd7f23a3a9709de68117bd7ed1f0f1f6e160ed55c6e7ca17502cc9fe
419
[ -1 ]
420
clclojure.asd
joinr_clclojure/clclojure.asd
;;note: for quicklisp users... ;;compile and load this file, ;;or from emacs/SLIM (C-c C-k) ;;then quicklisp can load it for us ;;easy... ;;(ql:quickload :clclojure) (asdf:defsystem :clclojure :depends-on (:named-readtables :cl-package-locks :cl-murmurhash) ;copied from example. debate using :cl-hamt :components ((:file "common-utils") (:file "walk" :depends-on ("common-utils")) (:file "sequences" :depends-on ("common-utils")) (:file "reader" :depends-on ("pvector" "cowmap" "sequences")) (:file "eval" :depends-on ("common-utils" "walk" "reader")) (:file "literals" :depends-on ("eval" "pvector" "cowmap")) (:file "keywordfunc") (:file "pvector") (:file "cowmap") (:file "lexical" :depends-on ("keywordfunc")) (:file "protocols" :depends-on ("literals" "common-utils" "reader" "pvector" "cowmap")) (:file "bootstrap" :depends-on ("literals" "common-utils" "lexical" "keywordfunc" "protocols" "pvector" "cowmap"))) )
1,429
Common Lisp
.asd
35
25.342857
111
0.451937
joinr/clclojure
224
8
4
EPL-1.0
9/19/2024, 11:25:15 AM (Europe/Amsterdam)
7d7e66863cbd0f0a967ad416786e19340e4737320b1fadb9247d387dcd2c85ec
420
[ -1 ]
470
load-tools.lisp
cac-t-u-s_om-sharp/build/load-tools.lisp
(in-package :cl-user) (export '(compile&load decode-local-path) :cl-user) ; (clean-sources) (defvar *compile-type* "xfasl") ;;; should be : "xfasl" on MacIntel, "nfasl" on MacPPC, "ofasl" on Win32, "64xfasl" or "xfasl" on Linux (setf *compile-type* (pathname-type (cl-user::compile-file-pathname ""))) #+win32(editor::bind-key "Find Source" "Control-." :global :pc) ;;; equivalent to LW'w CURRENT-PATHNAME, allowing other reference path like in om-relative-path (defun decode-local-path (path &optional relative-path) (labels ((string-until-char (string char) (let ((index (search char string))) (if index (values (subseq string 0 index) (subseq string (+ index 1))) (values string nil)))) (str2list-path (str) (let (list) (loop while str do (let ((rep (multiple-value-list (string-until-char str "/")))) (setf str (second rep)) (when (first rep) (push (first rep) list)))) (reverse list)))) (let ((decoded-path (str2list-path path)) (ref (or relative-path *load-pathname*))) (make-pathname :host (pathname-host ref) :device (pathname-device ref) :directory (append (pathname-directory ref) (butlast decoded-path)) :name (car (last decoded-path)))))) ;;; This is how to use a new compiled-file extension (not used) ;(when (and compile-ext (not (find compile-ext sys:*binary-file-types* :test 'string-equal))) ; (push compile-ext sys:*binary-file-types*)) ; WARNINGS ; - <file> can be a .lisp or a pathname with no extension; ; - Not sure why, but compile/load don't find the file type is :unspecific ; they do if the type is NIL (load searches for "*fasl" then "lisp", compile-file seraches "lisp") ; - The Lisp function "merge-pathname" tends to generate pathnames with type = :unspecific (defun compile&load (file &optional (verbose t) (force-compile nil) (compile-to nil)) ;;; Replace :unspecific pathname-type by NIL (when (equal :unspecific (pathname-type file)) (setf file (make-pathname :directory (pathname-directory file) :device (pathname-device file) :host (pathname-host file) :name (pathname-name file) :type NIL))) (let* (;;; Resolve the name of the actual Lisp file (lisp-file (truename (make-pathname :directory (pathname-directory file) :device (pathname-device file) :host (pathname-host file) :name (pathname-name file) :type "lisp"))) ;;; Find out the target for compiled file (default = same as Lisp file) (fasl-target (if compile-to (make-pathname :directory (pathname-directory compile-to) :host (pathname-host compile-to) :device (pathname-device compile-to) :name (pathname-name file)) (make-pathname :directory (pathname-directory file) :device (pathname-device file) :host (pathname-host file) :name (pathname-name file)))) ;;; Resolve the name of the compiled-file (fasl-file (make-pathname :directory (pathname-directory fasl-target) :device (pathname-device fasl-target) :host (pathname-host fasl-target) :name (pathname-name fasl-target) :type *compile-type*)) ;;; Is there a compiled-file already ? (fasl-present (probe-file fasl-file)) ;;; ... and is it up-to-date ? (= more recent than the last modification of the Lisp file) (fasl-outofdate (and fasl-present (or (not (file-write-date lisp-file)) (not (file-write-date fasl-file)) (> (file-write-date lisp-file) (file-write-date fasl-file)) )))) ; (print (format nil "File: ~s~%Lisp: ~s~%Fasl: ~s (~A-~A)" file lisp-file fasl-file fasl-present fasl-outofdate)) ;;; COMPILE-FILE is not available in delivered applications ;;; If it is and if required/necessary: compile the file (when (and (fboundp 'compile-file) ;; == ;; (not (member :om-deliver *features*)) (or force-compile (not fasl-present) fasl-outofdate)) (when fasl-target (ensure-directories-exist fasl-target)) (compile-file lisp-file :verbose 0 :output-file fasl-target) (setf fasl-outofdate nil)) (if fasl-outofdate ;;; If the fasl was here and is still out-of-date (couldn't be compiled) ;;; then load the Lisp file (progn (print (format nil "WARNING: File ~A is older than the LISP source file.~%=> Loading ~A." fasl-file lisp-file)) (load lisp-file :verbose verbose)) ;;; Otherwise, load the compiled file ;;; The handler-bind gives us a chance to recompile, just in case the compilation contents was wrong despite the date (catch 'faslerror (handler-bind ((conditions::fasl-error #'(lambda (c) (declare (ignore c)) (when (and (fboundp 'compile-file) fasl-file) (print (format nil "File ~s will be recompiled..." fasl-file)) (compile-file file :verbose verbose :output-file fasl-target) (load fasl-file :verbose verbose) (throw 'faslerror t) )))) ;;; At this stage, load what we have ! (if (probe-file fasl-file) (load fasl-file :verbose verbose) (load lisp-file :verbose verbose)) ))))) ;;; TEMP -- BUG LISPWORKS ; (trace (error :backtrace :bug-form :trace-output *terminal-io*)) ;(editor:defcommand "Buffer List To File" (p) ; "" ; (with-open-file (out "~/LispWorks-Buffer-List.txt" ; :direction :output ; :if-exists :supersede) ; (print editor::*buffer-list* out))) ;(editor:bind-key "Buffer List To File" #("control-c" "z")) ;;; END (defun clean-svn (&optional dir) (let ((src-root (or dir (make-pathname :directory (butlast (pathname-directory *load-pathname*) 2))))) (mapc #'(lambda (file) (if (system::directory-pathname-p file) (if (string-equal ".svn" (car (last (pathname-directory file)))) (system::call-system (concatenate 'string "rm -Rf \"" (namestring file) "\"")) (clean-svn file)) (when (and (pathname-type file) (or (string-equal (pathname-type file) "lisp~") (string-equal (pathname-type file) "DS_STORE"))) (delete-file file)) )) (directory (namestring src-root) :directories t)))) ; (clean-svn (make-pathname :directory (append (butlast (pathname-directory *load-pathname*)) '("libraries")))) (defun clean-sources (&optional dir (verbose t)) (let ((src-root (or dir (make-pathname :directory (butlast (pathname-directory *load-pathname*)))))) (mapc #'(lambda (file) (if (and (system::directory-pathname-p file) (not (string-equal (car (last (pathname-directory file))) ".git"))) (clean-sources file verbose) (when (and (pathname-type file) (or (find (pathname-type file) '("64xfasl" "xfasl" "fasl" "DS_STORE" "nfasl" "ofasl" "ufasl" "omfasl" "lisp~") :test 'string-equal) (string= (pathname-type file) *compile-type*))) ; remove compiled files (when verbose (print (concatenate 'string "Deleting " (namestring file) " ..."))) (delete-file file) ))) (directory (namestring src-root) :directories t)) )) ; (clean-sources) ; (clean-sources (make-pathname :directory (append (butlast (pathname-directory *load-pathname*) 4) '("om-6-7-libs" "OMChroma")))) (defun count-lines (file) (flet ((delete-spaces (string) (let ((pos (position-if #'(lambda (x) (not (member x (list #\Linefeed #\Space #\Tab) :test 'equal))) string))) (if pos (subseq string pos) "")))) (let ((n 0)) (with-open-file (f file :direction :input) (let ((line (read-line f nil 'eof))) (loop while (and line (not (equal line 'eof))) do (unless (or (string-equal (delete-spaces line) "") (equal (elt (delete-spaces line) 0) #\;)) (setf n (+ n 1))) (setf line (read-line f nil 'eof)) ))) n))) (defun count-sources (&optional dir) (let ((nfiles 0) (nlines 0) (src-root (or dir (make-pathname :directory (append (butlast (pathname-directory *load-pathname*) 1) '("code")))))) (mapc #'(lambda (file) (if (system::directory-pathname-p file) (let ((count (count-sources file))) (setf nfiles (+ nfiles (car count))) (setf nlines (+ nlines (caDr count)))) (when (and (pathname-type file) (string-equal (pathname-type file) "lisp")) (setf nfiles (+ nfiles 1)) (setf nlines (+ nlines (count-lines file))) ) )) (directory (namestring src-root) :directories t)) (list nfiles nlines) )) ; (count-sources) ; ==> 444 files, 132219 lines of code, 183377 lines
10,142
Common Lisp
.lisp
180
41.933333
158
0.54398
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
107f6508bd22e93016c3e80574c277f76a75646a2d5d5cb8d3d28fdab341bb3e
470
[ -1 ]
471
c-lisp-auto-bindings.lisp
cac-t-u-s_om-sharp/build/c-lisp-auto-bindings.lisp
(in-package :cl-user) (defparameter *c-lisp-types* '((void :void) (int :int) (bool :boolean) (float :float) (double :double) (char* :string) (iaeom_t* :pointer))) (defun colle-star (in) (let* ((str in) (pos (search " *" str))) (loop while pos do (setf str (concatenate 'string (subseq str 0 pos) "* " (subseq str (+ pos 2)))) (setf pos (search " *" str))) str)) (defun string-until-char (string char) (let ((index (search char string))) (if index (values (subseq string 0 index) (subseq string (+ index 1))) (values string nil)))) (defun convert-type (type) (or (cadr (find type *c-lisp-types* :key 'car)) (and (find #\* (string type)) :pointer) (and type (intern (concatenate 'string "UNKNOWN_TYPE_" (string type)) :keyword)))) (defun get-fun-list (file) (let ((line nil) (return-types ) (functions nil) (last-comment nil)) (with-open-file (f file :direction :input) (loop while (not (string-equal "eof" (setf line (colle-star (remove #\: (read-line f nil "eof")))))) do (multiple-value-bind (item-read pos) (read-from-string line nil nil) (if (find item-read *c-lisp-types* :key 'car) (let ((fun-and-args (subseq line pos))) (loop while (or (equal #\Space (elt fun-and-args 0)) (equal #\Tab (elt fun-and-args 0))) do (setf fun-and-args (subseq fun-and-args 1))) (multiple-value-bind (fname args) (string-until-char fun-and-args " ") (push ;; (function-name n-type n-type comments) (list fname item-read args (reverse last-comment)) functions) (setf last-comment nil))) (if item-read (push line last-comment)))))) (remove-duplicates (reverse functions) :key 'car :from-end t))) (defun write-args (string stream) (let ((argstring (remove #\( (remove #\) (substitute #\Space #\Tab string)))) (list nil)) (loop while argstring do (let ((rep (multiple-value-list (string-until-char argstring ",")))) (setf argstring (second rep)) (when (first rep) (push (first rep) list)))) (loop for item in (reverse list) collect (progn (loop while (and (> (length item) 0) (equal #\Space (elt item 0))) do (setf item (subseq item 1))) (when (and (>= (length item) 5) (string-equal (subseq item 0 5) "const")) (setf item (subseq item 6))) (multiple-value-bind (type pos) (read-from-string item nil nil) (when type (format stream " (~a :~a)" (read-from-string (subseq item pos) nil nil) (convert-type type))) )) ))) (defun make-ffi (in out &optional (package :cl-user)) (with-open-file (f out :direction :output :if-exists :supersede) (format f "(in-package :~a)" package) (terpri f) (terpri f) (loop for fun in (get-fun-list in) do (loop for cline in (nth 3 fun) do (write-line (concatenate 'string ";;; " cline) f)) (format f "(cffi::defcfun (~s ~a) :~a" (nth 0 fun) (nth 0 fun) (convert-type (nth 1 fun))) (write-args (nth 2 fun) f) (format f ")~%") (terpri f))) out)
3,524
Common Lisp
.lisp
71
37.774648
114
0.532211
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d7ae4a9ca9244f0588aed2125c7710f1c130c2bf207d714fbc61245e8f4e60d5
471
[ -1 ]
472
tests.lisp
cac-t-u-s_om-sharp/build/tests.lisp
;;; OpenMusic tests file (in-package :om) (defparameter *soundfile1* "/Users/bresson/_SHARED-FILES/IN-FILES/SOUNDFILES/Bassclarinet1.aif") (defparameter *soundfile2* "/Users/bresson/_SHARED-FILES/IN-FILES/SOUNDFILES/add-synth-4ch-sas.aiff") ; (test-play-sound) (defun add-sound-box (view soundfile pos) (let ((sound (om-init-instance (make-instance 'sound) `((:file ,soundfile) (:access-from-file nil)))) (box (omng-make-new-boxcall (find-class 'sound) pos))) (setf (value box) (list sound)) (setf (display box) :mini-view) (add-box-in-patch-editor box view) box)) (defun play-sound-box (box) (let ((dur (ms->sec (get-obj-dur (car (value box)))))) (play-boxes (list box)) (sleep (+ dur .5)))) (defun test-play-sound () (print "test-play-sound") (let* ((patch (open-new-document :patch)) (patchview (main-view (editor patch))) (box1 (add-sound-box patchview *soundfile1* (omp 200 200))) (box2 (add-sound-box patchview *soundfile2* (omp 300 200)))) (sleep 0.5) (play-sound-box box1) (play-sound-box box2) )) (defun test-om-spat () (print "test-om-spat") (open-doc-from-file :patch "/Users/bresson/SRC/OM7/IRCAM-FORGE/om7-patches/om-spat/om-spat-spat-scene.opat")) (defun test-symbolist () (print "test-symbolist") (open-doc-from-file :patch "/Users/bresson/SRC/symbolist/OM/symbolist/patches/symbolist-test.opat"))
1,480
Common Lisp
.lisp
34
37.617647
111
0.648122
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7181352e63da29ecccdc97025d0d154debd966d38622a2f906113331436ada12
472
[ -1 ]
473
deliver.lisp
cac-t-u-s_om-sharp/build/deliver.lisp
;;;============================== ;;; OM# main delivery script ;;; Run Lispworks with this file as -build argument ;;; to create the OM# application ;;;============================== (in-package "CL-USER") (load-all-patches) #+mswindows (require "ole") ;;; Used by the "Shell" window (= useful?) ;;; See also *modules* for more modules... (require "shell-buffer") (require "subproc") (print "==============================") (print "LOADING SOURCES") (print "==============================") (load (current-pathname "build")) (print "==============================") (print "APPLICATION SETUP") (print "==============================") (defparameter *full-app-name* om::*app-name*) (defparameter *om-directory-folders* (butlast (pathname-directory (current-pathname)))) (let ((version-str (concatenate 'string (format nil "~d.~d" *version-major* *version-minor*) (if (and *version-patch* (plusp *version-patch*)) (format nil ".~d" *version-patch*) "")))) ;(setf *full-app-name* (concatenate 'string om::*app-name* " " version-str)) (with-open-file (f (make-pathname :directory (butlast (pathname-directory (current-pathname))) :name "VERSION") :direction :output :if-exists :supersede) (write-string version-str f) )) #+cocoa (load (current-pathname "mac/application-bundle")) #| ;;; not really working... #+mswindows (load (current-pathname "win/dde")) |# (defun init-omsharp-standalone () (push :om-deliver *features*) #+cocoa (omsharp-interface) ;; #+mswindows(startup-omsharp-dde-server) (om::init-root-folders) (setf dspec::*active-finders* (append dspec::*active-finders* (list (merge-pathnames #+macosx (concatenate 'string *full-app-name* ".app/Contents/Resources/dspec-database." (oa::om-compiled-type)) #-macosx (concatenate 'string "resources/dspec-database." (oa::om-compiled-type)) om-api::*om-root* )))) #+cocoa(setf system::*stack-overflow-behaviour* nil) (setq om::*om-debug* nil) ;; will disable debug print messages (om::start-omsharp)) ;;;========================== ;;; SOURCE DEFINITIONS ;;;========================== ; (*active-finders*) (print "==============================") (print "SAVE SOURCE TRACKING") (print "==============================") (dspec::save-tags-database (make-pathname :directory (append *om-directory-folders* '("resources")) :name "dspec-database" :type (oa::om-compiled-type))) (dspec:discard-source-info) ;;;========================== ;;; FUNCTION REFERENCE ;;;========================== (om::gen-reference-doc) ;;;========================== ;;; BUILD IMAGE ;;;========================== ;(setf *debugger-hook* 'oa::om-debugger-hook) (defun version-to-hex (n) (format nil "#x~4,'0X~4,'0X~4,'0X~4,'0X" (round n) (round (* (cadr (multiple-value-list (round n))) 100)) (round (* (cadr (multiple-value-list (round (* 100 n)))) 100)) (round (* (cadr (multiple-value-list (round (* 10000 n)))) 100)) )) (defun move-mac-resources () (print "================================") (print "MOVING RESOURCES (macOS only)") (print "================================") (let* ((app-contents-folder (make-pathname :directory (append *om-directory-folders* (list (concatenate 'string *full-app-name* ".app") "Contents")))) (app-libs-folder (merge-pathnames (make-pathname :directory '(:relative "Frameworks")) app-contents-folder)) (app-resources-folder (merge-pathnames (make-pathname :directory '(:relative "Resources")) app-contents-folder))) (print (format nil "COPYING LIBRARIES TO: ~A" app-libs-folder)) (om::om-copy-directory (merge-pathnames "lib/mac/" (make-pathname :directory (append *om-directory-folders* '("resources")))) app-libs-folder) (print (format nil "COPYING RESOURCES TO: ~A" app-resources-folder)) (loop for item in (oa::om-directory (make-pathname :directory (append *om-directory-folders* '("resources"))) :files t :directories t) unless (string-equal "lib" (car (last (pathname-directory item)))) unless (string-equal "ttf" (string (pathname-type item))) do (if (system::directory-pathname-p item) (om::om-copy-directory item (make-pathname :device (pathname-device app-resources-folder) :directory (append (pathname-directory app-resources-folder) (last (pathname-directory item))))) (om::om-copy-file item (make-pathname :device (pathname-device app-resources-folder) :directory (pathname-directory app-resources-folder) :name (pathname-name item) :type (pathname-type item))) )) (om::om-copy-directory (make-pathname :device (pathname-device app-resources-folder) :directory (append *om-directory-folders* '("help-patches"))) (make-pathname :device (pathname-device app-resources-folder) :directory (append (pathname-directory app-resources-folder) '("help-patches")))) (om::om-copy-directory (make-pathname :device (pathname-device app-resources-folder) :directory (append *om-directory-folders* '("src"))) (make-pathname :device (pathname-device app-resources-folder) :directory (append (pathname-directory app-resources-folder) '("src")))) (clean-sources (make-pathname :device (pathname-device app-resources-folder) :directory (append (pathname-directory app-resources-folder) '("src"))) NIL) (om::om-copy-directory (make-pathname :device (pathname-device app-resources-folder) :directory (append *om-directory-folders* '("init"))) (make-pathname :device (pathname-device app-contents-folder) :directory (append (pathname-directory app-contents-folder) '("Init")))) )) (print "==============================") (print "CREATING APP") (print "==============================") ; (version-to-hex 6.020005) ; #x0006000200000005 (let ((application-pathname #+cocoa (when (save-argument-real-p) (compile-file-if-needed (sys:example-file "configuration/macos-application-bundle") :load t) (create-macos-application-bundle (make-pathname :directory (butlast (pathname-directory (current-pathname))) :name *full-app-name*) :document-types (list `("Patch" ("opat") ,(om::om-relative-path '("mac") "opat.icns")) `("Sequencer" ("oseq") ,(om::om-relative-path '("mac") "oseq.icns")) ;`("TextFun" ("olsp") ,(om::om-relative-path '("mac") "lsp-icon.icns")) `("Library" ("olib" "omlib") ,(om::om-relative-path '("mac") "olib.icns"))) :application-icns (om::om-relative-path '("mac") "om-sharp.icns") :identifier "fr.cactus.om-sharp" :version *version-string* )) #+mswindows (make-pathname :directory (butlast (pathname-directory (current-pathname))) :name *full-app-name* :type "exe") #+linux (make-pathname :directory (butlast (pathname-directory (current-pathname))) :name *full-app-name*))) #+macosx(move-mac-resources) (deliver 'init-omsharp-standalone application-pathname 0 #+macosx :split #+macosx :resources :interface :capi :keep-editor t :keep-debug-mode t :keep-load-function t :keep-pretty-printer t ;#+win32 :editor-style #+win32 :pc ;:keep-complex-numbers nil ;:keep-conditions :all ;:keep-xref-info t ;; ?? ;:editor-style :default :startup-bitmap-file NIL ;; *startup-bmp* ;; removed because of a delivery bug with menus #+mswindows :keep-gc-cursor #+mswindows nil #+mswindows :versioninfo #+mswindows (list :binary-version (read-from-string (version-to-hex *version*)) :version-string *version-string* :company-name "" :product-name "om-sharp" :file-description "") #+mswindows :console #+mswindows :input ; :quit-when-no-windows #+mswindows t #-mswindows nil #+(or cocoa win32) :packages-to-keep #+cocoa '(:objc) #+mswindows '(:comm) #+mswindows :icon-file #+mswindows "./win/om-sharp.ico" ) ) ; :editor-commands-to-keep :all-groups
9,782
Common Lisp
.lisp
175
41.32
140
0.5165
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b49b6e4c539023d5e12fe794402b758fff52ac83a4b8883b68e156cba673bf1f
473
[ -1 ]
474
build.lisp
cac-t-u-s_om-sharp/build/build.lisp
;;; OpenMusic build file ;;; load this file then evaluate the following form : ;;; (clos::set-clos-initarg-checking nil) ;;; a faire au debut... ;;; (objc:make-autorelease-pool) ;;;======================= ;;; RUN: ;;;======================= ;;; (om::start-omsharp) ;;;======================= (in-package "CL-USER") ;(setf *print-circle* NIL) (load (current-pathname "./load-tools.lisp")) ;;;======================================= ;;; APP/VERSION DATA ;;;======================================= (defparameter *app-name* "om-sharp") (defparameter *version-major* 1) (defparameter *version-minor* 7) (defparameter *version-patch* 0) (defparameter *version-update* 0) (defparameter *version-beta* nil) (defparameter *version* (+ *version-major* (/ *version-minor* 100.0) (/ *version-patch* 10000.0) (/ *version-update* 1000000.0))) (defparameter *version-string* (concatenate 'string (format nil "~d.~d" *version-major* *version-minor*) (if (and *version-patch* (plusp *version-patch*)) (format nil ".~d" *version-patch*) "") (if *version-beta* "-beta" "") (if (and *version-update* (plusp *version-update*)) (format nil "-u~d" *version-update*) "") )) (defparameter *release-language* :en) (defparameter *release-date* (subseq (sys::date-string nil nil) 0 10)) (defparameter *release-author* "jean bresson") (export '(*app-name* *version* *version-string* *release-language* *release-date* *release-author*) :cl-user) (defparameter *om-root-directory* (make-pathname :directory (butlast (pathname-directory *load-pathname*)))) ;;;======================================== ;;; FILE I/O ENCODING, USE UTF-8 AS DEFAULT ;;;======================================== #| (defun utf-8-file-encoding (pathname ef-spec buffer length) (declare (ignore pathname buffer length)) (system:merge-ef-specs ef-spec :utf-8)) (defun unicode-file-encoding (pathname ef-spec buffer length) (declare (ignore pathname buffer length)) (system:merge-ef-specs ef-spec :unicode)) (setq system:*file-encoding-detection-algorithm* (substitute 'utf-8-file-encoding 'system:locale-file-encoding system:*file-encoding-detection-algorithm*)) |# ;(pushnew :utf-8 system:*specific-valid-file-encodings*) ;(pushnew :latin-1 system:*specific-valid-file-encodings*) (lw::set-default-character-element-type 'character) ;;;======================================= ;;;; LOAD OM-API ;;;======================================= (load (merge-pathnames "src/api/om-lisp-LW/load-om-lisp.lisp" *om-root-directory*)) (load (merge-pathnames "src/api/om-api-LW/om-api.lisp" *om-root-directory*)) (load (merge-pathnames "src/api/foreign-interface/foreign-interface" *om-root-directory*)) ;;;======================================= ;;;; LOAD EXTERNAL LISP TOOLS ;;;======================================= (defparameter *externals-directory* (merge-pathnames "src/lisp-externals/" *om-root-directory*)) (require :asdf) (let ((slime/swank-loader (merge-pathnames "slime/swank-loader.lisp" *externals-directory*))) (if (probe-file slime/swank-loader) (load slime/swank-loader) (error "~S not found. You probably forgot to 'git submodule init' && 'git submodule update'" slime/swank-loader))) (setq swank-loader::*fasl-directory* (merge-pathnames "slime/fasl/" *externals-directory*)) (swank-loader:init :setup nil :load-contribs t) (load (merge-pathnames "ieee-floats/ieee-floats" *externals-directory*)) (load (merge-pathnames "mach-lib/mach-lib" *externals-directory*)) #+macosx(om-fi::add-foreign-loader 'mach::load-mach-lib) (progn (load (merge-pathnames "lispworks-udp/lispworks-udp.asd" *externals-directory*)) (asdf:operate 'asdf:load-op 'lispworks-udp) (push :udp *features*)) (load (merge-pathnames "XML/load-xml" *externals-directory*)) (progn (compile&load (merge-pathnames "Yason/package" *externals-directory*)) (compile&load (merge-pathnames "Yason/parse" *externals-directory*))) (progn (load (merge-pathnames "cl-svg/cl-svg.asd" *externals-directory*)) (asdf:load-system :cl-svg)) ;;;======================================= ;;;; LOAD THE SOURCES ;;;======================================= (defpackage :om-sharp (:use "OM-API" "OM-FI" "OM-LISP" "COMMON-LISP" "CL-USER" "HCL") (:nicknames "OM" "OPENMUSIC")) (in-package :om) (import '(cl-user:compile&load cl-user::decode-local-path) :om) (load (merge-pathnames "src/visual-language/load.lisp" cl-user::*om-root-directory*)) (load (merge-pathnames "src/player/load.lisp" cl-user::*om-root-directory*)) (editor:setup-indent "defclass*" 2 2 4) (editor:setup-indent "defclass!" 2 2 4) (editor:setup-indent "defmethod*" 0 2 4) (editor:setup-indent "defmethod!" 0 2 4) (editor:setup-indent "defgeneric*" 0 2 4) (push :om-sharp *features*) ;;; used for source tracking ;;; updated in delivered init call (om-lisp::om-set-source-tree-root-folder (merge-pathnames "src/" cl-user::*om-root-directory*)) (defparameter *om-packages* nil) (defparameter *packages-folder* (merge-pathnames "src/packages/" cl-user::*om-root-directory*)) (defun load-om-package (name) (let ((packager-loader (make-pathname :directory (append (pathname-directory *packages-folder*) (list name)) :name name :type "lisp"))) (if (probe-file packager-loader) (progn (print (format nil "LOADING PACKAGE: ~A" packager-loader)) (load packager-loader) (push name *om-packages*) name) (progn (print (format nil "PACKAGE LOADER NOT FOUND !!")) nil)) )) (defun find-om-package (name) (find name *om-packages* :test 'string-equal)) ;; can be called from a package... (defun require-om-package (name) (or (find-om-package name) (load-om-package name) (progn (capi:beep-pane) (print (format nil "Required package ~S not found !" name)) NIL))) (load-om-package "basic") (load-om-package "midi") (load-om-package "osc") (load-om-package "sequencer") (load-om-package "score") (load-om-package "sound") (load-om-package "sdif") (load-om-package "space") ;;;================================= ;;; Lisp formatting utils ;;;================================= (defun lisp-format-folder (dir &key exclude-folders) (loop for item in (oa::om-directory dir :directories t) unless (equal item dir) append (if (system::directory-pathname-p item) (unless (member (car (last (pathname-directory item))) exclude-folders :test 'string-equal) (lisp-format-folder item :exclude-folders exclude-folders)) (when (and (pathname-type item) (string= (pathname-type item) "lisp") (om-lisp::om-lisp-format-file item)) (list item)) ) )) (defun format-sources () (let ((formatted-files (lisp-format-folder (merge-pathnames "src/" cl-user::*om-root-directory*) :exclude-folders '("_BUILD" "lisp-externals" "lw-opengl" "foreign-interface" "libsndfile")))) (print (format nil "Formatting done: ~D files formatted" (length formatted-files))) (loop for file in formatted-files do (print (format nil " ~A" file))) )) ;=> Call this before comitting to the repository ! ; ; (format-sources) ; ;;;================================= ;;; Start ;;;================================= (defun cl-user::start-omsharp () (om::start-omsharp))
7,544
Common Lisp
.lisp
171
39.643275
119
0.620756
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
80212ae4dbf1397f90a9bb688c8a26fef3355c52736c180c02167c9c80cb4904
474
[ -1 ]
475
application-bundle.lisp
cac-t-u-s_om-sharp/build/mac/application-bundle.lisp
;;;============================== ;;; OM# application bundle for MacOS ;;; Loaded from the delivery file ;;;============================== (in-package "CL-USER") (capi:define-interface omsharp-application (capi::cocoa-default-application-interface) () (:menus (application-menu *full-app-name* ((:component (("About..." :callback 'om::show-about-win :callback-type :none))) (:component (("Preferences..." :callback 'om::show-preferences-win :accelerator "accelerator-," :callback-type :none))) (:component (("Hide OM#" :accelerator "accelerator-h" :callback-data :hidden) ("Hide Others" :accelerator "accelerator-meta-h" :callback-data :others-hidden) ("Show All" :callback-data :all-normal)) :callback #'(setf capi:top-level-interface-display-state) :callback-type :data-interface) (:component (("Quit" :accelerator "accelerator-q" :callback #'(lambda (interface) (capi:destroy interface)) :callback-type :interface))))) (open-recent-menu "Open Recent..." nil :items-function #'(lambda (interface) (mapcar #'(lambda (file) (make-instance 'capi::menu-item :title (namestring file) :callback #'(lambda () (om::open-om-document file)) :callback-type :none)) om::*om-recent-files*)) ) (file-menu "File" ((:component (("New Patch" :callback #'(lambda () (om::open-new-document :patch)) :callback-type :none :accelerator "accelerator-n") ("New Sequencer" :callback #'(lambda () (om::open-new-document :sequencer)) :callback-type :none) ("New Lisp function" :callback #'(lambda () (om::open-new-document :lispfun)) :callback-type :none) )) ("New Text/Lisp Buffer" :callback #'(lambda () (om-lisp::om-open-text-editor :lisp t)) :callback-type :none :accelerator "accelerator-N") (:component (("Open..." :accelerator "accelerator-o" :callback 'om::open-om-document :callback-type :none) open-recent-menu )) ) ) (windows-menu "Windows" ((:component (("Session Window" :callback 'om::show-main-window :accelerator "accelerator-shift-w" :callback-type :none) )) (:component (("Lisp Listener" :callback 'om::show-listener-win :callback-type :none :accelerator "accelerator-shift-l") )) )) ) (:menu-bar application-menu file-menu windows-menu) (:default-initargs :title *full-app-name* :application-menu 'application-menu ;:confirm-destroy-function 'quit-callback ;:destroy-callback #'(lambda (interface) (oa::om-exit-funcall)) ;:top-level-hook 'oa::interface-handle-error ;:window-styles '(:internal-borderles :never-iconic :textured-background) ;; :hides-on-deactivate-window) :toolbox ;:display-state :normal :message-callback 'omsharp-application-callback :dock-menu 'omsharp-dock-menu )) (capi:define-menu omsharp-dock-menu (self) "Dock Menu" ((:component (("Session Window" :callback 'om::show-main-window :accelerator "accelerator-shift-w" :callback-type :none) )) (:component (("Lisp Listener" :callback 'om::show-listener-win :callback-type :none :accelerator "accelerator-shift-l") )) ) ) (defun omsharp-application-callback (self message &rest args) (declare (ignore self)) (case message (:open-file (let* ((filename (pathname (car args))) (type (pathname-type filename))) (cond ((find type '("opat" "oseq" "olsp") :test 'string-equal) (oa::om-run-process "open doc" #'(lambda () (loop while (not om::*om-initialized*)) ;; leave time to load libs etc. (om::record-recent-file filename) (if om::*main-window* (capi:execute-with-interface om::*main-window* #'om::open-doc-from-file (om::extension-to-doctype type) filename) (om::open-doc-from-file (om::extension-to-doctype type) filename)) ) )) ((string-equal "lisp" type) (om::om-open-new-text-editor filename)) (t nil)) )))) (defun omsharp-interface () (capi:set-application-interface (make-instance 'omsharp-application)))
4,751
Common Lisp
.lisp
136
26.007353
117
0.563288
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
03a4cb7193dd9013b6f68a896dede0e0d054db71b4d4092692c32dae75329213
475
[ -1 ]
476
dde.lisp
cac-t-u-s_om-sharp/build/win/dde.lisp
;; -*- Mode: Lisp; rcs-header: "$Header: /hope/lwhope1-cam/hope.0/compound/23/LISPexamples/RCS/dde:lispworks-ide.lisp,v 1.13.8.1 2017/01/19 11:50:02 martin Exp $" -*- ;;;============================== ;;; OM# DDE server for Windows ;;; Loaded from the delivery file ;;;============================== ;;; ======================================================================== ;;; Copyright (c) 1987--2017 LispWorks Ltd. All rights reserved. ;;; ======================================================================== ;;; ======================================================================== ;;; examples/dde/lispworks-ide.lisp ;;; ;;; This example demonstrates DDE support for Windows Explorer interaction ;;; with the LispWorks IDE. ;;; ;;; To test it, you need to configure the Windows Explorer (below), and ;;; then you can do one of the following: ;;; a) load this file into an image and call ;;; (STARTUP-EDITOR-DDE-SERVER) ;;; b) Save an image with this file loaded and select it when configuring ;;; the Explorer in step (6) below. ;;; c) Load this file in .lispworks (or the siteinit file). ;;; d) Specify this file (or a file that loads it) as the -init file ;;; when configuring the Explorer. ;;; Configuring Windows Explorer: ;;; You can configure any file type, but it is assumed here that ;;; you want to configure the file type "lisp" to be opened ;;; by LispWorks. ;;; ;;; 1. Choose Tools->Folder Options... from any explorer window. ;;; 2. Select the File Types tab ;;; 3. if the extension "lisp" already exists, select it, ;;; otherwise click the "New" button and enter "lisp" as ;;; the extension. ;;; 4. With "lisp" selected, click on the "Advanced" button. ;;; 5. If the action "open" exists, double click on it. Otherwise ;;; click the "New" button and enter "open" as the "Action:" ;;; 6. Enter the LispWorks executable as the "application used to perform ;;; action". You can use the "Browse" button to find it. By default, ;;; it is "C:/Program Files/LispWorks/lispworks-<version>-<platform>.exe ;;; If you want it to load any special file (e.g. this file), add -init ;;; and the filename. ;;; 7. Select "Use DDE". ;;; 8. Enter [open("%1")] as the "message". ;;; The syntax of the square brackets is fixed. The word "open" ;;; is the function name, which must match the function name in ;;; WIN32:DEFINE-DDE-SERVER-FUNCTION below. The arguments in the ;;; parentheses must match the arguments of the function. ;;; 9. Enter LispWorks as the "application". ;;; This must must the :SERVICE name in WIN32:DEFINE-DDE-SERVER below. ;;; 10. Leave the "DDE Application Not Running:" blank. ;;; 11. Enter Editor as the "topic". ;;; This must match the topic in WIN32:DEFINE-DDE-DISPATCH-TOPIC below. ;;; 12. Click OK on the New Action dialog. ;;; 13. Click Close on the Add New File Type dialog and the Options dialog. ;;; ;;; Once you finished the configuration, you should be able to invoke ;;; LispWorks by clicking on a file with the extension "lisp" (or ;;; whatever extension you used). ;;; The code below also defines LOAD server-function. To make ;;; double-clicking cause LispWorks to load the file rather than edit ;;; it, you need to use [load("%1")] instead of [open("%1")] in the ;;; message (step (8) above). You can make opening a fasl be loading ;;; into LispWorks by using the message load with the appropriate fasl ;;; extension (in steps (2) and (3)): ;;; 32-bit LispWorks ofasl ;;; 64-bit LispWorks 64ofasl ;;; The code below demonstrates how to deal with issues that may arise ;;; in a "complex" application. ;;; ;;; The main point to note is that for the DDE server to work, the ;;; thread (a MP:PROCESS inside LISP) on which it was registered (the ;;; call to WIN32:START-DDE-SERVER) must be processing Windows ;;; messages. That means that this thread should not be involved in ;;; other activity which may cause it to stop processing Windows ;;; events. Below we use a dedicated process which processes Windows ;;; messages by using MP:WAIT-PROCESSING-EVENTS. ;;; ;;; The other problems are all to do with starting up. The Windows ;;; mechanism that the Windows Explorer uses waits for the first ;;; thread in the process that it starts to process Windows messages. ;;; If this thread does not process DDE messages, the operation fails. ;;; Therefore it is essential to start the DDE server (i.e. call ;;; WIN32:START-DDE-SERVER) before starting any other thread that may ;;; process Windows messages. This includes any GUI thread. ;;; ;;; The "application" that is used here is the LispWorks IDE, which ;;; does start GUI threads. Normally, you can write your code to start ;;; the DDE server, and then start other processes after ;;; WIN32:START-DDE-SERVER was called. But the IDE starts ;;; automatically, so the code below must make sure that ;;; WIN32:START-DDE-SERVER is called before the IDE windows are made. ;;; ;;; This raises another issue, because the DDE callback below calls ;;; ED, and it should interact properly with the IDE (for example, if ;;; you use MDI, it should use an editor inside the MDI). For this to ;;; work, the code needs to make sure that the IDE is ready before it ;;; actually processes DDE events. ;;; The order of actions needs to be: ;;; 1) Call WIN32:START-DDE-SERVER ;;; 2) Start the IDE windows ;;; 3) Start processing events ;;; ;;; To get the right order of action the code below hooks into the ;;; "Initialize LispWorks Tools" action (using DEFINE-ACTION), and ;;; action (2) above is actually ;;; (2.a) Telling the IDE that it can make windows ;;; (2.b) Wait for the IDE to make its windows. ;;; This is implemented by RUN-LISPWORKS-IDE-SERVER-LOOP. ;;; ;;; The hook on "Initialize LispWorks Tools", ;;; STARTUP-EDITOR-DDE-SERVER, starts a process with ;;; RUN-LISPWORKS-IDE-SERVER-LOOP as the function, waits for it to ;;; signal that it can make windows, and then returns. The ;;; initialization of the environment then continues as usual, and ;;; once it finish (a listener has been made) ;;; RUN-LISPWORKS-IDE-SERVER-LOOP continues to process DDE events. ;;; The overall order of actions is: ;;; 1) The IDE starts to initialize. ;;; 2) STARTUP-EDITOR-DDE-SERVER is called, starts a process with ;;; RUN-LISPWORKS-IDE-SERVER-LOOP and calls PROCESS-WAIT. ;;; 3) RUN-LISPWORKS-IDE-SERVER-LOOP starts the DDE. ;;; 4) RUN-LISPWORKS-IDE-SERVER-LOOP signals that it started the DDE ;;; by calling SIGNAL-DDE-STARTED. ;;; 5) RUN-LISPWORKS-IDE-SERVER-LOOP calls WAIT-FOR-THE-APPLICATION ;;; which calls PROCESS-WAIT. ;;; 6) STARTUP-EDITOR-DDE-SERVER wakes up and returns. ;;; 7) The IDE continues to initialize. ;;; 8) When the listener is made, WAIT-FOR-THE-APPLICATION wakes ;;; up and returns. ;;; 9) RUN-LISPWORKS-IDE-SERVER-LOOP starts to process DDE events. (in-package "CL-USER") (eval-when (:compile-toplevel :load-toplevel :execute) (require "dde")) ;;; Define the server functionality (win32:define-dde-server omsharp-server () () (:service "OM#")) (win32:define-dde-dispatch-topic document :server omsharp-server) (win32:define-dde-server-function (open :topic document) :execute ((filename string)) (let ((path (print (probe-file filename)))) (when path (setf *omsharp-app-fileopen* t) (print path) (om::open-om-document path) t))) ;;; The initial function of the DDE server process. ;;; 1) start the DDE server ;;; 2.a) Signal that the DDE started for anybody that waits for it. ;;; 2.b) Wait for the "application" (i.e. the IDE) to be ready. ;;; 3) Process events. (defun run-omsharp-server-loop (wait-object) "Starts the DDE server and runs its message loop." (win32:start-dde-server 'omsharp-server) ;; (1) (signal-dde-started wait-object) ;; (2.a) (wait-for-the-application) ;; (2.b) (my-loop-processing-dde-events)) ;; (3) ;;; (3) Processing events. This could be just a call ;;; (mp:wait-processing-events nil) ;;; if you don't have any periodic cleanups. (defun my-loop-processing-dde-events () (loop ;;; (mp:wait-processing-events 100) ;;; (do-periodic-cleanups) (mp:wait-processing-events 100) )) ;;; (2.b) This one waits for the "application" (i.e te IDE) to be ready. ;;; It checks for that by checking if there is any LW-TOOLS:LISTENER ;;; running. (defun wait-for-the-application () (mp:process-wait "Waiting for environment to start" 'capi:collect-interfaces 'om::om-main-window)) ;;;; If an image was saved with this file loaded, this ;;;; gives the option to start LispWorks without it ;;;; acting as a DDE server. (defun want-to-start-editor-dde-server () (not (SYSTEM::HAVE-LINE-ARGUMENT-P "-no-dde"))) ;;; (2.a) Signals that the DDE started. The waiting caller ;;; (in startup-editor-dde-server) waits for the ;;; car to become non-nil. (defun signal-dde-started (wait-object) (setf (car wait-object) t)) ;;; Start the Editor DDE server. ;;; First check if really want to do it. ;;; Create a process to run the DDE server, and then waits ;;; for it to be ready, so nothing else happens until ;;; win32:start-dde-server have been called. (defun startup-omsharp-dde-server (&optional screen) (declare (ignore screen)) (when (want-to-start-editor-dde-server) (let ((wait-object (list nil))) (mp:process-run-function "OM# DDE server" '() 'run-omsharp-server-loop wait-object) (mp:process-wait "Waiting for OM# DDE server to register" 'car wait-object)))) ; (startup-omsharp-dde-server)
9,634
Common Lisp
.lisp
195
47.620513
166
0.686988
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a4234c2b0d01d41ffe83846ff87b12bc501f5ee2f9a8b57da8ae54a008c336cd
476
[ -1 ]
477
foreign-interface.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/foreign-interface.lisp
;============================================================================ ; om#: visual programming language for computer-assisted music composition ;============================================================================ ; ; This program is free software. For information on usage ; and redistribution, see the "LICENSE" file in this distribution. ; ; 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. ; ;============================================================================ ; File author: J. Bresson ;============================================================================ ;;;========================================================= ;;; STANDARD INTERFACE FOR EXTERNAL PROGRAMS AND LIBRARIES ;;; USES CFFI ;;;========================================================= (defpackage :om-fi (:use :common-lisp) (:export :om-foreign-libraries-directory :om-foreign-library-pathname :om-load-foreign-library :om-load-foreign-libs)) (in-package :om-fi) ;;; CFFI (load (merge-pathnames "ffi/load-cffi" *load-pathname*)) ;;; REDEFINITION OF MEM ACCESSORS ;(cl-user::compile-file-if-needed (merge-pathnames "dereference.lisp" *load-pathname*)) ;(load (merge-pathnames "dereference" *load-pathname*)) ;;;======================== ;;; FOREIGN LIBRARIES ;;;======================== (defun string-until-char (string char) (let ((index (search char string))) (if index (values (subseq string 0 index) (subseq string (+ index 1))) (values string nil)))) ;;; changes the pathname to match with the default foreign lib pathname (defun om-foreign-library-pathname (lib) (let ((libraries-directory (om-foreign-libraries-directory))) (if (and libraries-directory (probe-file libraries-directory)) #+(or win32 linux) (namestring (make-pathname :directory (pathname-directory libraries-directory) :host (pathname-host libraries-directory) :device (pathname-device libraries-directory) :name (pathname-name lib) :type (pathname-type lib))) #+cocoa (let ((frameworkpos (position-if #'(lambda (name) (search ".framework" name)) (cdr (pathname-directory lib))))) (make-pathname :directory (append (pathname-directory libraries-directory) (if frameworkpos (subseq (pathname-directory lib) (1+ frameworkpos)))) :host (pathname-host libraries-directory) :device (pathname-device libraries-directory) :name (pathname-name lib) :type (pathname-type lib))) lib))) ;;; a redefinir pour changer de repertoire par defaut... ;(defun om-foreign-libraries-directory () nil) ; cl-user::*om-src-directory* ;(defvar *load-folder* cl-user::*om-src-directory*) (defvar *load-folder* (lw-tools::lisp-image-name)) ;;; dans le dossier de l'appli (defun om-foreign-libraries-directory () *load-folder*) ; #+win32(make-pathname :directory (pathname-directory (LISP-IMAGE-NAME)) ; :host (pathname-host (LISP-IMAGE-NAME)) :device (pathname-device (lw::LISP-IMAGE-NAME))) ; #+macosx(make-pathname :directory (append (pathname-directory *root-folder*) '("resources" "lib" "mac")) ; :host (pathname-host *root-folder*) :device (pathname-device *root-folder*)) ; #+linux(make-pathname :directory (append (pathname-directory *root-folder*) '("resources" "lib" "linux")) ; :host (pathname-host *root-folder*) :device (pathname-device *root-folder*)) ;;; We follow the CFFI conventions: ;;; ;;; (cffi::define-foreign-library opengl ;;; (:darwin (:framework "OpenGL")) ;;; (:unix (:or "libGL.so" "libGL.so.1" ;;; #p"/myhome/mylibGL.so")) ;;; (:windows "opengl32.dll") ;;; ;; an hypothetical example of a particular platform ;;; ((:and :some-system :some-cpu) "libGL-support.lib") ;;; ;; if no other clauses apply, this one will and a type will be ;;; ;; automatically 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 (or ;;; USE-FOREIGN-LIBRARY) the first clause matched by FEATUREP is ;;; processed. (defun om-load-foreign-library (name spec) (let ((lib (intern (string-upcase name) :keyword))) (eval `(cffi::define-foreign-library ,lib ,.spec)) (print (format nil "Loading foreign library: ~A" name)) (catch 'err (handler-bind ((error #'(lambda (err) (print (format nil "~A:~A" (type-of err) err)) (throw 'err nil)))) (cffi::load-foreign-library lib))))) (defvar *loaders* nil) (defun om-load-foreign-libs (&optional load-folder) (when load-folder (setf *load-folder* load-folder)) (mapcar 'funcall (reverse *loaders*))) (defun add-foreign-loader (fun) (pushnew fun *loaders*))
5,234
Common Lisp
.lisp
103
44.92233
112
0.588915
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fff352450fa7ffb8a1ca4383d91ec044abc83ee242f57772d1eb95acfd78a684
477
[ -1 ]
478
load-cffi.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/load-cffi.lisp
;;=========================================================================== ;;Load in recent CFFI ;; ;;Time-stamp: <2013-06-04 14:11:06 andersvi> ;; ;;This program is free software; you can redistribute it and/or modify ;;it under the terms of the GNU Lesser General Public License as published by ;;the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. ;; ;;You should have received a copy of the GNU Lesser General Public License ;;along with this program; if not, write to the Free Software ;;Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ;; ;;Author: Anders Vinjar ;;=========================================================================== (require 'asdf) (mapc #'(lambda (system) (let ((dir (if (consp system) (car system) system)) (asd-file (if (consp system) (cdr system) system))) (load (make-pathname :directory (append (pathname-directory *load-pathname*) (list dir)) :name asd-file :type "asd") :package :asdf))) '("alexandria" ;dependencies for newer cffi "babel" "trivial-features" ("CFFI" . "cffi") ("CFFI" . "cffi-grovel") ("CFFI" . "cffi-libffi") )) (pushnew :cffi *features*) (provide :cffi) (asdf:load-system :cffi)
1,531
Common Lisp
.lisp
39
36.794872
93
0.64455
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f8c266dcbecd8ea6ce3f4ebf72d927e65d92fd1db9670d707ad6182a877ca872
478
[ -1 ]
479
tf-xcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-xcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-xcl.lisp --- XCL trivial-features implementation. ;;; ;;; Copyright (C) 2009, 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) ;;;; Endianness ;;; XCL already pushes :LITTLE-ENDIAN. ;;;; OS ;;; XCL already pushes :LINUX, :UNIX, :FREEBSD, :NETBSD, :BSD and :WINDOWS. ;;;; CPU ;;; XCL already pushes :X86 and :X86-64.
1,499
Common Lisp
.lisp
32
45.625
75
0.736986
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
35a1dd2a44bbae75368e9d73ff4a2d3eb17bb1675e8dbcbe5984a16f8080a139
479
[ 103906, 245477 ]
480
tf-abcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-abcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-abcl.lisp --- ABCL trivial-features implementation. ;;; ;;; Copyright (C) 2009, 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) ;;;; Endianness (pushnew (let ((order (jcall "toString" (jstatic "nativeOrder" "java.nio.ByteOrder")))) (cond ((string-equal order "LITTLE_ENDIAN") :little-endian) ((string-equal order "BIG_ENDIAN") :big-endian) (t (error "Byte order ~A unknown" order)))) *features*) ;;;; OS ;;; ABCL already pushes :LINUX and :UNIX. ;;;; CPU ;;; ABCL already pushes :x86-64
1,789
Common Lisp
.lisp
39
41.666667
76
0.6875
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
757dffa2f9c94b831d8b629de3815f8ef0448ea88a679ba000a6428a39699316
480
[ 3696, 455236 ]
481
tf-mcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-mcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mcl.lisp --- Digitool MCL trivial-features implementation. ;;; ;;; Copyright (C) 2010, Chun Tian (binghe) <[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) ;;;; Endianness (pushnew :big-endian *features*) ;;;; OS ;;; MCL already pushes :UNIX and :DARWIN. (pushnew :bsd *features*) ;;;; CPU #+ppc-target (pushnew :ppc *features*)
1,493
Common Lisp
.lisp
33
44
70
0.739669
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8c4cf6b2181ec9e84f80948ae4ffa165c0e81d442c550a719f3d7960a2b1cee9
481
[ 162973, 387056 ]
482
tf-openmcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-openmcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-openmcl.lisp --- OpenMCL trivial-features implementation. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness (pushnew #+big-endian-target :big-endian #+little-endian-target :little-endian *features*) ;;;; OS ;;; OpenMCL already pushes :UNIX and :DARWIN. #+linux-target (pushnew :linux *features*) #+darwin (pushnew :bsd *features*) ;;;; CPU ;;; what about ppc64? #+ppc-target (pushnew :ppc *features*) #+x8664-target (pushnew :x86-64 *features*)
1,691
Common Lisp
.lisp
38
42.789474
70
0.734185
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
791b7988a4ed76a60d673d1dd5de7e08414ffb3cbc68a956169d43189a41ff2c
482
[ 241772, 483542 ]
483
tf-corman.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-corman.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-corman.lisp --- Corman Lisp implementation of trivial-features. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness (pushnew :little-endian *features*) ;;;; OS (pushnew :windows *features*) ;;;; CPU (pushnew :x86 *features*)
1,449
Common Lisp
.lisp
32
44.0625
70
0.743972
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f56ffe289851f2f1a9efe0f2f75e3115e71cffbcfbcaa604bbb31e06c30dd195
483
[ 240725, 394747 ]
484
tf-scl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-scl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-scl.lisp --- SCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness (pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2))) (setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff) (ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0) (#xfe (intern (symbol-name '#:big-endian) '#:keyword)) (#xff (intern (symbol-name '#:little-endian) '#:keyword)))) *features*) ;;;; OS ;;; SCL already pushes :unix, :bsd, :linux, :hpux, and :solaris ;;;; CPU ;;; SCL already pushes :amd64, :x86, :sparc, :sparc64, :hppa and :hppa64. ;;; For 64 bit CPUs the SCL pushes: :64bit #+amd64 (pushnew :x86-64 *features*)
1,915
Common Lisp
.lisp
39
46.435897
73
0.70182
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1ad43415f447e99e3987a38ab805993488621e4501839fbccbcb2d2b77edbb5a
484
[ 59962, 96965 ]
485
tf-mocl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-mocl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mocl.lisp --- MOCL trivial-features implementation. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness ;;; MOCL already pushes :LITTLE-ENDIAN. ;;;; OS ;;; MOCL already pushes :IOS, :DARWIN, :BSD, and :UNIX for iOS, ;;; and :ANDROID, :LINUX, and :UNIX for Android. ;;;; CPU ;;; MOCL already pushes :ARM.
1,528
Common Lisp
.lisp
33
45.090909
70
0.735887
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
01e7f0c301b8985d021823df7d1640b82f672091c99c0a2ae3e51a0ccae348d9
485
[ 345455, 388436 ]
486
tf-sbcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-sbcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-sbcl.lisp --- SBCL trivial-features implementation. ;;; ;;; Copyright (C) 2007-2009, 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) ;;;; Endianness (pushnew (sb-alien:with-alien ((ptr (array (sb-alien:unsigned 8) 2))) (setf (sb-sys:sap-ref-16 (sb-alien:alien-sap ptr) 0) #xfeff) (ecase (sb-sys:sap-ref-8 (sb-alien:alien-sap ptr) 0) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword)))) *features*) ;;;; OS ;;; SBCL already pushes :DARWIN, :LINUX, :BSD and :UNIX. #+win32 (progn ;; note: as of 2008 or so, SBCL doesn't push :UNIX and :WIN32 ;; simultaneously anymore. (setq *features* (remove :unix *features*)) (pushnew :windows *features*)) ;;;; CPU ;;; SBCL already pushes: :X86, :X86-64, and :PPC
1,978
Common Lisp
.lisp
43
43.302326
71
0.703684
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
123fce295cbd10a62206f8992a7812a67cb7b6ce827f2e56e91bd1bcdf56571b
486
[ 83885, 193875 ]
487
tf-ecl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-ecl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-ecl.lisp --- ECL implementation of trivial-features. ;;; ;;; Copyright (C) 2007-2009, 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) ;;;; Endianness (pushnew (let ((ptr (ffi:allocate-foreign-object :unsigned-short))) (unwind-protect (progn (setf (ffi:deref-pointer ptr :unsigned-short) #xfeff) (ecase (ffi:deref-pointer ptr :unsigned-byte) (#xfe (intern "BIG-ENDIAN" "KEYWORD")) (#xff (intern "LITTLE-ENDIAN" "KEYWORD")))) (ffi:free-foreign-object ptr))) *features*) ;;;; OS ;;; ECL already pushes :DARWIN, :LINUX, :UNIX (except on Darwin) and :BSD. #+darwin (pushnew :unix *features*) #+win32 (pushnew :windows *features*) ;;;; CPU ;;; FIXME: add more #+powerpc7450 (pushnew :ppc *features*) #+x86_64 (pushnew :x86-64 *features*) #+(or i386 i486 i586 i686) (pushnew :x86 *features*)
2,095
Common Lisp
.lisp
45
42.6
74
0.68952
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
75b0b94bd555e76996e1f18f5f7a7d585ceb3542cbb74b8bc497a14d7671392f
487
[ -1 ]
488
tf-mkcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-mkcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-mkcl.lisp --- MKCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007-2009, 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) ;;;; Endianness #-(or :little-endian :big-endian) (pushnew (let ((ptr (ffi:allocate-foreign-object :unsigned-short))) (unwind-protect (progn (setf (ffi:deref-pointer ptr :unsigned-short) #xfeff) (ecase (ffi:deref-pointer ptr :unsigned-byte) (#xfe (intern "BIG-ENDIAN" "KEYWORD")) (#xff (intern "LITTLE-ENDIAN" "KEYWORD")))) (ffi:free-foreign-object ptr))) *features*) ;;;; OS ;;; MKCL conforms to SPEC ;;;; CPU ;;; MKCL conforms to SPEC
1,883
Common Lisp
.lisp
41
41.682927
71
0.689204
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
885a34a0aafbee0f5a47392d71e9a221f60e9822e8f76b7a6c21e382db988846
488
[ 71224, 94055 ]
489
tf-lispworks.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-lispworks.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-lispworks.lisp --- Lispworks implementation of trivial-features. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness ;;; Lispworks pushes :LITTLE-ENDIAN. #-little-endian (pushnew :big-endian *features*) #-(and) (pushnew (fli:with-dynamic-foreign-objects () (let ((ptr (fli:alloca :type :byte :nelems 2))) (setf (fli:dereference ptr :type '(:unsigned :short)) #xfeff) (ecase (fli:dereference ptr :type '(:unsigned :byte)) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword))))) *features*) ;;;; OS ;;; Lispworks already pushes :DARWIN, :LINUX and :UNIX. #+win32 (pushnew :windows *features*) ;;; Pushing :BSD. (Make sure this list is complete.) #+(or darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; Lispworks already pushes :X86. #+powerpc (pushnew :ppc *features*)
2,118
Common Lisp
.lisp
46
43.130435
74
0.706796
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
db6d0064e7d78554cc69c374d7019970e26d99341c73d6ae50dc1d1c893a1090
489
[ 113219, 115575 ]
490
tf-clisp.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-clisp.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-clisp.lisp --- CLISP trivial-features implementation. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness (pushnew (intern (symbol-name (if sys::*big-endian* '#:big-endian '#:little-endian)) '#:keyword) *features*) ;;;; OS ;;; CLISP already exports :UNIX. #+win32 (pushnew :windows *features*) #-win32 (eval-when (:compile-toplevel :load-toplevel :execute) (pushnew (with-standard-io-syntax (read-from-string (format nil ":~(~A~)" (posix:uname-sysname (posix:uname))))) *features*)) #+(or darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; FIXME: not complete (pushnew (intern (symbol-name (cond ((string= (machine-type) "X86_64") '#:x86-64) ((member :pc386 *features*) '#:x86) ((string= (machine-type) "POWER MACINTOSH") '#:ppc))) '#:keyword) *features*)
2,215
Common Lisp
.lisp
53
36.584906
74
0.658457
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
de0d680f6beac90f5f8251f74244cecc426917e07e3db085a70641005223b16d
490
[ -1 ]
491
tf-allegro.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-allegro.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-allegro.lisp --- Allegro implementation of trivial-features. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness ;;; Allegro already pushes :LITTLE-ENDIAN and :BIG-ENDIAN. ;;;; OS ;;; Allegro already pushes :LINUX and :UNIX. #+mswindows (pushnew :windows *features*) #+macosx (pushnew :darwin *features*) ;;; Pushing :BSD. (Make sure this list is complete.) #+(or macosx darwin freebsd netbsd openbsd) (pushnew :bsd *features*) ;;;; CPU ;;; Allegro already pushes :X86 and :X86-64. ;;; what about PPC64? #+powerpc (pushnew :ppc *features*)
1,768
Common Lisp
.lisp
39
44.076923
70
0.739965
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e61f709a0c836ba1c186d4db197709e13541b52c18be15b7f8298ae7d7c5f551
491
[ 192598, 211707 ]
492
tf-cmucl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/src/tf-cmucl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tf-cmucl.lisp --- CMUCL implementation of trivial-features. ;;; ;;; Copyright (C) 2007, 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) ;;;; Endianness (pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2))) (setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff) (ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0) (#xfe (intern "BIG-ENDIAN" :keyword)) (#xff (intern "LITTLE-ENDIAN" :keyword)))) *features*) ;;;; OS ;;; CMUCL already pushes :UNIX, :BSD, :LINUX and :DARWIN. ;;;; CPU ;;; CMUCL already pushes :PPC and :X86.
1,764
Common Lisp
.lisp
37
44.945946
70
0.706977
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ba3a09ffd44e57286827af2e07b0ea70e5733872245cf5123e86dbc4a3ccd76c
492
[ 128010, 211512 ]
493
sysinfo.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/tests/sysinfo.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; sysinfo.lisp --- FFI definitions for GetSystemInfo(). ;;; ;;; Copyright (C) 2007, 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 :trivial-features-tests) (defctype word :unsigned-short) (defcenum (architecture word) (:amd64 9) (:ia64 6) (:intel 0) (:unknown #xffff)) (defcstruct (system-info :size 36) (processor-architecture architecture)) (load-foreign-library "kernel32.dll") (defcfun ("GetSystemInfo" %get-system-info :cconv :stdcall) :void (system-info :pointer)) ;;; only getting at the CPU architecture for now. (defun get-system-info () (with-foreign-object (si 'system-info) (%get-system-info si) (foreign-slot-value si 'system-info 'processor-architecture)))
1,863
Common Lisp
.lisp
42
42.666667
70
0.74366
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
02f393dd2a41c098de795cd587d4061a6b4045cabc797e7f691b597b745db457
493
[ 225896, 456355 ]
494
package.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/tests/package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- TRIVIAL-FEATURES-TESTS package definition. ;;; ;;; Copyright (C) 2007, 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) (defpackage :trivial-features-tests (:use :common-lisp :regression-test :alexandria :cffi))
1,430
Common Lisp
.lisp
31
44.225806
70
0.739442
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1e197c8c1e5eb336257ead13e97f9d3435de742047323b5f8ef9c2eeebfa0c4b
494
[ -1 ]
495
tests.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/tests/tests.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tests.lisp --- trivial-features tests. ;;; ;;; Copyright (C) 2007, 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 :trivial-features-tests) ;;;; Support Code #-windows (progn ;; Hmm, why not just use OSICAT-POSIX:UNAME? (defcfun ("uname" %uname) :int (buf :pointer)) ;; Get system identification. (defun uname () (with-foreign-object (buf 'utsname) (when (= (%uname buf) -1) (error "uname() returned -1")) (macrolet ((utsname-slot (name) `(foreign-string-to-lisp (foreign-slot-pointer buf 'utsname ',name)))) (values (utsname-slot sysname) ;; (utsname-slot nodename) ;; (utsname-slot release) ;; (utsname-slot version) (utsname-slot machine)))))) (defun mutually-exclusive-p (features) (= 1 (loop for feature in features when (featurep feature) count 1))) ;;;; Tests (deftest endianness.1 (with-foreign-object (p :uint16) (setf (mem-ref p :uint16) #xfeff) (ecase (mem-ref p :uint8) (#xfe (featurep :big-endian)) (#xff (featurep :little-endian)))) t) (defparameter *bsds* '(:darwin :netbsd :openbsd :freebsd)) (defparameter *unices* (list* :linux *bsds*)) #+windows (deftest os.1 (featurep (list* :or :unix *unices*)) nil) #-windows (deftest os.1 (featurep (make-keyword (string-upcase (uname)))) t) (deftest os.2 (if (featurep :bsd) (mutually-exclusive-p *bsds*) (featurep `(:not (:or ,@*bsds*)))) t) (deftest os.3 (if (featurep `(:or ,@*unices*)) (featurep :unix) t) t) (deftest os.4 (if (featurep :windows) (not (featurep :unix)) t) t) (deftest cpu.1 (mutually-exclusive-p '(:ppc :ppc64 :x86 :x86-64 :alpha :mips)) t) #+windows (deftest cpu.2 (case (get-system-info) (:intel (featurep :x86)) (:amd64 (featurep :x86-64)) (:ia64 nil) ; add this feature later! (t t)) t)
3,147
Common Lisp
.lisp
91
30.142857
71
0.654061
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
a22b77aa6c2bf1a5a243fecaa0dfff9b72f8c27873205d98de520e2ddf515b9f
495
[ -1 ]
496
utsname.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/trivial-features/tests/utsname.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; utsname.lisp --- Grovel definitions for uname(3). ;;; ;;; Copyright (C) 2007, 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 :trivial-features-tests) (include "sys/utsname.h") (cstruct utsname "struct utsname" (sysname "sysname" :type :char) (nodename "nodename" :type :char) (release "release" :type :char) (version "version" :type :char) (machine "machine" :type :char))
1,559
Common Lisp
.lisp
33
45.848485
70
0.736704
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8584bb974e814032d30252973d8e5c3d3ed6c184f283ad4dcfbf8d5c21cc8aa1
496
[ 82534, 411114 ]
497
package.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/package.lisp
(defpackage :alexandria.0.dev (:nicknames :alexandria) (:use :cl) #+sb-package-locks (:lock t) (:export ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BLESSED ;; ;; Binding constructs #:if-let #:when-let #:when-let* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; REVIEW IN PROGRESS ;; ;; Control flow ;; ;; -- no clear consensus yet -- #:cswitch #:eswitch #:switch ;; -- problem free? -- #:multiple-value-prog2 #:nth-value-or #:whichever #:xor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; REVIEW PENDING ;; ;; Definitions #:define-constant ;; Hash tables #:alist-hash-table #:copy-hash-table #:ensure-gethash #:hash-table-alist #:hash-table-keys #:hash-table-plist #:hash-table-values #:maphash-keys #:maphash-values #:plist-hash-table ;; Functions #:compose #:conjoin #:curry #:disjoin #:ensure-function #:ensure-functionf #:multiple-value-compose #:named-lambda #:rcurry ;; Lists #:alist-plist #:appendf #:nconcf #:reversef #:nreversef #:circular-list #:circular-list-p #:circular-tree-p #:doplist #:ensure-car #:ensure-cons #:ensure-list #:flatten #:lastcar #:make-circular-list #:map-product #:mappend #:nunionf #:plist-alist #:proper-list #:proper-list-length #:proper-list-p #:remove-from-plist #:remove-from-plistf #:delete-from-plist #:delete-from-plistf #:set-equal #:setp #:unionf ;; Numbers #:binomial-coefficient #:clamp #:count-permutations #:factorial #:gaussian-random #:iota #:lerp #:map-iota #:maxf #:mean #:median #:minf #:standard-deviation #:subfactorial #:variance ;; Arrays #:array-index #:array-length #:copy-array ;; Sequences #:copy-sequence #:deletef #:emptyp #:ends-with #:ends-with-subseq #:extremum #:first-elt #:last-elt #:length= #:map-combinations #:map-derangements #:map-permutations #:proper-sequence #:random-elt #:removef #:rotate #:sequence-of-length-p #:shuffle #:starts-with #:starts-with-subseq ;; Macros #:once-only #:parse-body #:parse-ordinary-lambda-list #:with-gensyms #:with-unique-names ;; Symbols #:ensure-symbol #:format-symbol #:make-gensym #:make-gensym-list #:make-keyword ;; Strings #:string-designator ;; Types #:negative-double-float #:negative-fixnum-p #:negative-float #:negative-float-p #:negative-long-float #:negative-long-float-p #:negative-rational #:negative-rational-p #:negative-real #:negative-single-float-p #:non-negative-double-float #:non-negative-double-float-p #:non-negative-fixnum #:non-negative-fixnum-p #:non-negative-float #:non-negative-float-p #:non-negative-integer-p #:non-negative-long-float #:non-negative-rational #:non-negative-real-p #:non-negative-short-float-p #:non-negative-single-float #:non-negative-single-float-p #:non-positive-double-float #:non-positive-double-float-p #:non-positive-fixnum #:non-positive-fixnum-p #:non-positive-float #:non-positive-float-p #:non-positive-integer #:non-positive-rational #:non-positive-real #:non-positive-real-p #:non-positive-short-float #:non-positive-short-float-p #:non-positive-single-float-p #:ordinary-lambda-list-keywords #:positive-double-float #:positive-double-float-p #:positive-fixnum #:positive-fixnum-p #:positive-float #:positive-float-p #:positive-integer #:positive-rational #:positive-real #:positive-real-p #:positive-short-float #:positive-short-float-p #:positive-single-float #:positive-single-float-p #:coercef #:negative-double-float-p #:negative-fixnum #:negative-integer #:negative-integer-p #:negative-real-p #:negative-short-float #:negative-short-float-p #:negative-single-float #:non-negative-integer #:non-negative-long-float-p #:non-negative-rational-p #:non-negative-real #:non-negative-short-float #:non-positive-integer-p #:non-positive-long-float #:non-positive-long-float-p #:non-positive-rational-p #:non-positive-single-float #:of-type #:positive-integer-p #:positive-long-float #:positive-long-float-p #:positive-rational-p #:type= ;; Conditions #:required-argument #:ignore-some-conditions #:simple-style-warning #:simple-reader-error #:simple-parse-error #:simple-program-error #:unwind-protect-case ;; Features #:featurep ;; io #:with-input-from-file #:with-output-to-file #:read-file-into-string #:write-string-into-file #:read-file-into-byte-vector #:write-byte-vector-into-file #:copy-stream #:copy-file ;; new additions collected at the end (subject to removal or further changes) #:symbolicate #:assoc-value #:rassoc-value #:destructuring-case #:destructuring-ccase #:destructuring-ecase ))
5,180
Common Lisp
.lisp
242
17.438017
80
0.634872
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
eeb40bbf3b2ffe74bde14fe0bbc573b591c9acbdbb1f789da15bc6fccb8db570
497
[ 299714 ]
498
types.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/types.lisp
(in-package :alexandria) (deftype array-index (&optional (length array-dimension-limit)) "Type designator for an index into array of LENGTH: an integer between 0 (inclusive) and LENGTH (exclusive). LENGTH defaults to ARRAY-DIMENSION-LIMIT." `(integer 0 (,length))) (deftype array-length (&optional (length array-dimension-limit)) "Type designator for a dimension of an array of LENGTH: an integer between 0 (inclusive) and LENGTH (inclusive). LENGTH defaults to ARRAY-DIMENSION-LIMIT." `(integer 0 ,length)) ;; This MACROLET will generate most of CDR5 (http://cdr.eurolisp.org/document/5/) ;; except the RATIO related definitions and ARRAY-INDEX. (macrolet ((frob (type &optional (base-type type)) (let ((subtype-names (list)) (predicate-names (list))) (flet ((make-subtype-name (format-control) (let ((result (format-symbol :alexandria format-control (symbol-name type)))) (push result subtype-names) result)) (make-predicate-name (sybtype-name) (let ((result (format-symbol :alexandria '#:~A-p (symbol-name sybtype-name)))) (push result predicate-names) result)) (make-docstring (range-beg range-end range-type) (let ((inf (ecase range-type (:negative "-inf") (:positive "+inf")))) (format nil "Type specifier denoting the ~(~A~) range from ~A to ~A." type (if (equal range-beg ''*) inf (ensure-car range-beg)) (if (equal range-end ''*) inf (ensure-car range-end)))))) (let* ((negative-name (make-subtype-name '#:negative-~a)) (non-positive-name (make-subtype-name '#:non-positive-~a)) (non-negative-name (make-subtype-name '#:non-negative-~a)) (positive-name (make-subtype-name '#:positive-~a)) (negative-p-name (make-predicate-name negative-name)) (non-positive-p-name (make-predicate-name non-positive-name)) (non-negative-p-name (make-predicate-name non-negative-name)) (positive-p-name (make-predicate-name positive-name)) (negative-extremum) (positive-extremum) (below-zero) (above-zero) (zero)) (setf (values negative-extremum below-zero above-zero positive-extremum zero) (ecase type (fixnum (values 'most-negative-fixnum -1 1 'most-positive-fixnum 0)) (integer (values ''* -1 1 ''* 0)) (rational (values ''* '(0) '(0) ''* 0)) (real (values ''* '(0) '(0) ''* 0)) (float (values ''* '(0.0E0) '(0.0E0) ''* 0.0E0)) (short-float (values ''* '(0.0S0) '(0.0S0) ''* 0.0S0)) (single-float (values ''* '(0.0F0) '(0.0F0) ''* 0.0F0)) (double-float (values ''* '(0.0D0) '(0.0D0) ''* 0.0D0)) (long-float (values ''* '(0.0L0) '(0.0L0) ''* 0.0L0)))) `(progn (deftype ,negative-name () ,(make-docstring negative-extremum below-zero :negative) `(,',base-type ,,negative-extremum ,',below-zero)) (deftype ,non-positive-name () ,(make-docstring negative-extremum zero :negative) `(,',base-type ,,negative-extremum ,',zero)) (deftype ,non-negative-name () ,(make-docstring zero positive-extremum :positive) `(,',base-type ,',zero ,,positive-extremum)) (deftype ,positive-name () ,(make-docstring above-zero positive-extremum :positive) `(,',base-type ,',above-zero ,,positive-extremum)) (declaim (inline ,@predicate-names)) (defun ,negative-p-name (n) (and (typep n ',type) (< n ,zero))) (defun ,non-positive-p-name (n) (and (typep n ',type) (<= n ,zero))) (defun ,non-negative-p-name (n) (and (typep n ',type) (<= ,zero n))) (defun ,positive-p-name (n) (and (typep n ',type) (< ,zero n))))))))) (frob fixnum integer) (frob integer) (frob rational) (frob real) (frob float) (frob short-float) (frob single-float) (frob double-float) (frob long-float)) (defun of-type (type) "Returns a function of one argument, which returns true when its argument is of TYPE." (lambda (thing) (typep thing type))) (define-compiler-macro of-type (&whole form type &environment env) ;; This can yeild a big benefit, but no point inlining the function ;; all over the place if TYPE is not constant. (if (constantp type env) (with-gensyms (thing) `(lambda (,thing) (typep ,thing ,type))) form)) (declaim (inline type=)) (defun type= (type1 type2) "Returns a primary value of T is TYPE1 and TYPE2 are the same type, and a secondary value that is true is the type equality could be reliably determined: primary value of NIL and secondary value of T indicates that the types are not equivalent." (multiple-value-bind (sub ok) (subtypep type1 type2) (cond ((and ok sub) (subtypep type2 type1)) (ok (values nil ok)) (t (multiple-value-bind (sub ok) (subtypep type2 type1) (declare (ignore sub)) (values nil ok)))))) (define-modify-macro coercef (type-spec) coerce "Modify-macro for COERCE.")
5,826
Common Lisp
.lisp
122
36.172131
95
0.549833
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
d2f492efcbc45d4485049e3a3af774f4e153014f016ea530c743f127a6aa63c2
498
[ -1 ]
499
io.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/io.lisp
;; Copyright (c) 2002-2006, Edward Marco Baringer ;; All rights reserved. (in-package :alexandria) (defmacro with-open-file* ((stream filespec &key direction element-type if-exists if-does-not-exist external-format) &body body) "Just like WITH-OPEN-FILE, but NIL values in the keyword arguments mean to use the default value specified for OPEN." (once-only (direction element-type if-exists if-does-not-exist external-format) `(with-open-stream (,stream (apply #'open ,filespec (append (when ,direction (list :direction ,direction)) (when ,element-type (list :element-type ,element-type)) (when ,if-exists (list :if-exists ,if-exists)) (when ,if-does-not-exist (list :if-does-not-exist ,if-does-not-exist)) (when ,external-format (list :external-format ,external-format))))) ,@body))) (defmacro with-input-from-file ((stream-name file-name &rest args &key (direction nil direction-p) &allow-other-keys) &body body) "Evaluate BODY with STREAM-NAME to an input stream on the file FILE-NAME. ARGS is sent as is to the call to OPEN except EXTERNAL-FORMAT, which is only sent to WITH-OPEN-FILE when it's not NIL." (declare (ignore direction)) (when direction-p (error "Can't specifiy :DIRECTION for WITH-INPUT-FROM-FILE.")) `(with-open-file* (,stream-name ,file-name :direction :input ,@args) ,@body)) (defmacro with-output-to-file ((stream-name file-name &rest args &key (direction nil direction-p) &allow-other-keys) &body body) "Evaluate BODY with STREAM-NAME to an output stream on the file FILE-NAME. ARGS is sent as is to the call to OPEN except EXTERNAL-FORMAT, which is only sent to WITH-OPEN-FILE when it's not NIL." (declare (ignore direction)) (when direction-p (error "Can't specifiy :DIRECTION for WITH-OUTPUT-TO-FILE.")) `(with-open-file* (,stream-name ,file-name :direction :output ,@args) ,@body)) (defun read-file-into-string (pathname &key (buffer-size 4096) external-format) "Return the contents of the file denoted by PATHNAME as a fresh string. The EXTERNAL-FORMAT parameter will be passed directly to WITH-OPEN-FILE unless it's NIL, which means the system default." (with-input-from-file (file-stream pathname :external-format external-format) (let ((*print-pretty* nil)) (with-output-to-string (datum) (let ((buffer (make-array buffer-size :element-type 'character))) (loop :for bytes-read = (read-sequence buffer file-stream) :do (write-sequence buffer datum :start 0 :end bytes-read) :while (= bytes-read buffer-size))))))) (defun write-string-into-file (string pathname &key (if-exists :error) if-does-not-exist external-format) "Write STRING to PATHNAME. The EXTERNAL-FORMAT parameter will be passed directly to WITH-OPEN-FILE unless it's NIL, which means the system default." (with-output-to-file (file-stream pathname :if-exists if-exists :if-does-not-exist if-does-not-exist :external-format external-format) (write-sequence string file-stream))) (defun read-file-into-byte-vector (pathname) "Read PATHNAME into a freshly allocated (unsigned-byte 8) vector." (with-input-from-file (stream pathname :element-type '(unsigned-byte 8)) (let ((length (file-length stream))) (assert length) (let ((result (make-array length :element-type '(unsigned-byte 8)))) (read-sequence result stream) result)))) (defun write-byte-vector-into-file (bytes pathname &key (if-exists :error) if-does-not-exist) "Write BYTES to PATHNAME." (check-type bytes (vector (unsigned-byte 8))) (with-output-to-file (stream pathname :if-exists if-exists :if-does-not-exist if-does-not-exist :element-type '(unsigned-byte 8)) (write-sequence bytes stream))) (defun copy-file (from to &key (if-to-exists :supersede) (element-type '(unsigned-byte 8)) finish-output) (with-input-from-file (input from :element-type element-type) (with-output-to-file (output to :element-type element-type :if-exists if-to-exists) (copy-stream input output :element-type element-type :finish-output finish-output)))) (defun copy-stream (input output &key (element-type (stream-element-type input)) (buffer-size 4096) (buffer (make-array buffer-size :element-type element-type)) (start 0) end finish-output) "Reads data from INPUT and writes it to OUTPUT. Both INPUT and OUTPUT must be streams, they will be passed to READ-SEQUENCE and WRITE-SEQUENCE and must have compatible element-types." (check-type start non-negative-integer) (check-type end (or null non-negative-integer)) (check-type buffer-size positive-integer) (when (and end (< end start)) (error "END is smaller than START in ~S" 'copy-stream)) (let ((output-position 0) (input-position 0)) (unless (zerop start) ;; FIXME add platform specific optimization to skip seekable streams (loop while (< input-position start) do (let ((n (read-sequence buffer input :end (min (length buffer) (- start input-position))))) (when (zerop n) (error "~@<Could not read enough bytes from the input to fulfill ~ the :START ~S requirement in ~S.~:@>" 'copy-stream start)) (incf input-position n)))) (assert (= input-position start)) (loop while (or (null end) (< input-position end)) do (let ((n (read-sequence buffer input :end (when end (min (length buffer) (- end input-position)))))) (when (zerop n) (if end (error "~@<Could not read enough bytes from the input to fulfill ~ the :END ~S requirement in ~S.~:@>" 'copy-stream end) (return))) (incf input-position n) (write-sequence buffer output :end n) (incf output-position n))) (when finish-output (finish-output output)) output-position))
7,142
Common Lisp
.lisp
137
38.49635
87
0.576434
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
37914a6b3772f0b8c07bc742d946537fb25b64e36503a064e40bf0595ace87e6
499
[ 324886 ]
500
symbols.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/symbols.lisp
(in-package :alexandria) (declaim (inline ensure-symbol)) (defun ensure-symbol (name &optional (package *package*)) "Returns a symbol with name designated by NAME, accessible in package designated by PACKAGE. If symbol is not already accessible in PACKAGE, it is interned there. Returns a secondary value reflecting the status of the symbol in the package, which matches the secondary return value of INTERN. Example: (ensure-symbol :cons :cl) => cl:cons, :external " (intern (string name) package)) (defun maybe-intern (name package) (values (if package (intern name (if (eq t package) *package* package)) (make-symbol name)))) (declaim (inline format-symbol)) (defun format-symbol (package control &rest arguments) "Constructs a string by applying ARGUMENTS to string designator CONTROL as if by FORMAT within WITH-STANDARD-IO-SYNTAX, and then creates a symbol named by that string. If PACKAGE is NIL, returns an uninterned symbol, if package is T, returns a symbol interned in the current package, and otherwise returns a symbol interned in the package designated by PACKAGE." (maybe-intern (with-standard-io-syntax (apply #'format nil (string control) arguments)) package)) (defun make-keyword (name) "Interns the string designated by NAME in the KEYWORD package." (intern (string name) :keyword)) (defun make-gensym (name) "If NAME is a non-negative integer, calls GENSYM using it. Otherwise NAME must be a string designator, in which case calls GENSYM using the designated string as the argument." (gensym (if (typep name '(integer 0)) name (string name)))) (defun make-gensym-list (length &optional (x "G")) "Returns a list of LENGTH gensyms, each generated as if with a call to MAKE-GENSYM, using the second (optional, defaulting to \"G\") argument." (let ((g (if (typep x '(integer 0)) x (string x)))) (loop repeat length collect (gensym g)))) (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))))))
2,497
Common Lisp
.lisp
55
40.436364
85
0.70148
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2bcaa63cc4ead28a52ae70c425cbe1af4094784f92f1f1cd33f1b98fde23b1cb
500
[ 209270 ]
501
strings.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/strings.lisp
(in-package :alexandria) (deftype string-designator () "A string designator type. A string designator is either a string, a symbol, or a character." `(or symbol string character))
185
Common Lisp
.lisp
5
35
78
0.765363
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3292a8707b514367087483e3a36fd83f8edce9b71037c9073ab6dddc04fa07d0
501
[ 152729 ]
502
sequences.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/sequences.lisp
(in-package :alexandria) ;; Make these inlinable by declaiming them INLINE here and some of them ;; NOTINLINE at the end of the file. Exclude functions that have a compiler ;; macro, because NOTINLINE is required to prevent compiler-macro expansion. (declaim (inline copy-sequence sequence-of-length-p)) (defun sequence-of-length-p (sequence length) "Return true if SEQUENCE is a sequence of length LENGTH. Signals an error if SEQUENCE is not a sequence. Returns FALSE for circular lists." (declare (type array-index length) (inline length) (optimize speed)) (etypecase sequence (null (zerop length)) (cons (let ((n (1- length))) (unless (minusp n) (let ((tail (nthcdr n sequence))) (and tail (null (cdr tail))))))) (vector (= length (length sequence))) (sequence (= length (length sequence))))) (defun rotate-tail-to-head (sequence n) (declare (type (integer 1) n)) (if (listp sequence) (let ((m (mod n (proper-list-length sequence)))) (if (null (cdr sequence)) sequence (let* ((tail (last sequence (+ m 1))) (last (cdr tail))) (setf (cdr tail) nil) (nconc last sequence)))) (let* ((len (length sequence)) (m (mod n len)) (tail (subseq sequence (- len m)))) (replace sequence sequence :start1 m :start2 0) (replace sequence tail) sequence))) (defun rotate-head-to-tail (sequence n) (declare (type (integer 1) n)) (if (listp sequence) (let ((m (mod (1- n) (proper-list-length sequence)))) (if (null (cdr sequence)) sequence (let* ((headtail (nthcdr m sequence)) (tail (cdr headtail))) (setf (cdr headtail) nil) (nconc tail sequence)))) (let* ((len (length sequence)) (m (mod n len)) (head (subseq sequence 0 m))) (replace sequence sequence :start1 0 :start2 m) (replace sequence head :start1 (- len m)) sequence))) (defun rotate (sequence &optional (n 1)) "Returns a sequence of the same type as SEQUENCE, with the elements of SEQUENCE rotated by N: N elements are moved from the end of the sequence to the front if N is positive, and -N elements moved from the front to the end if N is negative. SEQUENCE must be a proper sequence. N must be an integer, defaulting to 1. If absolute value of N is greater then the length of the sequence, the results are identical to calling ROTATE with (* (signum n) (mod n (length sequence))). Note: the original sequence may be destructively altered, and result sequence may share structure with it." (if (plusp n) (rotate-tail-to-head sequence n) (if (minusp n) (rotate-head-to-tail sequence (- n)) sequence))) (defun shuffle (sequence &key (start 0) end) "Returns a random permutation of SEQUENCE bounded by START and END. Original sequece may be destructively modified, and share storage with the original one. Signals an error if SEQUENCE is not a proper sequence." (declare (type fixnum start) (type (or fixnum null) end)) (etypecase sequence (list (let* ((end (or end (proper-list-length sequence))) (n (- end start))) (do ((tail (nthcdr start sequence) (cdr tail))) ((zerop n)) (rotatef (car tail) (car (nthcdr (random n) tail))) (decf n)))) (vector (let ((end (or end (length sequence)))) (loop for i from start below end do (rotatef (aref sequence i) (aref sequence (+ i (random (- end i)))))))) (sequence (let ((end (or end (length sequence)))) (loop for i from (- end 1) downto start do (rotatef (elt sequence i) (elt sequence (+ i (random (- end i))))))))) sequence) (defun random-elt (sequence &key (start 0) end) "Returns a random element from SEQUENCE bounded by START and END. Signals an error if the SEQUENCE is not a proper non-empty sequence, or if END and START are not proper bounding index designators for SEQUENCE." (declare (sequence sequence) (fixnum start) (type (or fixnum null) end)) (let* ((size (if (listp sequence) (proper-list-length sequence) (length sequence))) (end2 (or end size))) (cond ((zerop size) (error 'type-error :datum sequence :expected-type `(and sequence (not (satisfies emptyp))))) ((not (and (<= 0 start) (< start end2) (<= end2 size))) (error 'simple-type-error :datum (cons start end) :expected-type `(cons (integer 0 (,end2)) (or null (integer (,start) ,size))) :format-control "~@<~S and ~S are not valid bounding index designators for ~ a sequence of length ~S.~:@>" :format-arguments (list start end size))) (t (let ((index (+ start (random (- end2 start))))) (elt sequence index)))))) (declaim (inline remove/swapped-arguments)) (defun remove/swapped-arguments (sequence item &rest keyword-arguments) (apply #'remove item sequence keyword-arguments)) (define-modify-macro removef (item &rest remove-keywords) remove/swapped-arguments "Modify-macro for REMOVE. Sets place designated by the first argument to the result of calling REMOVE with ITEM, place, and the REMOVE-KEYWORDS.") (declaim (inline delete/swapped-arguments)) (defun delete/swapped-arguments (sequence item &rest keyword-arguments) (apply #'delete item sequence keyword-arguments)) (define-modify-macro deletef (item &rest remove-keywords) delete/swapped-arguments "Modify-macro for DELETE. Sets place designated by the first argument to the result of calling DELETE with ITEM, place, and the REMOVE-KEYWORDS.") (deftype proper-sequence () "Type designator for proper sequences, that is proper lists and sequences that are not lists." `(or proper-list (and (not list) sequence))) (defun emptyp (sequence) "Returns true if SEQUENCE is an empty sequence. Signals an error if SEQUENCE is not a sequence." (etypecase sequence (list (null sequence)) (sequence (zerop (length sequence))))) (defun length= (&rest sequences) "Takes any number of sequences or integers in any order. Returns true iff the length of all the sequences and the integers are equal. Hint: there's a compiler macro that expands into more efficient code if the first argument is a literal integer." (declare (dynamic-extent sequences) (inline sequence-of-length-p) (optimize speed)) (unless (cdr sequences) (error "You must call LENGTH= with at least two arguments")) ;; There's room for optimization here: multiple list arguments could be ;; traversed in parallel. (let* ((first (pop sequences)) (current (if (integerp first) first (length first)))) (declare (type array-index current)) (dolist (el sequences) (if (integerp el) (unless (= el current) (return-from length= nil)) (unless (sequence-of-length-p el current) (return-from length= nil))))) t) (define-compiler-macro length= (&whole form length &rest sequences) (cond ((zerop (length sequences)) form) (t (let ((optimizedp (integerp length))) (with-unique-names (tmp current) (declare (ignorable current)) `(locally (declare (inline sequence-of-length-p)) (let ((,tmp) ,@(unless optimizedp `((,current ,length)))) ,@(unless optimizedp `((unless (integerp ,current) (setf ,current (length ,current))))) (and ,@(loop :for sequence :in sequences :collect `(progn (setf ,tmp ,sequence) (if (integerp ,tmp) (= ,tmp ,(if optimizedp length current)) (sequence-of-length-p ,tmp ,(if optimizedp length current))))))))))))) (defun copy-sequence (type sequence) "Returns a fresh sequence of TYPE, which has the same elements as SEQUENCE." (if (typep sequence type) (copy-seq sequence) (coerce sequence type))) (defun first-elt (sequence) "Returns the first element of SEQUENCE. Signals a type-error if SEQUENCE is not a sequence, or is an empty sequence." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (cond ((consp sequence) (car sequence)) ((and (typep sequence '(and sequence (not list))) (plusp (length sequence))) (elt sequence 0)) (t (error 'type-error :datum sequence :expected-type '(and sequence (not (satisfies emptyp))))))) (defun (setf first-elt) (object sequence) "Sets the first element of SEQUENCE. Signals a type-error if SEQUENCE is not a sequence, is an empty sequence, or if OBJECT cannot be stored in SEQUENCE." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (cond ((consp sequence) (setf (car sequence) object)) ((and (typep sequence '(and sequence (not list))) (plusp (length sequence))) (setf (elt sequence 0) object)) (t (error 'type-error :datum sequence :expected-type '(and sequence (not (satisfies emptyp))))))) (defun last-elt (sequence) "Returns the last element of SEQUENCE. Signals a type-error if SEQUENCE is not a proper sequence, or is an empty sequence." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (let ((len 0)) (cond ((consp sequence) (lastcar sequence)) ((and (typep sequence '(and sequence (not list))) (plusp (setf len (length sequence)))) (elt sequence (1- len))) (t (error 'type-error :datum sequence :expected-type '(and proper-sequence (not (satisfies emptyp)))))))) (defun (setf last-elt) (object sequence) "Sets the last element of SEQUENCE. Signals a type-error if SEQUENCE is not a proper sequence, is an empty sequence, or if OBJECT cannot be stored in SEQUENCE." (let ((len 0)) (cond ((consp sequence) (setf (lastcar sequence) object)) ((and (typep sequence '(and sequence (not list))) (plusp (setf len (length sequence)))) (setf (elt sequence (1- len)) object)) (t (error 'type-error :datum sequence :expected-type '(and proper-sequence (not (satisfies emptyp)))))))) (defun starts-with-subseq (prefix sequence &rest args &key (return-suffix nil) &allow-other-keys) "Test whether the first elements of SEQUENCE are the same (as per TEST) as the elements of PREFIX. If RETURN-SUFFIX is T the functions returns, as a second value, a displaced array pointing to the sequence after PREFIX." (remove-from-plistf args :return-suffix) (let ((sequence-length (length sequence)) (prefix-length (length prefix))) (if (<= prefix-length sequence-length) (let ((mismatch (apply #'mismatch prefix sequence args))) (if mismatch (if (< mismatch prefix-length) (values nil nil) (values t (when return-suffix (make-array (- sequence-length mismatch) :element-type (array-element-type sequence) :displaced-to sequence :displaced-index-offset prefix-length :adjustable nil)))) (values t (when return-suffix (make-array 0 :element-type (array-element-type sequence) :adjustable nil))))) (values nil nil)))) (defun ends-with-subseq (suffix sequence &key (test #'eql)) "Test whether SEQUENCE ends with SUFFIX. In other words: return true if the last (length SUFFIX) elements of SEQUENCE are equal to SUFFIX." (let ((sequence-length (length sequence)) (suffix-length (length suffix))) (when (< sequence-length suffix-length) ;; if SEQUENCE is shorter than SUFFIX, then SEQUENCE can't end with SUFFIX. (return-from ends-with-subseq nil)) (loop for sequence-index from (- sequence-length suffix-length) below sequence-length for suffix-index from 0 below suffix-length when (not (funcall test (elt sequence sequence-index) (elt suffix suffix-index))) do (return-from ends-with-subseq nil) finally (return t)))) (defun starts-with (object sequence &key (test #'eql) (key #'identity)) "Returns true if SEQUENCE is a sequence whose first element is EQL to OBJECT. Returns NIL if the SEQUENCE is not a sequence or is an empty sequence." (funcall test (funcall key (typecase sequence (cons (car sequence)) (sequence (if (plusp (length sequence)) (elt sequence 0) (return-from starts-with nil))) (t (return-from starts-with nil)))) object)) (defun ends-with (object sequence &key (test #'eql) (key #'identity)) "Returns true if SEQUENCE is a sequence whose last element is EQL to OBJECT. Returns NIL if the SEQUENCE is not a sequence or is an empty sequence. Signals an error if SEQUENCE is an improper list." (funcall test (funcall key (typecase sequence (cons ;; signals for improper lists (lastcar sequence)) (sequence ;; Can't use last-elt, as that signals an error ;; for empty sequences (let ((len (length sequence))) (if (plusp len) (elt sequence (1- len)) (return-from ends-with nil)))) (t (return-from ends-with nil)))) object)) (defun map-combinations (function sequence &key (start 0) end length (copy t)) "Calls FUNCTION with each combination of LENGTH constructable from the elements of the subsequence of SEQUENCE delimited by START and END. START defaults to 0, END to length of SEQUENCE, and LENGTH to the length of the delimited subsequence. (So unless LENGTH is specified there is only a single combination, which has the same elements as the delimited subsequence.) If COPY is true (the default) each combination is freshly allocated. If COPY is false all combinations are EQ to each other, in which case consequences are specified if a combination is modified by FUNCTION." (let* ((end (or end (length sequence))) (size (- end start)) (length (or length size)) (combination (subseq sequence 0 length)) (function (ensure-function function))) (if (= length size) (funcall function combination) (flet ((call () (funcall function (if copy (copy-seq combination) combination)))) (etypecase sequence ;; When dealing with lists we prefer walking back and ;; forth instead of using indexes. (list (labels ((combine-list (c-tail o-tail) (if (not c-tail) (call) (do ((tail o-tail (cdr tail))) ((not tail)) (setf (car c-tail) (car tail)) (combine-list (cdr c-tail) (cdr tail)))))) (combine-list combination (nthcdr start sequence)))) (vector (labels ((combine (count start) (if (zerop count) (call) (loop for i from start below end do (let ((j (- count 1))) (setf (aref combination j) (aref sequence i)) (combine j (+ i 1))))))) (combine length start))) (sequence (labels ((combine (count start) (if (zerop count) (call) (loop for i from start below end do (let ((j (- count 1))) (setf (elt combination j) (elt sequence i)) (combine j (+ i 1))))))) (combine length start))))))) sequence) (defun map-permutations (function sequence &key (start 0) end length (copy t)) "Calls function with each permutation of LENGTH constructable from the subsequence of SEQUENCE delimited by START and END. START defaults to 0, END to length of the sequence, and LENGTH to the length of the delimited subsequence." (let* ((end (or end (length sequence))) (size (- end start)) (length (or length size))) (labels ((permute (seq n) (let ((n-1 (- n 1))) (if (zerop n-1) (funcall function (if copy (copy-seq seq) seq)) (loop for i from 0 upto n-1 do (permute seq n-1) (if (evenp n-1) (rotatef (elt seq 0) (elt seq n-1)) (rotatef (elt seq i) (elt seq n-1))))))) (permute-sequence (seq) (permute seq length))) (if (= length size) ;; Things are simple if we need to just permute the ;; full START-END range. (permute-sequence (subseq sequence start end)) ;; Otherwise we need to generate all the combinations ;; of LENGTH in the START-END range, and then permute ;; a copy of the result: can't permute the combination ;; directly, as they share structure with each other. (let ((permutation (subseq sequence 0 length))) (flet ((permute-combination (combination) (permute-sequence (replace permutation combination)))) (declare (dynamic-extent #'permute-combination)) (map-combinations #'permute-combination sequence :start start :end end :length length :copy nil))))))) (defun map-derangements (function sequence &key (start 0) end (copy t)) "Calls FUNCTION with each derangement of the subsequence of SEQUENCE denoted by the bounding index designators START and END. Derangement is a permutation of the sequence where no element remains in place. SEQUENCE is not modified, but individual derangements are EQ to each other. Consequences are unspecified if calling FUNCTION modifies either the derangement or SEQUENCE." (let* ((end (or end (length sequence))) (size (- end start)) ;; We don't really care about the elements here. (derangement (subseq sequence 0 size)) ;; Bitvector that has 1 for elements that have been deranged. (mask (make-array size :element-type 'bit :initial-element 0))) (declare (dynamic-extent mask)) ;; ad hoc algorith (labels ((derange (place n) ;; Perform one recursive step in deranging the ;; sequence: PLACE is index of the original sequence ;; to derange to another index, and N is the number of ;; indexes not yet deranged. (if (zerop n) (funcall function (if copy (copy-seq derangement) derangement)) ;; Itarate over the indexes I of the subsequence to ;; derange: if I != PLACE and I has not yet been ;; deranged by an earlier call put the element from ;; PLACE to I, mark I as deranged, and recurse, ;; finally removing the mark. (loop for i from 0 below size do (unless (or (= place (+ i start)) (not (zerop (bit mask i)))) (setf (elt derangement i) (elt sequence place) (bit mask i) 1) (derange (1+ place) (1- n)) (setf (bit mask i) 0)))))) (derange start size) sequence))) (declaim (notinline sequence-of-length-p)) (define-condition no-extremum (error) () (:report (lambda (condition stream) (declare (ignore condition)) (format stream "Empty sequence in ~S." 'extremum)))) (defun extremum (sequence predicate &key key (start 0) end) "Returns the element of SEQUENCE that would appear first if the subsequence bounded by START and END was sorted using PREDICATE and KEY. EXTREMUM determines the relationship between two elements of SEQUENCE by using the PREDICATE function. PREDICATE should return true if and only if the first argument is strictly less than the second one (in some appropriate sense). Two arguments X and Y are considered to be equal if (FUNCALL PREDICATE X Y) and (FUNCALL PREDICATE Y X) are both false. The arguments to the PREDICATE function are computed from elements of SEQUENCE using the KEY function, if supplied. If KEY is not supplied or is NIL, the sequence element itself is used. If SEQUENCE is empty, NIL is returned." (let* ((pred-fun (ensure-function predicate)) (key-fun (unless (or (not key) (eq key 'identity) (eq key #'identity)) (ensure-function key))) (real-end (or end (length sequence)))) (cond ((> real-end start) (if key-fun (flet ((reduce-keys (a b) (if (funcall pred-fun (funcall key-fun a) (funcall key-fun b)) a b))) (declare (dynamic-extent #'reduce-keys)) (reduce #'reduce-keys sequence :start start :end real-end)) (flet ((reduce-elts (a b) (if (funcall pred-fun a b) a b))) (declare (dynamic-extent #'reduce-elts)) (reduce #'reduce-elts sequence :start start :end real-end)))) ((= real-end start) nil) (t (error "Invalid bounding indexes for sequence of length ~S: ~S ~S, ~S ~S" (length sequence) :start start :end end)))))
23,766
Common Lisp
.lisp
498
35.369478
100
0.5709
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
64bed0e987fb61d436d84893ebee691ab1022bbf67d44d831086a544f1210757
502
[ 390255 ]
503
tests.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/tests.lisp
(in-package :cl-user) (defpackage :alexandria-tests (:use :cl :alexandria #+sbcl :sb-rt #-sbcl :rtest) (:import-from #+sbcl :sb-rt #-sbcl :rtest #:*compile-tests* #:*expected-failures*)) (in-package :alexandria-tests) (defun run-tests (&key ((:compiled *compile-tests*))) (do-tests)) (defun hash-table-test-name (name) ;; Workaround for Clisp calling EQL in a hash-table FASTHASH-EQL. (hash-table-test (make-hash-table :test name))) ;;;; Arrays (deftest copy-array.1 (let* ((orig (vector 1 2 3)) (copy (copy-array orig))) (values (eq orig copy) (equalp orig copy))) nil t) (deftest copy-array.2 (let ((orig (make-array 1024 :fill-pointer 0))) (vector-push-extend 1 orig) (vector-push-extend 2 orig) (vector-push-extend 3 orig) (let ((copy (copy-array orig))) (values (eq orig copy) (equalp orig copy) (array-has-fill-pointer-p copy) (eql (fill-pointer orig) (fill-pointer copy))))) nil t t t) (deftest copy-array.3 (let* ((orig (vector 1 2 3)) (copy (copy-array orig))) (typep copy 'simple-array)) t) (deftest copy-array.4 (let ((orig (make-array 21 :adjustable t :fill-pointer 0))) (dotimes (n 42) (vector-push-extend n orig)) (let ((copy (copy-array orig :adjustable nil :fill-pointer nil))) (typep copy 'simple-array))) t) (deftest array-index.1 (typep 0 'array-index) t) ;;;; Conditions (deftest unwind-protect-case.1 (let (result) (unwind-protect-case () (random 10) (:normal (push :normal result)) (:abort (push :abort result)) (:always (push :always result))) result) (:always :normal)) (deftest unwind-protect-case.2 (let (result) (unwind-protect-case () (random 10) (:always (push :always result)) (:normal (push :normal result)) (:abort (push :abort result))) result) (:normal :always)) (deftest unwind-protect-case.3 (let (result1 result2 result3) (ignore-errors (unwind-protect-case () (error "FOOF!") (:normal (push :normal result1)) (:abort (push :abort result1)) (:always (push :always result1)))) (catch 'foof (unwind-protect-case () (throw 'foof 42) (:normal (push :normal result2)) (:abort (push :abort result2)) (:always (push :always result2)))) (block foof (unwind-protect-case () (return-from foof 42) (:normal (push :normal result3)) (:abort (push :abort result3)) (:always (push :always result3)))) (values result1 result2 result3)) (:always :abort) (:always :abort) (:always :abort)) (deftest unwind-protect-case.4 (let (result) (unwind-protect-case (aborted-p) (random 42) (:always (setq result aborted-p))) result) nil) (deftest unwind-protect-case.5 (let (result) (block foof (unwind-protect-case (aborted-p) (return-from foof) (:always (setq result aborted-p)))) result) t) ;;;; Control flow (deftest switch.1 (switch (13 :test =) (12 :oops) (13.0 :yay)) :yay) (deftest switch.2 (switch (13) ((+ 12 2) :oops) ((- 13 1) :oops2) (t :yay)) :yay) (deftest eswitch.1 (let ((x 13)) (eswitch (x :test =) (12 :oops) (13.0 :yay))) :yay) (deftest eswitch.2 (let ((x 13)) (eswitch (x :key 1+) (11 :oops) (14 :yay))) :yay) (deftest cswitch.1 (cswitch (13 :test =) (12 :oops) (13.0 :yay)) :yay) (deftest cswitch.2 (cswitch (13 :key 1-) (12 :yay) (13.0 :oops)) :yay) (deftest multiple-value-prog2.1 (multiple-value-prog2 (values 1 1 1) (values 2 20 200) (values 3 3 3)) 2 20 200) (deftest nth-value-or.1 (multiple-value-bind (a b c) (nth-value-or 1 (values 1 nil 1) (values 2 2 2)) (= a b c 2)) t) (deftest whichever.1 (let ((x (whichever 1 2 3))) (and (member x '(1 2 3)) t)) t) (deftest whichever.2 (let* ((a 1) (b 2) (c 3) (x (whichever a b c))) (and (member x '(1 2 3)) t)) t) (deftest xor.1 (xor nil nil 1 nil) 1 t) (deftest xor.2 (xor nil nil 1 2) nil nil) (deftest xor.3 (xor nil nil nil) nil t) ;;;; Definitions (deftest define-constant.1 (let ((name (gensym))) (eval `(define-constant ,name "FOO" :test 'equal)) (eval `(define-constant ,name "FOO" :test 'equal)) (values (equal "FOO" (symbol-value name)) (constantp name))) t t) (deftest define-constant.2 (let ((name (gensym))) (eval `(define-constant ,name 13)) (eval `(define-constant ,name 13)) (values (eql 13 (symbol-value name)) (constantp name))) t t) ;;;; Errors ;;; TYPEP is specified to return a generalized boolean and, for ;;; example, ECL exploits this by returning the superclasses of ERROR ;;; in this case. (defun errorp (x) (not (null (typep x 'error)))) (deftest required-argument.1 (multiple-value-bind (res err) (ignore-errors (required-argument)) (errorp err)) t) ;;;; Hash tables (deftest ensure-hash-table.1 (let ((table (make-hash-table)) (x (list 1))) (multiple-value-bind (value already-there) (ensure-gethash x table 42) (and (= value 42) (not already-there) (= 42 (gethash x table)) (multiple-value-bind (value2 already-there2) (ensure-gethash x table 13) (and (= value2 42) already-there2 (= 42 (gethash x table))))))) t) (deftest copy-hash-table.1 (let ((orig (make-hash-table :test 'eq :size 123)) (foo "foo")) (setf (gethash orig orig) t (gethash foo orig) t) (let ((eq-copy (copy-hash-table orig)) (eql-copy (copy-hash-table orig :test 'eql)) (equal-copy (copy-hash-table orig :test 'equal)) (equalp-copy (copy-hash-table orig :test 'equalp))) (list (eql (hash-table-size eq-copy) (hash-table-size orig)) (eql (hash-table-rehash-size eq-copy) (hash-table-rehash-size orig)) (hash-table-count eql-copy) (gethash orig eq-copy) (gethash (copy-seq foo) eql-copy) (gethash foo eql-copy) (gethash (copy-seq foo) equal-copy) (gethash "FOO" equal-copy) (gethash "FOO" equalp-copy)))) (t t 2 t nil t t nil t)) (deftest copy-hash-table.2 (let ((ht (make-hash-table)) (list (list :list (vector :A :B :C)))) (setf (gethash 'list ht) list) (let* ((shallow-copy (copy-hash-table ht)) (deep1-copy (copy-hash-table ht :key 'copy-list)) (list (gethash 'list ht)) (shallow-list (gethash 'list shallow-copy)) (deep1-list (gethash 'list deep1-copy))) (list (eq ht shallow-copy) (eq ht deep1-copy) (eq list shallow-list) (eq list deep1-list) ; outer list was copied. (eq (second list) (second shallow-list)) (eq (second list) (second deep1-list)) ; inner vector wasn't copied. ))) (nil nil t nil t t)) (deftest maphash-keys.1 (let ((keys nil) (table (make-hash-table))) (declare (notinline maphash-keys)) (dotimes (i 10) (setf (gethash i table) t)) (maphash-keys (lambda (k) (push k keys)) table) (set-equal keys '(0 1 2 3 4 5 6 7 8 9))) t) (deftest maphash-values.1 (let ((vals nil) (table (make-hash-table))) (declare (notinline maphash-values)) (dotimes (i 10) (setf (gethash i table) (- i))) (maphash-values (lambda (v) (push v vals)) table) (set-equal vals '(0 -1 -2 -3 -4 -5 -6 -7 -8 -9))) t) (deftest hash-table-keys.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) t)) (set-equal (hash-table-keys table) '(0 1 2 3 4 5 6 7 8 9))) t) (deftest hash-table-values.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash (gensym) table) i)) (set-equal (hash-table-values table) '(0 1 2 3 4 5 6 7 8 9))) t) (deftest hash-table-alist.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) (- i))) (let ((alist (hash-table-alist table))) (list (length alist) (assoc 0 alist) (assoc 3 alist) (assoc 9 alist) (assoc nil alist)))) (10 (0 . 0) (3 . -3) (9 . -9) nil)) (deftest hash-table-plist.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) (- i))) (let ((plist (hash-table-plist table))) (list (length plist) (getf plist 0) (getf plist 2) (getf plist 7) (getf plist nil)))) (20 0 -2 -7 nil)) (deftest alist-hash-table.1 (let* ((alist '((0 a) (1 b) (2 c))) (table (alist-hash-table alist))) (list (hash-table-count table) (gethash 0 table) (gethash 1 table) (gethash 2 table) (eq (hash-table-test-name 'eql) (hash-table-test table)))) (3 (a) (b) (c) t)) (deftest plist-hash-table.1 (let* ((plist '(:a 1 :b 2 :c 3)) (table (plist-hash-table plist :test 'eq))) (list (hash-table-count table) (gethash :a table) (gethash :b table) (gethash :c table) (gethash 2 table) (gethash nil table) (eq (hash-table-test-name 'eq) (hash-table-test table)))) (3 1 2 3 nil nil t)) ;;;; Functions (deftest disjoin.1 (let ((disjunction (disjoin (lambda (x) (and (consp x) :cons)) (lambda (x) (and (stringp x) :string))))) (list (funcall disjunction 'zot) (funcall disjunction '(foo bar)) (funcall disjunction "test"))) (nil :cons :string)) (deftest disjoin.2 (let ((disjunction (disjoin #'zerop))) (list (funcall disjunction 0) (funcall disjunction 1))) (t nil)) (deftest conjoin.1 (let ((conjunction (conjoin #'consp (lambda (x) (stringp (car x))) (lambda (x) (char (car x) 0))))) (list (funcall conjunction 'zot) (funcall conjunction '(foo)) (funcall conjunction '("foo")))) (nil nil #\f)) (deftest conjoin.2 (let ((conjunction (conjoin #'zerop))) (list (funcall conjunction 0) (funcall conjunction 1))) (t nil)) (deftest compose.1 (let ((composite (compose '1+ (lambda (x) (* x 2)) #'read-from-string))) (funcall composite "1")) 3) (deftest compose.2 (let ((composite (locally (declare (notinline compose)) (compose '1+ (lambda (x) (* x 2)) #'read-from-string)))) (funcall composite "2")) 5) (deftest compose.3 (let ((compose-form (funcall (compiler-macro-function 'compose) '(compose '1+ (lambda (x) (* x 2)) #'read-from-string) nil))) (let ((fun (funcall (compile nil `(lambda () ,compose-form))))) (funcall fun "3"))) 7) (deftest compose.4 (let ((composite (compose #'zerop))) (list (funcall composite 0) (funcall composite 1))) (t nil)) (deftest multiple-value-compose.1 (let ((composite (multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s))))))) (multiple-value-list (funcall composite "2 7"))) (3 1)) (deftest multiple-value-compose.2 (let ((composite (locally (declare (notinline multiple-value-compose)) (multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s)))))))) (multiple-value-list (funcall composite "2 11"))) (5 1)) (deftest multiple-value-compose.3 (let ((compose-form (funcall (compiler-macro-function 'multiple-value-compose) '(multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s))))) nil))) (let ((fun (funcall (compile nil `(lambda () ,compose-form))))) (multiple-value-list (funcall fun "2 9")))) (4 1)) (deftest multiple-value-compose.4 (let ((composite (multiple-value-compose #'truncate))) (multiple-value-list (funcall composite 9 2))) (4 1)) (deftest curry.1 (let ((curried (curry '+ 3))) (funcall curried 1 5)) 9) (deftest curry.2 (let ((curried (locally (declare (notinline curry)) (curry '* 2 3)))) (funcall curried 7)) 42) (deftest curry.3 (let ((curried-form (funcall (compiler-macro-function 'curry) '(curry '/ 8) nil))) (let ((fun (funcall (compile nil `(lambda () ,curried-form))))) (funcall fun 2))) 4) (deftest curry.4 (let* ((x 1) (curried (curry (progn (incf x) (lambda (y z) (* x y z))) 3))) (list (funcall curried 7) (funcall curried 7) x)) (42 42 2)) (deftest rcurry.1 (let ((r (rcurry '/ 2))) (funcall r 8)) 4) (deftest rcurry.2 (let* ((x 1) (curried (rcurry (progn (incf x) (lambda (y z) (* x y z))) 3))) (list (funcall curried 7) (funcall curried 7) x)) (42 42 2)) (deftest named-lambda.1 (let ((fac (named-lambda fac (x) (if (> x 1) (* x (fac (- x 1))) x)))) (funcall fac 5)) 120) (deftest named-lambda.2 (let ((fac (named-lambda fac (&key x) (if (> x 1) (* x (fac :x (- x 1))) x)))) (funcall fac :x 5)) 120) ;;;; Lists (deftest alist-plist.1 (alist-plist '((a . 1) (b . 2) (c . 3))) (a 1 b 2 c 3)) (deftest plist-alist.1 (plist-alist '(a 1 b 2 c 3)) ((a . 1) (b . 2) (c . 3))) (deftest unionf.1 (let* ((list (list 1 2 3)) (orig list)) (unionf list (list 1 2 4)) (values (equal orig (list 1 2 3)) (eql (length list) 4) (set-difference list (list 1 2 3 4)) (set-difference (list 1 2 3 4) list))) t t nil nil) (deftest nunionf.1 (let ((list (list 1 2 3))) (nunionf list (list 1 2 4)) (values (eql (length list) 4) (set-difference (list 1 2 3 4) list) (set-difference list (list 1 2 3 4)))) t nil nil) (deftest appendf.1 (let* ((list (list 1 2 3)) (orig list)) (appendf list '(4 5 6) '(7 8)) (list list (eq list orig))) ((1 2 3 4 5 6 7 8) nil)) (deftest nconcf.1 (let ((list1 (list 1 2 3)) (list2 (list 4 5 6))) (nconcf list1 list2 (list 7 8 9)) list1) (1 2 3 4 5 6 7 8 9)) (deftest circular-list.1 (let ((circle (circular-list 1 2 3))) (list (first circle) (second circle) (third circle) (fourth circle) (eq circle (nthcdr 3 circle)))) (1 2 3 1 t)) (deftest circular-list-p.1 (let* ((circle (circular-list 1 2 3 4)) (tree (list circle circle)) (dotted (cons circle t)) (proper (list 1 2 3 circle)) (tailcirc (list* 1 2 3 circle))) (list (circular-list-p circle) (circular-list-p tree) (circular-list-p dotted) (circular-list-p proper) (circular-list-p tailcirc))) (t nil nil nil t)) (deftest circular-list-p.2 (circular-list-p 'foo) nil) (deftest circular-tree-p.1 (let* ((circle (circular-list 1 2 3 4)) (tree1 (list circle circle)) (tree2 (let* ((level2 (list 1 nil 2)) (level1 (list level2))) (setf (second level2) level1) level1)) (dotted (cons circle t)) (proper (list 1 2 3 circle)) (tailcirc (list* 1 2 3 circle)) (quite-proper (list 1 2 3)) (quite-dotted (list 1 (cons 2 3)))) (list (circular-tree-p circle) (circular-tree-p tree1) (circular-tree-p tree2) (circular-tree-p dotted) (circular-tree-p proper) (circular-tree-p tailcirc) (circular-tree-p quite-proper) (circular-tree-p quite-dotted))) (t t t t t t nil nil)) (deftest circular-tree-p.2 (alexandria:circular-tree-p '#1=(#1#)) t) (deftest proper-list-p.1 (let ((l1 (list 1)) (l2 (list 1 2)) (l3 (cons 1 2)) (l4 (list (cons 1 2) 3)) (l5 (circular-list 1 2))) (list (proper-list-p l1) (proper-list-p l2) (proper-list-p l3) (proper-list-p l4) (proper-list-p l5))) (t t nil t nil)) (deftest proper-list-p.2 (proper-list-p '(1 2 . 3)) nil) (deftest proper-list.type.1 (let ((l1 (list 1)) (l2 (list 1 2)) (l3 (cons 1 2)) (l4 (list (cons 1 2) 3)) (l5 (circular-list 1 2))) (list (typep l1 'proper-list) (typep l2 'proper-list) (typep l3 'proper-list) (typep l4 'proper-list) (typep l5 'proper-list))) (t t nil t nil)) (deftest proper-list-length.1 (values (proper-list-length nil) (proper-list-length (list 1)) (proper-list-length (list 2 2)) (proper-list-length (list 3 3 3)) (proper-list-length (list 4 4 4 4)) (proper-list-length (list 5 5 5 5 5)) (proper-list-length (list 6 6 6 6 6 6)) (proper-list-length (list 7 7 7 7 7 7 7)) (proper-list-length (list 8 8 8 8 8 8 8 8)) (proper-list-length (list 9 9 9 9 9 9 9 9 9))) 0 1 2 3 4 5 6 7 8 9) (deftest proper-list-length.2 (flet ((plength (x) (handler-case (proper-list-length x) (type-error () :ok)))) (values (plength (list* 1)) (plength (list* 2 2)) (plength (list* 3 3 3)) (plength (list* 4 4 4 4)) (plength (list* 5 5 5 5 5)) (plength (list* 6 6 6 6 6 6)) (plength (list* 7 7 7 7 7 7 7)) (plength (list* 8 8 8 8 8 8 8 8)) (plength (list* 9 9 9 9 9 9 9 9 9)))) :ok :ok :ok :ok :ok :ok :ok :ok :ok) (deftest lastcar.1 (let ((l1 (list 1)) (l2 (list 1 2))) (list (lastcar l1) (lastcar l2))) (1 2)) (deftest lastcar.error.2 (handler-case (progn (lastcar (circular-list 1 2 3)) nil) (error () t)) t) (deftest setf-lastcar.1 (let ((l (list 1 2 3 4))) (values (lastcar l) (progn (setf (lastcar l) 42) (lastcar l)))) 4 42) (deftest setf-lastcar.2 (let ((l (circular-list 1 2 3))) (multiple-value-bind (res err) (ignore-errors (setf (lastcar l) 4)) (typep err 'type-error))) t) (deftest make-circular-list.1 (let ((l (make-circular-list 3 :initial-element :x))) (setf (car l) :y) (list (eq l (nthcdr 3 l)) (first l) (second l) (third l) (fourth l))) (t :y :x :x :y)) (deftest circular-list.type.1 (let* ((l1 (list 1 2 3)) (l2 (circular-list 1 2 3)) (l3 (list* 1 2 3 l2))) (list (typep l1 'circular-list) (typep l2 'circular-list) (typep l3 'circular-list))) (nil t t)) (deftest ensure-list.1 (let ((x (list 1)) (y 2)) (list (ensure-list x) (ensure-list y))) ((1) (2))) (deftest ensure-cons.1 (let ((x (cons 1 2)) (y nil) (z "foo")) (values (ensure-cons x) (ensure-cons y) (ensure-cons z))) (1 . 2) (nil) ("foo")) (deftest setp.1 (setp '(1)) t) (deftest setp.2 (setp nil) t) (deftest setp.3 (setp "foo") nil) (deftest setp.4 (setp '(1 2 3 1)) nil) (deftest setp.5 (setp '(1 2 3)) t) (deftest setp.6 (setp '(a :a)) t) (deftest setp.7 (setp '(a :a) :key 'character) nil) (deftest setp.8 (setp '(a :a) :key 'character :test (constantly nil)) t) (deftest set-equal.1 (set-equal '(1 2 3) '(3 1 2)) t) (deftest set-equal.2 (set-equal '("Xa") '("Xb") :test (lambda (a b) (eql (char a 0) (char b 0)))) t) (deftest set-equal.3 (set-equal '(1 2) '(4 2)) nil) (deftest set-equal.4 (set-equal '(a b c) '(:a :b :c) :key 'string :test 'equal) t) (deftest set-equal.5 (set-equal '(a d c) '(:a :b :c) :key 'string :test 'equal) nil) (deftest set-equal.6 (set-equal '(a b c) '(a b c d)) nil) (deftest map-product.1 (map-product 'cons '(2 3) '(1 4)) ((2 . 1) (2 . 4) (3 . 1) (3 . 4))) (deftest map-product.2 (map-product #'cons '(2 3) '(1 4)) ((2 . 1) (2 . 4) (3 . 1) (3 . 4))) (deftest flatten.1 (flatten '((1) 2 (((3 4))) ((((5)) 6)) 7)) (1 2 3 4 5 6 7)) (deftest remove-from-plist.1 (let ((orig '(a 1 b 2 c 3 d 4))) (list (remove-from-plist orig 'a 'c) (remove-from-plist orig 'b 'd) (remove-from-plist orig 'b) (remove-from-plist orig 'a) (remove-from-plist orig 'd 42 "zot") (remove-from-plist orig 'a 'b 'c 'd) (remove-from-plist orig 'a 'b 'c 'd 'x) (equal orig '(a 1 b 2 c 3 d 4)))) ((b 2 d 4) (a 1 c 3) (a 1 c 3 d 4) (b 2 c 3 d 4) (a 1 b 2 c 3) nil nil t)) (deftest mappend.1 (mappend (compose 'list '*) '(1 2 3) '(1 2 3)) (1 4 9)) (deftest assoc-value.1 (let ((key1 '(complex key)) (key2 'simple-key) (alist '()) (result '())) (push 1 (assoc-value alist key1 :test #'equal)) (push 2 (assoc-value alist key1 :test 'equal)) (push 42 (assoc-value alist key2)) (push 43 (assoc-value alist key2 :test 'eq)) (push (assoc-value alist key1 :test #'equal) result) (push (assoc-value alist key2) result) (push 'very (rassoc-value alist (list 2 1) :test #'equal)) (push (cdr (assoc '(very complex key) alist :test #'equal)) result) result) ((2 1) (43 42) (2 1))) ;;;; Numbers (deftest clamp.1 (list (clamp 1.5 1 2) (clamp 2.0 1 2) (clamp 1.0 1 2) (clamp 3 1 2) (clamp 0 1 2)) (1.5 2.0 1.0 2 1)) (deftest gaussian-random.1 (let ((min -0.2) (max +0.2)) (multiple-value-bind (g1 g2) (gaussian-random min max) (values (<= min g1 max) (<= min g2 max) (/= g1 g2) ;uh ))) t t t) (deftest iota.1 (iota 3) (0 1 2)) (deftest iota.2 (iota 3 :start 0.0d0) (0.0d0 1.0d0 2.0d0)) (deftest iota.3 (iota 3 :start 2 :step 3.0) (2.0 5.0 8.0)) (deftest map-iota.1 (let (all) (declare (notinline map-iota)) (values (map-iota (lambda (x) (push x all)) 3 :start 2 :step 1.1d0) all)) 3 (4.2d0 3.1d0 2.0d0)) (deftest lerp.1 (lerp 0.5 1 2) 1.5) (deftest lerp.2 (lerp 0.1 1 2) 1.1) (deftest mean.1 (mean '(1 2 3)) 2) (deftest mean.2 (mean '(1 2 3 4)) 5/2) (deftest mean.3 (mean '(1 2 10)) 13/3) (deftest median.1 (median '(100 0 99 1 98 2 97)) 97) (deftest median.2 (median '(100 0 99 1 98 2 97 96)) 193/2) (deftest variance.1 (variance (list 1 2 3)) 2/3) (deftest standard-deviation.1 (< 0 (standard-deviation (list 1 2 3)) 1) t) (deftest maxf.1 (let ((x 1)) (maxf x 2) x) 2) (deftest maxf.2 (let ((x 1)) (maxf x 0) x) 1) (deftest maxf.3 (let ((x 1) (c 0)) (maxf x (incf c)) (list x c)) (1 1)) (deftest maxf.4 (let ((xv (vector 0 0 0)) (p 0)) (maxf (svref xv (incf p)) (incf p)) (list p xv)) (2 #(0 2 0))) (deftest minf.1 (let ((y 1)) (minf y 0) y) 0) (deftest minf.2 (let ((xv (vector 10 10 10)) (p 0)) (minf (svref xv (incf p)) (incf p)) (list p xv)) (2 #(10 2 10))) (deftest subfactorial.1 (mapcar #'subfactorial (iota 22)) (1 0 1 2 9 44 265 1854 14833 133496 1334961 14684570 176214841 2290792932 32071101049 481066515734 7697064251745 130850092279664 2355301661033953 44750731559645106 895014631192902121 18795307255050944540)) ;;;; Arrays #+nil (deftest array-index.type) #+nil (deftest copy-array) ;;;; Sequences (deftest rotate.1 (list (rotate (list 1 2 3) 0) (rotate (list 1 2 3) 1) (rotate (list 1 2 3) 2) (rotate (list 1 2 3) 3) (rotate (list 1 2 3) 4)) ((1 2 3) (3 1 2) (2 3 1) (1 2 3) (3 1 2))) (deftest rotate.2 (list (rotate (vector 1 2 3 4) 0) (rotate (vector 1 2 3 4)) (rotate (vector 1 2 3 4) 2) (rotate (vector 1 2 3 4) 3) (rotate (vector 1 2 3 4) 4) (rotate (vector 1 2 3 4) 5)) (#(1 2 3 4) #(4 1 2 3) #(3 4 1 2) #(2 3 4 1) #(1 2 3 4) #(4 1 2 3))) (deftest rotate.3 (list (rotate (list 1 2 3) 0) (rotate (list 1 2 3) -1) (rotate (list 1 2 3) -2) (rotate (list 1 2 3) -3) (rotate (list 1 2 3) -4)) ((1 2 3) (2 3 1) (3 1 2) (1 2 3) (2 3 1))) (deftest rotate.4 (list (rotate (vector 1 2 3 4) 0) (rotate (vector 1 2 3 4) -1) (rotate (vector 1 2 3 4) -2) (rotate (vector 1 2 3 4) -3) (rotate (vector 1 2 3 4) -4) (rotate (vector 1 2 3 4) -5)) (#(1 2 3 4) #(2 3 4 1) #(3 4 1 2) #(4 1 2 3) #(1 2 3 4) #(2 3 4 1))) (deftest rotate.5 (values (rotate (list 1) 17) (rotate (list 1) -5)) (1) (1)) (deftest shuffle.1 (let ((s (shuffle (iota 100)))) (list (equal s (iota 100)) (every (lambda (x) (member x s)) (iota 100)) (every (lambda (x) (typep x '(integer 0 99))) s))) (nil t t)) (deftest shuffle.2 (let ((s (shuffle (coerce (iota 100) 'vector)))) (list (equal s (coerce (iota 100) 'vector)) (every (lambda (x) (find x s)) (iota 100)) (every (lambda (x) (typep x '(integer 0 99))) s))) (nil t t)) (deftest shuffle.3 (let* ((orig (coerce (iota 21) 'vector)) (copy (copy-seq orig))) (shuffle copy :start 10 :end 15) (list (every #'eql (subseq copy 0 10) (subseq orig 0 10)) (every #'eql (subseq copy 15) (subseq orig 15)))) (t t)) (deftest random-elt.1 (let ((s1 #(1 2 3 4)) (s2 '(1 2 3 4))) (list (dotimes (i 1000 nil) (unless (member (random-elt s1) s2) (return nil)) (when (/= (random-elt s1) (random-elt s1)) (return t))) (dotimes (i 1000 nil) (unless (member (random-elt s2) s2) (return nil)) (when (/= (random-elt s2) (random-elt s2)) (return t))))) (t t)) (deftest removef.1 (let* ((x '(1 2 3)) (x* x) (y #(1 2 3)) (y* y)) (removef x 1) (removef y 3) (list x x* y y*)) ((2 3) (1 2 3) #(1 2) #(1 2 3))) (deftest deletef.1 (let* ((x (list 1 2 3)) (x* x) (y (vector 1 2 3))) (deletef x 2) (deletef y 1) (list x x* y)) ((1 3) (1 3) #(2 3))) (deftest map-permutations.1 (let ((seq (list 1 2 3)) (seen nil) (ok t)) (map-permutations (lambda (s) (unless (set-equal s seq) (setf ok nil)) (when (member s seen :test 'equal) (setf ok nil)) (push s seen)) seq :copy t) (values ok (length seen))) t 6) (deftest proper-sequence.type.1 (mapcar (lambda (x) (typep x 'proper-sequence)) (list (list 1 2 3) (vector 1 2 3) #2a((1 2) (3 4)) (circular-list 1 2 3 4))) (t t nil nil)) (deftest emptyp.1 (mapcar #'emptyp (list (list 1) (circular-list 1) nil (vector) (vector 1))) (nil nil t t nil)) (deftest sequence-of-length-p.1 (mapcar #'sequence-of-length-p (list nil #() (list 1) (vector 1) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2)) (list 0 0 1 1 2 2 1 1 4 4)) (t t t t t t nil nil nil nil)) (deftest length=.1 (mapcar #'length= (list nil #() (list 1) (vector 1) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2)) (list 0 0 1 1 2 2 1 1 4 4)) (t t t t t t nil nil nil nil)) (deftest length=.2 ;; test the compiler macro (macrolet ((x (&rest args) (funcall (compile nil `(lambda () (length= ,@args)))))) (list (x 2 '(1 2)) (x '(1 2) '(3 4)) (x '(1 2) 2) (x '(1 2) 2 '(3 4)) (x 1 2 3))) (t t t t nil)) (deftest copy-sequence.1 (let ((l (list 1 2 3)) (v (vector #\a #\b #\c))) (declare (notinline copy-sequence)) (let ((l.list (copy-sequence 'list l)) (l.vector (copy-sequence 'vector l)) (l.spec-v (copy-sequence '(vector fixnum) l)) (v.vector (copy-sequence 'vector v)) (v.list (copy-sequence 'list v)) (v.string (copy-sequence 'string v))) (list (member l (list l.list l.vector l.spec-v)) (member v (list v.vector v.list v.string)) (equal l.list l) (equalp l.vector #(1 2 3)) (type= (upgraded-array-element-type 'fixnum) (array-element-type l.spec-v)) (equalp v.vector v) (equal v.list '(#\a #\b #\c)) (equal "abc" v.string)))) (nil nil t t t t t t)) (deftest first-elt.1 (mapcar #'first-elt (list (list 1 2 3) "abc" (vector :a :b :c))) (1 #\a :a)) (deftest first-elt.error.1 (mapcar (lambda (x) (handler-case (first-elt x) (type-error () :type-error))) (list nil #() 12 :zot)) (:type-error :type-error :type-error :type-error)) (deftest setf-first-elt.1 (let ((l (list 1 2 3)) (s (copy-seq "foobar")) (v (vector :a :b :c))) (setf (first-elt l) -1 (first-elt s) #\x (first-elt v) 'zot) (values l s v)) (-1 2 3) "xoobar" #(zot :b :c)) (deftest setf-first-elt.error.1 (let ((l 'foo)) (multiple-value-bind (res err) (ignore-errors (setf (first-elt l) 4)) (typep err 'type-error))) t) (deftest last-elt.1 (mapcar #'last-elt (list (list 1 2 3) (vector :a :b :c) "FOOBAR" #*001 #*010)) (3 :c #\R 1 0)) (deftest last-elt.error.1 (mapcar (lambda (x) (handler-case (last-elt x) (type-error () :type-error))) (list nil #() 12 :zot (circular-list 1 2 3) (list* 1 2 3 (circular-list 4 5)))) (:type-error :type-error :type-error :type-error :type-error :type-error)) (deftest setf-last-elt.1 (let ((l (list 1 2 3)) (s (copy-seq "foobar")) (b (copy-seq #*010101001))) (setf (last-elt l) '??? (last-elt s) #\? (last-elt b) 0) (values l s b)) (1 2 ???) "fooba?" #*010101000) (deftest setf-last-elt.error.1 (handler-case (setf (last-elt 'foo) 13) (type-error () :type-error)) :type-error) (deftest starts-with.1 (list (starts-with 1 '(1 2 3)) (starts-with 1 #(1 2 3)) (starts-with #\x "xyz") (starts-with 2 '(1 2 3)) (starts-with 3 #(1 2 3)) (starts-with 1 1) (starts-with nil nil)) (t t t nil nil nil nil)) (deftest starts-with.2 (values (starts-with 1 '(-1 2 3) :key '-) (starts-with "foo" '("foo" "bar") :test 'equal) (starts-with "f" '(#\f) :key 'string :test 'equal) (starts-with -1 '(0 1 2) :key #'1+) (starts-with "zot" '("ZOT") :test 'equal)) t t t nil nil) (deftest ends-with.1 (list (ends-with 3 '(1 2 3)) (ends-with 3 #(1 2 3)) (ends-with #\z "xyz") (ends-with 2 '(1 2 3)) (ends-with 1 #(1 2 3)) (ends-with 1 1) (ends-with nil nil)) (t t t nil nil nil nil)) (deftest ends-with.2 (values (ends-with 2 '(0 13 1) :key '1+) (ends-with "foo" (vector "bar" "foo") :test 'equal) (ends-with "X" (vector 1 2 #\X) :key 'string :test 'equal) (ends-with "foo" "foo" :test 'equal)) t t t nil) (deftest ends-with.error.1 (handler-case (ends-with 3 (circular-list 3 3 3 1 3 3)) (type-error () :type-error)) :type-error) (deftest sequences.passing-improper-lists (macrolet ((signals-error-p (form) `(handler-case (progn ,form nil) (type-error (e) t))) (cut (fn &rest args) (with-gensyms (arg) (print`(lambda (,arg) (apply ,fn (list ,@(substitute arg '_ args)))))))) (let ((circular-list (make-circular-list 5 :initial-element :foo)) (dotted-list (list* 'a 'b 'c 'd))) (loop for nth from 0 for fn in (list (cut #'lastcar _) (cut #'rotate _ 3) (cut #'rotate _ -3) (cut #'shuffle _) (cut #'random-elt _) (cut #'last-elt _) (cut #'ends-with :foo _)) nconcing (let ((on-circular-p (signals-error-p (funcall fn circular-list))) (on-dotted-p (signals-error-p (funcall fn dotted-list)))) (when (or (not on-circular-p) (not on-dotted-p)) (append (unless on-circular-p (let ((*print-circle* t)) (list (format nil "No appropriate error signalled when passing ~S to ~Ath entry." circular-list nth)))) (unless on-dotted-p (list (format nil "No appropriate error signalled when passing ~S to ~Ath entry." dotted-list nth))))))))) nil) (deftest with-unique-names.1 (let ((*gensym-counter* 0)) (let ((syms (with-unique-names (foo bar quux) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("FOO0" "BAR1" "QUUX2") (mapcar #'symbol-name syms))))) (nil t)) (deftest with-unique-names.2 (let ((*gensym-counter* 0)) (let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux #\q)) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("_foo_0" "-BAR-1" "q2") (mapcar #'symbol-name syms))))) (nil t)) (deftest with-unique-names.3 (let ((*gensym-counter* 0)) (multiple-value-bind (res err) (ignore-errors (eval '(let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux 42)) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("_foo_0" "-BAR-1" "q2") (mapcar #'symbol-name syms)))))) (errorp err))) t) (deftest once-only.1 (macrolet ((cons1.good (x) (once-only (x) `(cons ,x ,x))) (cons1.bad (x) `(cons ,x ,x))) (let ((y 0)) (list (cons1.good (incf y)) y (cons1.bad (incf y)) y))) ((1 . 1) 1 (2 . 3) 3)) (deftest once-only.2 (macrolet ((cons1 (x) (once-only ((y x)) `(cons ,y ,y)))) (let ((z 0)) (list (cons1 (incf z)) z (cons1 (incf z))))) ((1 . 1) 1 (2 . 2))) (deftest parse-body.1 (parse-body '("doc" "body") :documentation t) ("body") nil "doc") (deftest parse-body.2 (parse-body '("body") :documentation t) ("body") nil nil) (deftest parse-body.3 (parse-body '("doc" "body")) ("doc" "body") nil nil) (deftest parse-body.4 (parse-body '((declare (foo)) "doc" (declare (bar)) body) :documentation t) (body) ((declare (foo)) (declare (bar))) "doc") (deftest parse-body.5 (parse-body '((declare (foo)) "doc" (declare (bar)) body)) ("doc" (declare (bar)) body) ((declare (foo))) nil) (deftest parse-body.6 (multiple-value-bind (res err) (ignore-errors (parse-body '("foo" "bar" "quux") :documentation t)) (errorp err)) t) ;;;; Symbols (deftest ensure-symbol.1 (ensure-symbol :cons :cl) cons :external) (deftest ensure-symbol.2 (ensure-symbol "CONS" :alexandria) cons :inherited) (deftest ensure-symbol.3 (ensure-symbol 'foo :keyword) :foo :external) (deftest ensure-symbol.4 (ensure-symbol #\* :alexandria) * :inherited) (deftest format-symbol.1 (let ((s (format-symbol nil '#:x-~d 13))) (list (symbol-package s) (string= (string '#:x-13) (symbol-name s)))) (nil t)) (deftest format-symbol.2 (format-symbol :keyword '#:sym-~a (string :bolic)) :sym-bolic) (deftest format-symbol.3 (let ((*package* (find-package :cl))) (format-symbol t '#:find-~a (string 'package))) find-package) (deftest make-keyword.1 (list (make-keyword 'zot) (make-keyword "FOO") (make-keyword #\Q)) (:zot :foo :q)) (deftest make-gensym-list.1 (let ((*gensym-counter* 0)) (let ((syms (make-gensym-list 3 "FOO"))) (list (find-if 'symbol-package syms) (equal '("FOO0" "FOO1" "FOO2") (mapcar 'symbol-name syms))))) (nil t)) (deftest make-gensym-list.2 (let ((*gensym-counter* 0)) (let ((syms (make-gensym-list 3))) (list (find-if 'symbol-package syms) (equal '("G0" "G1" "G2") (mapcar 'symbol-name syms))))) (nil t)) ;;;; Type-system (deftest of-type.1 (locally (declare (notinline of-type)) (let ((f (of-type 'string))) (list (funcall f "foo") (funcall f 'bar)))) (t nil)) (deftest type=.1 (type= 'string 'string) t t) (deftest type=.2 (type= 'list '(or null cons)) t t) (deftest type=.3 (type= 'null '(and symbol list)) t t) (deftest type=.4 (type= 'string '(satisfies emptyp)) nil nil) (deftest type=.5 (type= 'string 'list) nil t) (macrolet ((test (type numbers) `(deftest ,(format-symbol t '#:cdr5.~a (string type)) (let ((numbers ,numbers)) (values (mapcar (of-type ',(format-symbol t '#:negative-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:non-positive-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:non-negative-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:positive-~a (string type))) numbers))) (t t t nil nil nil nil) (t t t t nil nil nil) (nil nil nil t t t t) (nil nil nil nil t t t)))) (test fixnum (list most-negative-fixnum -42 -1 0 1 42 most-positive-fixnum)) (test integer (list (1- most-negative-fixnum) -42 -1 0 1 42 (1+ most-positive-fixnum))) (test rational (list (1- most-negative-fixnum) -42/13 -1 0 1 42/13 (1+ most-positive-fixnum))) (test real (list most-negative-long-float -42/13 -1 0 1 42/13 most-positive-long-float)) (test float (list most-negative-short-float -42.02 -1.0 0.0 1.0 42.02 most-positive-short-float)) (test short-float (list most-negative-short-float -42.02s0 -1.0s0 0.0s0 1.0s0 42.02s0 most-positive-short-float)) (test single-float (list most-negative-single-float -42.02f0 -1.0f0 0.0f0 1.0f0 42.02f0 most-positive-single-float)) (test double-float (list most-negative-double-float -42.02d0 -1.0d0 0.0d0 1.0d0 42.02d0 most-positive-double-float)) (test long-float (list most-negative-long-float -42.02l0 -1.0l0 0.0l0 1.0l0 42.02l0 most-positive-long-float))) ;;;; Bindings (declaim (notinline opaque)) (defun opaque (x) x) (deftest if-let.1 (if-let (x (opaque :ok)) x :bad) :ok) (deftest if-let.2 (if-let (x (opaque nil)) :bad (and (not x) :ok)) :ok) (deftest if-let.3 (let ((x 1)) (if-let ((x 2) (y x)) (+ x y) :oops)) 3) (deftest if-let.4 (if-let ((x 1) (y nil)) :oops (and (not y) x)) 1) (deftest if-let.5 (if-let (x) :oops (not x)) t) (deftest if-let.error.1 (handler-case (eval '(if-let x :oops :oops)) (type-error () :type-error)) :type-error) (deftest when-let.1 (when-let (x (opaque :ok)) (setf x (cons x x)) x) (:ok . :ok)) (deftest when-let.2 (when-let ((x 1) (y nil) (z 3)) :oops) nil) (deftest when-let.3 (let ((x 1)) (when-let ((x 2) (y x)) (+ x y))) 3) (deftest when-let.error.1 (handler-case (eval '(when-let x :oops)) (type-error () :type-error)) :type-error) (deftest when-let*.1 (let ((x 1)) (when-let* ((x 2) (y x)) (+ x y))) 4) (deftest when-let*.2 (let ((y 1)) (when-let* (x y) (1+ x))) 2) (deftest when-let*.3 (when-let* ((x t) (y (consp x)) (z (error "OOPS"))) t) nil) (deftest when-let*.error.1 (handler-case (eval '(when-let* x :oops)) (type-error () :type-error)) :type-error) (deftest doplist.1 (let (keys values) (doplist (k v '(a 1 b 2 c 3) (values t (reverse keys) (reverse values) k v)) (push k keys) (push v values))) t (a b c) (1 2 3) nil nil) (deftest count-permutations.1 (values (count-permutations 31 7) (count-permutations 1 1) (count-permutations 2 1) (count-permutations 2 2) (count-permutations 3 2) (count-permutations 3 1)) 13253058000 1 2 2 6 3) (deftest binomial-coefficient.1 (alexandria:binomial-coefficient 1239 139) 28794902202288970200771694600561826718847179309929858835480006683522184441358211423695124921058123706380656375919763349913245306834194782172712255592710204598527867804110129489943080460154) (deftest copy-stream.1 (let ((data "sdkfjhsakfh weior763495ewofhsdfk sdfadlkfjhsadf woif sdlkjfhslkdfh sdklfjh")) (values (equal data (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out)))) (equal (subseq data 10 20) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :start 10 :end 20)))) (equal (subseq data 10) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :start 10)))) (equal (subseq data 0 20) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :end 20)))))) t t t t) (deftest extremum.1 (let ((n 0)) (dotimes (i 10) (let ((data (shuffle (coerce (iota 10000 :start i) 'vector))) (ok t)) (unless (eql i (extremum data #'<)) (setf ok nil)) (unless (eql i (extremum (coerce data 'list) #'<)) (setf ok nil)) (unless (eql (+ 9999 i) (extremum data #'>)) (setf ok nil)) (unless (eql (+ 9999 i) (extremum (coerce data 'list) #'>)) (setf ok nil)) (when ok (incf n)))) (when (eql 10 (extremum #(100 1 10 1000) #'> :start 1 :end 3)) (incf n)) (when (eql -1000 (extremum #(100 1 10 -1000) #'> :key 'abs)) (incf n)) (when (eq nil (extremum "" (lambda (a b) (error "wtf? ~S, ~S" a b)))) (incf n)) n) 13) (deftest starts-with-subseq.start1 (starts-with-subseq "foo" "oop" :start1 1) t nil) (deftest starts-with-subseq.start2 (starts-with-subseq "foo" "xfoop" :start2 1) t nil) (deftest format-symbol.print-case-bound (let ((upper (intern "FOO-BAR")) (lower (intern "foo-bar")) (*print-escape* nil)) (values (let ((*print-case* :downcase)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))) (let ((*print-case* :upcase)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))) (let ((*print-case* :capitalize)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))))) t t t) (deftest iota.fp-start-and-complex-integer-step (equal '(#C(0.0 0.0) #C(0.0 2.0) #C(0.0 4.0)) (iota 3 :start 0.0 :step #C(0 2))) t) (deftest parse-ordinary-lambda-list.1 (multiple-value-bind (req opt rest keys allowp aux keyp) (parse-ordinary-lambda-list '(a b c &optional d &key)) (and (equal '(a b c) req) (equal '((d nil nil)) opt) (equal '() keys) (not allowp) (not aux) (eq t keyp))))
49,429
Common Lisp
.lisp
1,667
20.827235
191
0.491122
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
f58297cb1280d89509d43c6895fba1910bdb366f61675113972035e0ec018ee0
503
[ -1 ]
504
control-flow.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/control-flow.lisp
(in-package :alexandria) (defun extract-function-name (spec) "Useful for macros that want to mimic the functional interface for functions like #'eq and 'eq." (if (and (consp spec) (member (first spec) '(quote function))) (second spec) spec)) (defun generate-switch-body (whole object clauses test key &optional default) (with-gensyms (value) (setf test (extract-function-name test)) (setf key (extract-function-name key)) (when (and (consp default) (member (first default) '(error cerror))) (setf default `(,@default "No keys match in SWITCH. Testing against ~S with ~S." ,value ',test))) `(let ((,value (,key ,object))) (cond ,@(mapcar (lambda (clause) (if (member (first clause) '(t otherwise)) (progn (when default (error "Multiple default clauses or illegal use of a default clause in ~S." whole)) (setf default `(progn ,@(rest clause))) '(())) (destructuring-bind (key-form &body forms) clause `((,test ,value ,key-form) ,@forms)))) clauses) (t ,default))))) (defmacro switch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Evaluates first matching clause, returning its values, or evaluates and returns the values of DEFAULT if no keys match." (generate-switch-body whole object clauses test key)) (defmacro eswitch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Like SWITCH, but signals an error if no key matches." (generate-switch-body whole object clauses test key '(error))) (defmacro cswitch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Like SWITCH, but signals a continuable error if no key matches." (generate-switch-body whole object clauses test key '(cerror "Return NIL from CSWITCH."))) (defmacro whichever (&rest possibilities &environment env) "Evaluates exactly one of POSSIBILITIES, chosen at random." (setf possibilities (mapcar (lambda (p) (macroexpand p env)) possibilities)) (if (every (lambda (p) (constantp p)) possibilities) `(svref (load-time-value (vector ,@possibilities)) (random ,(length possibilities))) (labels ((expand (possibilities position random-number) (if (null (cdr possibilities)) (car possibilities) (let* ((length (length possibilities)) (half (truncate length 2)) (second-half (nthcdr half possibilities)) (first-half (butlast possibilities (- length half)))) `(if (< ,random-number ,(+ position half)) ,(expand first-half position random-number) ,(expand second-half (+ position half) random-number)))))) (with-gensyms (random-number) (let ((length (length possibilities))) `(let ((,random-number (random ,length))) ,(expand possibilities 0 random-number))))))) (defmacro xor (&rest datums) "Evaluates its arguments one at a time, from left to right. If more then one argument evaluates to a true value no further DATUMS are evaluated, and NIL is returned as both primary and secondary value. If exactly one argument evaluates to true, its value is returned as the primary value after all the arguments have been evaluated, and T is returned as the secondary value. If no arguments evaluate to true NIL is retuned as primary, and T as secondary value." (with-gensyms (xor tmp true) `(let (,tmp ,true) (block ,xor ,@(mapcar (lambda (datum) `(if (setf ,tmp ,datum) (if ,true (return-from ,xor (values nil nil)) (setf ,true ,tmp)))) datums) (return-from ,xor (values ,true t)))))) (defmacro nth-value-or (nth-value &body forms) "Evaluates FORM arguments one at a time, until the NTH-VALUE returned by one of the forms is true. It then returns all the values returned by evaluating that form. If none of the forms return a true nth value, this form returns NIL." (once-only (nth-value) (with-gensyms (values) `(let ((,values (multiple-value-list ,(first forms)))) (if (nth ,nth-value ,values) (values-list ,values) ,(if (rest forms) `(nth-value-or ,nth-value ,@(rest forms)) nil)))))) (defmacro multiple-value-prog2 (first-form second-form &body forms) "Evaluates FIRST-FORM, then SECOND-FORM, and then FORMS. Yields as its value all the value returned by SECOND-FORM." `(progn ,first-form (multiple-value-prog1 ,second-form ,@forms)))
5,119
Common Lisp
.lisp
97
40.824742
107
0.59246
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
18353e7867d3f19bc7528ef869f5069aa861e89a55601646a0cc42f593eee45e
504
[ 37640 ]
505
conditions.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/conditions.lisp
(in-package :alexandria) (defun required-argument (&optional name) "Signals an error for a missing argument of NAME. Intended for use as an initialization form for structure and class-slots, and a default value for required keyword arguments." (error "Required argument ~@[~S ~]missing." name)) (define-condition simple-style-warning (simple-warning style-warning) ()) (defun simple-style-warning (message &rest args) (warn 'simple-style-warning :format-control message :format-arguments args)) ;; We don't specify a :report for simple-reader-error to let the ;; underlying implementation report the line and column position for ;; us. Unfortunately this way the message from simple-error is not ;; displayed, unless there's special support for that in the ;; implementation. But even then it's still inspectable from the ;; debugger... (define-condition simple-reader-error #-sbcl(simple-error reader-error) #+sbcl(sb-int:simple-reader-error) ()) (defun simple-reader-error (stream message &rest args) (error 'simple-reader-error :stream stream :format-control message :format-arguments args)) (define-condition simple-parse-error (simple-error parse-error) ()) (defun simple-parse-error (message &rest args) (error 'simple-parse-error :format-control message :format-arguments args)) (define-condition simple-program-error (simple-error program-error) ()) (defun simple-program-error (message &rest args) (error 'simple-program-error :format-control message :format-arguments args)) (defmacro ignore-some-conditions ((&rest conditions) &body body) "Similar to CL:IGNORE-ERRORS but the (unevaluated) CONDITIONS list determines which specific conditions are to be ignored." `(handler-case (progn ,@body) ,@(loop for condition in conditions collect `(,condition (c) (values nil c))))) (defmacro unwind-protect-case ((&optional abort-flag) protected-form &body clauses) "Like CL:UNWIND-PROTECT, but you can specify the circumstances that the cleanup CLAUSES are run. clauses ::= (:NORMAL form*)* | (:ABORT form*)* | (:ALWAYS form*)* Clauses can be given in any order, and more than one clause can be given for each circumstance. The clauses whose denoted circumstance occured, are executed in the order the clauses appear. ABORT-FLAG is the name of a variable that will be bound to T in CLAUSES if the PROTECTED-FORM aborted preemptively, and to NIL otherwise. Examples: (unwind-protect-case () (protected-form) (:normal (format t \"This is only evaluated if PROTECTED-FORM executed normally.~%\")) (:abort (format t \"This is only evaluated if PROTECTED-FORM aborted preemptively.~%\")) (:always (format t \"This is evaluated in either case.~%\"))) (unwind-protect-case (aborted-p) (protected-form) (:always (perform-cleanup-if aborted-p))) " (check-type abort-flag (or null symbol)) (let ((gflag (gensym "FLAG+"))) `(let ((,gflag t)) (unwind-protect (multiple-value-prog1 ,protected-form (setf ,gflag nil)) (let ,(and abort-flag `((,abort-flag ,gflag))) ,@(loop for (cleanup-kind . forms) in clauses collect (ecase cleanup-kind (:normal `(when (not ,gflag) ,@forms)) (:abort `(when ,gflag ,@forms)) (:always `(progn ,@forms)))))))))
3,363
Common Lisp
.lisp
74
41.364865
94
0.718301
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
3496993edfd1ee244a614cd684a509988cb5a0315414b10837159cc3d83cfae6
505
[ 482225 ]
506
numbers.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/numbers.lisp
(in-package :alexandria) (declaim (inline clamp)) (defun clamp (number min max) "Clamps the NUMBER into [min, max] range. Returns MIN if NUMBER is lesser then MIN and MAX if NUMBER is greater then MAX, otherwise returns NUMBER." (if (< number min) min (if (> number max) max number))) (defun gaussian-random (&optional min max) "Returns two gaussian random double floats as the primary and secondary value, optionally constrained by MIN and MAX. Gaussian random numbers form a standard normal distribution around 0.0d0. Sufficiently positive MIN or negative MAX will cause the algorithm used to take a very long time. If MIN is positive it should be close to zero, and similarly if MAX is negative it should be close to zero." (labels ((gauss () (loop for x1 = (- (random 2.0d0) 1.0d0) for x2 = (- (random 2.0d0) 1.0d0) for w = (+ (expt x1 2) (expt x2 2)) when (< w 1.0d0) do (let ((v (sqrt (/ (* -2.0d0 (log w)) w)))) (return (values (* x1 v) (* x2 v)))))) (guard (x min max) (unless (<= min x max) (tagbody :retry (multiple-value-bind (x1 x2) (gauss) (when (<= min x1 max) (setf x x1) (go :done)) (when (<= min x2 max) (setf x x2) (go :done)) (go :retry)) :done)) x)) (multiple-value-bind (g1 g2) (gauss) (values (guard g1 (or min g1) (or max g1)) (guard g2 (or min g2) (or max g2)))))) (declaim (inline iota)) (defun iota (n &key (start 0) (step 1)) "Return a list of n numbers, starting from START (with numeric contagion from STEP applied), each consequtive number being the sum of the previous one and STEP. START defaults to 0 and STEP to 1. Examples: (iota 4) => (0 1 2 3) (iota 3 :start 1 :step 1.0) => (1.0 2.0 3.0) (iota 3 :start -1 :step -1/2) => (-1 -3/2 -2) " (declare (type (integer 0) n) (number start step)) (loop repeat n ;; KLUDGE: get numeric contagion right for the first element too for i = (+ (- (+ start step) step)) then (+ i step) collect i)) (declaim (inline map-iota)) (defun map-iota (function n &key (start 0) (step 1)) "Calls FUNCTION with N numbers, starting from START (with numeric contagion from STEP applied), each consequtive number being the sum of the previous one and STEP. START defaults to 0 and STEP to 1. Returns N. Examples: (map-iota #'print 3 :start 1 :step 1.0) => 3 ;;; 1.0 ;;; 2.0 ;;; 3.0 " (declare (type (integer 0) n) (number start step)) (loop repeat n ;; KLUDGE: get numeric contagion right for the first element too for i = (+ start (- step step)) then (+ i step) do (funcall function i)) n) (declaim (inline lerp)) (defun lerp (v a b) "Returns the result of linear interpolation between A and B, using the interpolation coefficient V." (+ a (* v (- b a)))) (declaim (inline mean)) (defun mean (sample) "Returns the mean of SAMPLE. SAMPLE must be a sequence of numbers." (/ (reduce #'+ sample) (length sample))) (declaim (inline median)) (defun median (sample) "Returns median of SAMPLE. SAMPLE must be a sequence of real numbers." (let* ((vector (sort (copy-sequence 'vector sample) #'<)) (length (length vector)) (middle (truncate length 2))) (if (oddp length) (aref vector middle) (/ (+ (aref vector middle) (aref vector (1- middle))) 2)))) (declaim (inline variance)) (defun variance (sample &key (biased t)) "Variance of SAMPLE. Returns the biased variance if BIASED is true (the default), and the unbiased estimator of variance if BIASED is false. SAMPLE must be a sequence of numbers." (let ((mean (mean sample))) (/ (reduce (lambda (a b) (+ a (expt (- b mean) 2))) sample :initial-value 0) (- (length sample) (if biased 0 1))))) (declaim (inline standard-deviation)) (defun standard-deviation (sample &key (biased t)) "Standard deviation of SAMPLE. Returns the biased standard deviation if BIASED is true (the default), and the square root of the unbiased estimator for variance if BIASED is false (which is not the same as the unbiased estimator for standard deviation). SAMPLE must be a sequence of numbers." (sqrt (variance sample :biased biased))) (define-modify-macro maxf (&rest numbers) max "Modify-macro for MAX. Sets place designated by the first argument to the maximum of its original value and NUMBERS.") (define-modify-macro minf (&rest numbers) min "Modify-macro for MIN. Sets place designated by the first argument to the minimum of its original value and NUMBERS.") ;;;; Factorial ;;; KLUDGE: This is really dependant on the numbers in question: for ;;; small numbers this is larger, and vice versa. Ideally instead of a ;;; constant we would have RANGE-FAST-TO-MULTIPLY-DIRECTLY-P. (defconstant +factorial-bisection-range-limit+ 8) ;;; KLUDGE: This is really platform dependant: ideally we would use ;;; (load-time-value (find-good-direct-multiplication-limit)) instead. (defconstant +factorial-direct-multiplication-limit+ 13) (defun %multiply-range (i j) ;; We use a a bit of cleverness here: ;; ;; 1. For large factorials we bisect in order to avoid expensive bignum ;; multiplications: 1 x 2 x 3 x ... runs into bignums pretty soon, ;; and once it does that all further multiplications will be with bignums. ;; ;; By instead doing the multiplication in a tree like ;; ((1 x 2) x (3 x 4)) x ((5 x 6) x (7 x 8)) ;; we manage to get less bignums. ;; ;; 2. Division isn't exactly free either, however, so we don't bisect ;; all the way down, but multiply ranges of integers close to each ;; other directly. ;; ;; For even better results it should be possible to use prime ;; factorization magic, but Nikodemus ran out of steam. ;; ;; KLUDGE: We support factorials of bignums, but it seems quite ;; unlikely anyone would ever be able to use them on a modern lisp, ;; since the resulting numbers are unlikely to fit in memory... but ;; it would be extremely unelegant to define FACTORIAL only on ;; fixnums, _and_ on lisps with 16 bit fixnums this can actually be ;; needed. (labels ((bisect (j k) (declare (type (integer 1 #.most-positive-fixnum) j k)) (if (< (- k j) +factorial-bisection-range-limit+) (multiply-range j k) (let ((middle (+ j (truncate (- k j) 2)))) (* (bisect j middle) (bisect (+ middle 1) k))))) (bisect-big (j k) (declare (type (integer 1) j k)) (if (= j k) j (let ((middle (+ j (truncate (- k j) 2)))) (* (if (<= middle most-positive-fixnum) (bisect j middle) (bisect-big j middle)) (bisect-big (+ middle 1) k))))) (multiply-range (j k) (declare (type (integer 1 #.most-positive-fixnum) j k)) (do ((f k (* f m)) (m (1- k) (1- m))) ((< m j) f) (declare (type (integer 0 (#.most-positive-fixnum)) m) (type unsigned-byte f))))) (bisect i j))) (declaim (inline factorial)) (defun %factorial (n) (if (< n 2) 1 (%multiply-range 1 n))) (defun factorial (n) "Factorial of non-negative integer N." (check-type n (integer 0)) (%factorial n)) ;;;; Combinatorics (defun binomial-coefficient (n k) "Binomial coefficient of N and K, also expressed as N choose K. This is the number of K element combinations given N choises. N must be equal to or greater then K." (check-type n (integer 0)) (check-type k (integer 0)) (assert (>= n k)) (if (or (zerop k) (= n k)) 1 (let ((n-k (- n k))) ;; Swaps K and N-K if K < N-K because the algorithm ;; below is faster for bigger K and smaller N-K (when (< k n-k) (rotatef k n-k)) (if (= 1 n-k) n ;; General case, avoid computing the 1x...xK twice: ;; ;; N! 1x...xN (K+1)x...xN ;; -------- = ---------------- = ------------, N>1 ;; K!(N-K)! 1x...xK x (N-K)! (N-K)! (/ (%multiply-range (+ k 1) n) (%factorial n-k)))))) (defun subfactorial (n) "Subfactorial of the non-negative integer N." (check-type n (integer 0)) (if (zerop n) 1 (do ((x 1 (1+ x)) (a 0 (* x (+ a b))) (b 1 a)) ((= n x) a)))) (defun count-permutations (n &optional (k n)) "Number of K element permutations for a sequence of N objects. K defaults to N" (check-type n (integer 0)) (check-type k (integer 0)) (assert (>= n k)) (%multiply-range (1+ (- n k)) n))
9,161
Common Lisp
.lisp
221
34.443439
83
0.594122
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
59973c6d785e13dde281a30dfec6b0a7dd3cac43438eb9bdd69658e464fbb100
506
[ -1 ]
507
hash-tables.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/hash-tables.lisp
(in-package :alexandria) (defun copy-hash-table (table &key key test size rehash-size rehash-threshold) "Returns a copy of hash table TABLE, with the same keys and values as the TABLE. The copy has the same properties as the original, unless overridden by the keyword arguments. Before each of the original values is set into the new hash-table, KEY is invoked on the value. As KEY defaults to CL:IDENTITY, a shallow copy is returned by default." (setf key (or key 'identity)) (setf test (or test (hash-table-test table))) (setf size (or size (hash-table-size table))) (setf rehash-size (or rehash-size (hash-table-rehash-size table))) (setf rehash-threshold (or rehash-threshold (hash-table-rehash-threshold table))) (let ((copy (make-hash-table :test test :size size :rehash-size rehash-size :rehash-threshold rehash-threshold))) (maphash (lambda (k v) (setf (gethash k copy) (funcall key v))) table) copy)) (declaim (inline maphash-keys)) (defun maphash-keys (function table) "Like MAPHASH, but calls FUNCTION with each key in the hash table TABLE." (maphash (lambda (k v) (declare (ignore v)) (funcall function k)) table)) (declaim (inline maphash-values)) (defun maphash-values (function table) "Like MAPHASH, but calls FUNCTION with each value in the hash table TABLE." (maphash (lambda (k v) (declare (ignore k)) (funcall function v)) table)) (defun hash-table-keys (table) "Returns a list containing the keys of hash table TABLE." (let ((keys nil)) (maphash-keys (lambda (k) (push k keys)) table) keys)) (defun hash-table-values (table) "Returns a list containing the values of hash table TABLE." (let ((values nil)) (maphash-values (lambda (v) (push v values)) table) values)) (defun hash-table-alist (table) "Returns an association list containing the keys and values of hash table TABLE." (let ((alist nil)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist)) (defun hash-table-plist (table) "Returns a property list containing the keys and values of hash table TABLE." (let ((plist nil)) (maphash (lambda (k v) (setf plist (list* k v plist))) table) plist)) (defun alist-hash-table (alist &rest hash-table-initargs) "Returns a hash table containing the keys and values of the association list ALIST. Hash table is initialized using the HASH-TABLE-INITARGS." (let ((table (apply #'make-hash-table hash-table-initargs))) (dolist (cons alist) (setf (gethash (car cons) table) (cdr cons))) table)) (defun plist-hash-table (plist &rest hash-table-initargs) "Returns a hash table containing the keys and values of the property list PLIST. Hash table is initialized using the HASH-TABLE-INITARGS." (let ((table (apply #'make-hash-table hash-table-initargs))) (do ((tail plist (cddr tail))) ((not tail)) (setf (gethash (car tail) table) (cadr tail))) table)) (defmacro ensure-gethash (key hash-table &optional default) "Like GETHASH, but if KEY is not found in the HASH-TABLE saves the DEFAULT under key before returning it. Secondary return value is true if key was already in the table." `(multiple-value-bind (value ok) (gethash ,key ,hash-table) (if ok (values value ok) (values (setf (gethash ,key ,hash-table) ,default) nil))))
3,644
Common Lisp
.lisp
88
34.784091
83
0.657828
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
36d394a342ecad7f7695486af6452365e813d88ca5aea8eb482d679d0bd7a854
507
[ -1 ]
508
features.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/features.lisp
(in-package :alexandria) (defun featurep (feature-expression) "Returns T if the argument matches the state of the *FEATURES* list and NIL if it does not. FEATURE-EXPRESSION can be any atom or list acceptable to the reader macros #+ and #-." (etypecase feature-expression (symbol (not (null (member feature-expression *features*)))) (cons (check-type (first feature-expression) symbol) (eswitch ((first feature-expression) :test 'string=) (:and (every #'featurep (rest feature-expression))) (:or (some #'featurep (rest feature-expression))) (:not (assert (= 2 (length feature-expression))) (not (featurep (second feature-expression))))))))
717
Common Lisp
.lisp
13
48.230769
67
0.672831
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
62ef5e127d148013fe960c051a9d2d0ac840c1def960819d3b0c65d97e55958d
508
[ 449622 ]
509
functions.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/functions.lisp
(in-package :alexandria) ;;; To propagate return type and allow the compiler to eliminate the IF when ;;; it is known if the argument is function or not. (declaim (inline ensure-function)) (declaim (ftype (function (t) (values function &optional)) ensure-function)) (defun ensure-function (function-designator) "Returns the function designated by FUNCTION-DESIGNATOR: if FUNCTION-DESIGNATOR is a function, it is returned, otherwise it must be a function name and its FDEFINITION is returned." (if (functionp function-designator) function-designator (fdefinition function-designator))) (define-modify-macro ensure-functionf/1 () ensure-function) (defmacro ensure-functionf (&rest places) "Multiple-place modify macro for ENSURE-FUNCTION: ensures that each of PLACES contains a function." `(progn ,@(mapcar (lambda (x) `(ensure-functionf/1 ,x)) places))) (defun disjoin (predicate &rest more-predicates) "Returns a function that applies each of PREDICATE and MORE-PREDICATE functions in turn to its arguments, returning the primary value of the first predicate that returns true, without calling the remaining predicates. If none of the predicates returns true, NIL is returned." (declare (optimize (speed 3) (safety 1) (debug 1))) (let ((predicate (ensure-function predicate)) (more-predicates (mapcar #'ensure-function more-predicates))) (lambda (&rest arguments) (or (apply predicate arguments) (some (lambda (p) (declare (type function p)) (apply p arguments)) more-predicates))))) (defun conjoin (predicate &rest more-predicates) "Returns a function that applies each of PREDICATE and MORE-PREDICATE functions in turn to its arguments, returning NIL if any of the predicates returns false, without calling the remaining predicates. If none of the predicates returns false, returns the primary value of the last predicate." (if (null more-predicates) predicate (lambda (&rest arguments) (and (apply predicate arguments) ;; Cannot simply use CL:EVERY because we want to return the ;; non-NIL value of the last predicate if all succeed. (do ((tail (cdr more-predicates) (cdr tail)) (head (car more-predicates) (car tail))) ((not tail) (apply head arguments)) (unless (apply head arguments) (return nil))))))) (defun compose (function &rest more-functions) "Returns a function composed of FUNCTION and MORE-FUNCTIONS that applies its arguments to to each in turn, starting from the rightmost of MORE-FUNCTIONS, and then calling the next one with the primary value of the last." (declare (optimize (speed 3) (safety 1) (debug 1))) (reduce (lambda (f g) (let ((f (ensure-function f)) (g (ensure-function g))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) (funcall f (apply g arguments))))) more-functions :initial-value function)) (define-compiler-macro compose (function &rest more-functions) (labels ((compose-1 (funs) (if (cdr funs) `(funcall ,(car funs) ,(compose-1 (cdr funs))) `(apply ,(car funs) arguments)))) (let* ((args (cons function more-functions)) (funs (make-gensym-list (length args) "COMPOSE"))) `(let ,(loop for f in funs for arg in args collect `(,f (ensure-function ,arg))) (declare (optimize (speed 3) (safety 1) (debug 1))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) ,(compose-1 funs)))))) (defun multiple-value-compose (function &rest more-functions) "Returns a function composed of FUNCTION and MORE-FUNCTIONS that applies its arguments to each in turn, starting from the rightmost of MORE-FUNCTIONS, and then calling the next one with all the return values of the last." (declare (optimize (speed 3) (safety 1) (debug 1))) (reduce (lambda (f g) (let ((f (ensure-function f)) (g (ensure-function g))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) (multiple-value-call f (apply g arguments))))) more-functions :initial-value function)) (define-compiler-macro multiple-value-compose (function &rest more-functions) (labels ((compose-1 (funs) (if (cdr funs) `(multiple-value-call ,(car funs) ,(compose-1 (cdr funs))) `(apply ,(car funs) arguments)))) (let* ((args (cons function more-functions)) (funs (make-gensym-list (length args) "MV-COMPOSE"))) `(let ,(mapcar #'list funs args) (declare (optimize (speed 3) (safety 1) (debug 1))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) ,(compose-1 funs)))))) (defun curry (function &rest arguments) "Returns a function that applies ARGUMENTS and the arguments it is called with to FUNCTION." (declare (optimize (speed 3) (safety 1) (debug 1))) (let ((fn (ensure-function function))) (lambda (&rest more) (declare (dynamic-extent more)) ;; Using M-V-C we don't need to append the arguments. (multiple-value-call fn (values-list arguments) (values-list more))))) (define-compiler-macro curry (function &rest arguments) (let ((curries (make-gensym-list (length arguments) "CURRY")) (fun (gensym "FUN"))) `(let ((,fun (ensure-function ,function)) ,@(mapcar #'list curries arguments)) (declare (optimize (speed 3) (safety 1) (debug 1))) (lambda (&rest more) (apply ,fun ,@curries more))))) (defun rcurry (function &rest arguments) "Returns a function that applies the arguments it is called with and ARGUMENTS to FUNCTION." (declare (optimize (speed 3) (safety 1) (debug 1))) (let ((fn (ensure-function function))) (lambda (&rest more) (declare (dynamic-extent more)) (multiple-value-call fn (values-list more) (values-list arguments))))) (defmacro named-lambda (name lambda-list &body body) "Expands into a lambda-expression within whose BODY NAME denotes the corresponding function." `(labels ((,name ,lambda-list ,@body)) #',name))
6,127
Common Lisp
.lisp
131
41.473282
78
0.690906
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
68b06478ac17af94579c556a2e355aa92a189bd91f6329a6576e52671265ca26
509
[ 476874 ]
510
binding.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/binding.lisp
(in-package :alexandria) (defmacro if-let (bindings &body (then-form &optional else-form)) "Creates new variable bindings, and conditionally executes either THEN-FORM or ELSE-FORM. ELSE-FORM defaults to NIL. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, the THEN-FORM is executed with the bindings in effect, otherwise the ELSE-FORM is executed with the bindings in effect." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (if (and ,@variables) ,then-form ,else-form)))) (defmacro when-let (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) All initial-forms are executed sequentially in the specified order. Then all the variables are bound to the corresponding values. If all variables were bound to true values, then FORMS are executed as an implicit PROGN." (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings)) (variables (mapcar #'car binding-list))) `(let ,binding-list (when (and ,@variables) ,@forms)))) (defmacro when-let* (bindings &body forms) "Creates new variable bindings, and conditionally executes FORMS. BINDINGS must be either single binding of the form: (variable initial-form) or a list of bindings of the form: ((variable-1 initial-form-1) (variable-2 initial-form-2) ... (variable-n initial-form-n)) Each initial-form is executed in turn, and the variable bound to the corresponding value. Initial-form expressions can refer to variables previously bound by the WHEN-LET*. Execution of WHEN-LET* stops immediately if any initial-form evaluates to NIL. If all initial-forms evaluate to true, then FORMS are executed as an implicit PROGN." (let ((binding-list (if (and (consp bindings) (symbolp (car bindings))) (list bindings) bindings))) (labels ((bind (bindings forms) (if bindings `((let (,(car bindings)) (when ,(caar bindings) ,@(bind (cdr bindings) forms)))) forms))) `(let (,(car binding-list)) (when ,(caar binding-list) ,@(bind (cdr binding-list) forms))))))
3,047
Common Lisp
.lisp
71
35.859155
78
0.668246
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0ed009bb90b0f373fcb44e2ce379d4bf4345f29fe7804cf1082e30b10b5c03de
510
[ 77061 ]
511
lists.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/lists.lisp
(in-package :alexandria) (declaim (inline safe-endp)) (defun safe-endp (x) (declare (optimize safety)) (endp x)) (defun alist-plist (alist) "Returns a property list containing the same keys and values as the association list ALIST in the same order." (let (plist) (dolist (pair alist) (push (car pair) plist) (push (cdr pair) plist)) (nreverse plist))) (defun plist-alist (plist) "Returns an association list containing the same keys and values as the property list PLIST in the same order." (let (alist) (do ((tail plist (cddr tail))) ((safe-endp tail) (nreverse alist)) (push (cons (car tail) (cadr tail)) alist)))) (declaim (inline racons)) (defun racons (key value ralist) (acons value key ralist)) (macrolet ((define-alist-get (name get-entry get-value-from-entry add doc) `(progn (declaim (inline ,name)) (defun ,name (alist key &key (test 'eql)) ,doc (let ((entry (,get-entry key alist :test test))) (values (,get-value-from-entry entry) entry))) (define-setf-expander ,name (place key &key (test ''eql) &environment env) (multiple-value-bind (temporary-variables initforms newvals setter getter) (get-setf-expansion place env) (when (cdr newvals) (error "~A cannot store multiple values in one place" ',name)) (with-unique-names (new-value key-val test-val alist entry) (values (append temporary-variables (list alist key-val test-val entry)) (append initforms (list getter key test `(,',get-entry ,key-val ,alist :test ,test-val))) `(,new-value) `(cond (,entry (setf (,',get-value-from-entry ,entry) ,new-value)) (t (let ,newvals (setf ,(first newvals) (,',add ,key ,new-value ,alist)) ,setter ,new-value))) `(,',get-value-from-entry ,entry)))))))) (define-alist-get assoc-value assoc cdr acons "ASSOC-VALUE is an alist accessor very much like ASSOC, but it can be used with SETF.") (define-alist-get rassoc-value rassoc car racons "RASSOC-VALUE is an alist accessor very much like RASSOC, but it can be used with SETF.")) (defun malformed-plist (plist) (error "Malformed plist: ~S" plist)) (defmacro doplist ((key val plist &optional values) &body body) "Iterates over elements of PLIST. BODY can be preceded by declarations, and is like a TAGBODY. RETURN may be used to terminate the iteration early. If RETURN is not used, returns VALUES." (multiple-value-bind (forms declarations) (parse-body body) (with-gensyms (tail loop results) `(block nil (flet ((,results () (let (,key ,val) (declare (ignorable ,key ,val)) (return ,values)))) (let* ((,tail ,plist) (,key (if ,tail (pop ,tail) (,results))) (,val (if ,tail (pop ,tail) (malformed-plist ',plist)))) (declare (ignorable ,key ,val)) ,@declarations (tagbody ,loop ,@forms (setf ,key (if ,tail (pop ,tail) (,results)) ,val (if ,tail (pop ,tail) (malformed-plist ',plist))) (go ,loop)))))))) (define-modify-macro appendf (&rest lists) append "Modify-macro for APPEND. Appends LISTS to the place designated by the first argument.") (define-modify-macro nconcf (&rest lists) nconc "Modify-macro for NCONC. Concatenates LISTS to place designated by the first argument.") (define-modify-macro unionf (list &rest args) union "Modify-macro for UNION. Saves the union of LIST and the contents of the place designated by the first argument to the designated place.") (define-modify-macro nunionf (list &rest args) nunion "Modify-macro for NUNION. Saves the union of LIST and the contents of the place designated by the first argument to the designated place. May modify either argument.") (define-modify-macro reversef () reverse "Modify-macro for REVERSE. Copies and reverses the list stored in the given place and saves back the result into the place.") (define-modify-macro nreversef () nreverse "Modify-macro for NREVERSE. Reverses the list stored in the given place by destructively modifying it and saves back the result into the place.") (defun circular-list (&rest elements) "Creates a circular list of ELEMENTS." (let ((cycle (copy-list elements))) (nconc cycle cycle))) (defun circular-list-p (object) "Returns true if OBJECT is a circular list, NIL otherwise." (and (listp object) (do ((fast object (cddr fast)) (slow (cons (car object) (cdr object)) (cdr slow))) (nil) (unless (and (consp fast) (listp (cdr fast))) (return nil)) (when (eq fast slow) (return t))))) (defun circular-tree-p (object) "Returns true if OBJECT is a circular tree, NIL otherwise." (labels ((circularp (object seen) (and (consp object) (do ((fast (cons (car object) (cdr object)) (cddr fast)) (slow object (cdr slow))) (nil) (when (or (eq fast slow) (member slow seen)) (return-from circular-tree-p t)) (when (or (not (consp fast)) (not (consp (cdr slow)))) (return (do ((tail object (cdr tail))) ((not (consp tail)) nil) (let ((elt (car tail))) (circularp elt (cons object seen)))))))))) (circularp object nil))) (defun proper-list-p (object) "Returns true if OBJECT is a proper list." (cond ((not object) t) ((consp object) (do ((fast object (cddr fast)) (slow (cons (car object) (cdr object)) (cdr slow))) (nil) (unless (and (listp fast) (consp (cdr fast))) (return (and (listp fast) (not (cdr fast))))) (when (eq fast slow) (return nil)))) (t nil))) (deftype proper-list () "Type designator for proper lists. Implemented as a SATISFIES type, hence not recommended for performance intensive use. Main usefullness as a type designator of the expected type in a TYPE-ERROR." `(and list (satisfies proper-list-p))) (defun circular-list-error (list) (error 'type-error :datum list :expected-type '(and list (not circular-list)))) (macrolet ((def (name lambda-list doc step declare ret1 ret2) (assert (member 'list lambda-list)) `(defun ,name ,lambda-list ,doc (do ((last list fast) (fast list (cddr fast)) (slow (cons (car list) (cdr list)) (cdr slow)) ,@(when step (list step))) (nil) (declare (dynamic-extent slow) ,@(when declare (list declare)) (ignorable last)) (when (safe-endp fast) (return ,ret1)) (when (safe-endp (cdr fast)) (return ,ret2)) (when (eq fast slow) (circular-list-error list)))))) (def proper-list-length (list) "Returns length of LIST, signalling an error if it is not a proper list." (n 1 (+ n 2)) ;; KLUDGE: Most implementations don't actually support lists with bignum ;; elements -- and this is WAY faster on most implementations then declaring ;; N to be an UNSIGNED-BYTE. (fixnum n) (1- n) n) (def lastcar (list) "Returns the last element of LIST. Signals a type-error if LIST is not a proper list." nil nil (cadr last) (car fast)) (def (setf lastcar) (object list) "Sets the last element of LIST. Signals a type-error if LIST is not a proper list." nil nil (setf (cadr last) object) (setf (car fast) object))) (defun make-circular-list (length &key initial-element) "Creates a circular list of LENGTH with the given INITIAL-ELEMENT." (let ((cycle (make-list length :initial-element initial-element))) (nconc cycle cycle))) (deftype circular-list () "Type designator for circular lists. Implemented as a SATISFIES type, so not recommended for performance intensive use. Main usefullness as the expected-type designator of a TYPE-ERROR." `(satisfies circular-list-p)) (defun ensure-car (thing) "If THING is a CONS, its CAR is returned. Otherwise THING is returned." (if (consp thing) (car thing) thing)) (defun ensure-cons (cons) "If CONS is a cons, it is returned. Otherwise returns a fresh cons with CONS in the car, and NIL in the cdr." (if (consp cons) cons (cons cons nil))) (defun ensure-list (list) "If LIST is a list, it is returned. Otherwise returns the list designated by LIST." (if (listp list) list (list list))) (defun remove-from-plist (plist &rest keys) "Returns a propery-list with same keys and values as PLIST, except that keys in the list designated by KEYS and values corresponding to them are removed. The returned property-list may share structure with the PLIST, but PLIST is not destructively modified. Keys are compared using EQ." (declare (optimize (speed 3))) ;; FIXME: possible optimization: (remove-from-plist '(:x 0 :a 1 :b 2) :a) ;; could return the tail without consing up a new list. (loop for (key . rest) on plist by #'cddr do (assert rest () "Expected a proper plist, got ~S" plist) unless (member key keys :test #'eq) collect key and collect (first rest))) (defun delete-from-plist (plist &rest keys) "Just like REMOVE-FROM-PLIST, but this version may destructively modify the provided plist." ;; FIXME: should not cons (apply 'remove-from-plist plist keys)) (define-modify-macro remove-from-plistf (&rest keys) remove-from-plist "Modify macro for REMOVE-FROM-PLIST.") (define-modify-macro delete-from-plistf (&rest keys) delete-from-plist "Modify macro for DELETE-FROM-PLIST.") (declaim (inline sans)) (defun sans (plist &rest keys) "Alias of REMOVE-FROM-PLIST for backward compatibility." (apply #'remove-from-plist plist keys)) (defun mappend (function &rest lists) "Applies FUNCTION to respective element(s) of each LIST, appending all the all the result list to a single list. FUNCTION must return a list." (loop for results in (apply #'mapcar function lists) append results)) (defun setp (object &key (test #'eql) (key #'identity)) "Returns true if OBJECT is a list that denotes a set, NIL otherwise. A list denotes a set if each element of the list is unique under KEY and TEST." (and (listp object) (let (seen) (dolist (elt object t) (let ((key (funcall key elt))) (if (member key seen :test test) (return nil) (push key seen))))))) (defun set-equal (list1 list2 &key (test #'eql) (key nil keyp)) "Returns true if every element of LIST1 matches some element of LIST2 and every element of LIST2 matches some element of LIST1. Otherwise returns false." (let ((keylist1 (if keyp (mapcar key list1) list1)) (keylist2 (if keyp (mapcar key list2) list2))) (and (dolist (elt keylist1 t) (or (member elt keylist2 :test test) (return nil))) (dolist (elt keylist2 t) (or (member elt keylist1 :test test) (return nil)))))) (defun map-product (function list &rest more-lists) "Returns a list containing the results of calling FUNCTION with one argument from LIST, and one from each of MORE-LISTS for each combination of arguments. In other words, returns the product of LIST and MORE-LISTS using FUNCTION. Example: (map-product 'list '(1 2) '(3 4) '(5 6)) => ((1 3 5) (1 3 6) (1 4 5) (1 4 6) (2 3 5) (2 3 6) (2 4 5) (2 4 6)) " (labels ((%map-product (f lists) (let ((more (cdr lists)) (one (car lists))) (if (not more) (mapcar f one) (mappend (lambda (x) (%map-product (curry f x) more)) one))))) (%map-product (ensure-function function) (cons list more-lists)))) (defun flatten (tree) "Traverses the tree in order, collecting non-null leaves into a list." (let (list) (labels ((traverse (subtree) (when subtree (if (consp subtree) (progn (traverse (car subtree)) (traverse (cdr subtree))) (push subtree list))))) (traverse tree)) (nreverse list)))
13,555
Common Lisp
.lisp
317
32.921136
85
0.588788
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0ecde6b4de98205ed8aef39c72bbacb4ede1c98463c4691440cbf4ab4ddf111a
511
[ -1 ]
512
arrays.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/arrays.lisp
(in-package :alexandria) (defun copy-array (array &key (element-type (array-element-type array)) (fill-pointer (and (array-has-fill-pointer-p array) (fill-pointer array))) (adjustable (adjustable-array-p array))) "Returns an undisplaced copy of ARRAY, with same fill-pointer and adjustability (if any) as the original, unless overridden by the keyword arguments." (let* ((dimensions (array-dimensions array)) (new-array (make-array dimensions :element-type element-type :adjustable adjustable :fill-pointer fill-pointer))) (dotimes (i (array-total-size array)) (setf (row-major-aref new-array i) (row-major-aref array i))) new-array))
871
Common Lisp
.lisp
17
36.352941
81
0.565064
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
dc6437be907d331b0c88982212aa6be57f615f022094fa4722eb48ae9c52389a
512
[ 156047 ]
513
definitions.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/definitions.lisp
(in-package :alexandria) (defun %reevaluate-constant (name value test) (if (not (boundp name)) value (let ((old (symbol-value name)) (new value)) (if (not (constantp name)) (prog1 new (cerror "Try to redefine the variable as a constant." "~@<~S is an already bound non-constant variable ~ whose value is ~S.~:@>" name old)) (if (funcall test old new) old (restart-case (error "~@<~S is an already defined constant whose value ~ ~S is not equal to the provided initial value ~S ~ under ~S.~:@>" name old new test) (ignore () :report "Retain the current value." old) (continue () :report "Try to redefine the constant." new))))))) (defmacro define-constant (name initial-value &key (test ''eql) documentation) "Ensures that the global variable named by NAME is a constant with a value that is equal under TEST to the result of evaluating INITIAL-VALUE. TEST is a /function designator/ that defaults to EQL. If DOCUMENTATION is given, it becomes the documentation string of the constant. Signals an error if NAME is already a bound non-constant variable. Signals an error if NAME is already a constant variable whose value is not equal under TEST to result of evaluating INITIAL-VALUE." `(defconstant ,name (%reevaluate-constant ',name ,initial-value ,test) ,@(when documentation `(,documentation))))
1,656
Common Lisp
.lisp
33
38.333333
80
0.595429
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
415a44564fadc94f56e657b9e9722d90e762f048286fd9c959859ef07b87f16b
513
[ 40227 ]
514
macros.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/alexandria/macros.lisp
(in-package :alexandria) (defmacro with-gensyms (names &body forms) "Binds each variable named by a symbol in NAMES to a unique symbol around FORMS. Each of NAMES must either be either a symbol, or of the form: (symbol string-designator) Bare symbols appearing in NAMES are equivalent to: (symbol symbol) The string-designator is used as the argument to GENSYM when constructing the unique symbol the named variable will be bound to." `(let ,(mapcar (lambda (name) (multiple-value-bind (symbol string) (etypecase name (symbol (values name (symbol-name name))) ((cons symbol (cons string-designator null)) (values (first name) (string (second name))))) `(,symbol (gensym ,string)))) names) ,@forms)) (defmacro with-unique-names (names &body forms) "Alias for WITH-GENSYMS." `(with-gensyms ,names ,@forms)) (defmacro once-only (specs &body forms) "Evaluates FORMS with symbols specified in SPECS rebound to temporary variables, ensuring that each initform is evaluated only once. Each of SPECS must either be a symbol naming the variable to be rebound, or of the form: (symbol initform) Bare symbols in SPECS are equivalent to (symbol symbol) Example: (defmacro cons1 (x) (once-only (x) `(cons ,x ,x))) (let ((y 0)) (cons1 (incf y))) => (1 . 1) " (let ((gensyms (make-gensym-list (length specs) "ONCE-ONLY")) (names-and-forms (mapcar (lambda (spec) (etypecase spec (list (destructuring-bind (name form) spec (cons name form))) (symbol (cons spec spec)))) specs))) ;; bind in user-macro `(let ,(mapcar (lambda (g n) (list g `(gensym ,(string (car n))))) gensyms names-and-forms) ;; bind in final expansion `(let (,,@(mapcar (lambda (g n) ``(,,g ,,(cdr n))) gensyms names-and-forms)) ;; bind in user-macro ,(let ,(mapcar (lambda (n g) (list (car n) g)) names-and-forms gensyms) ,@forms))))) (defun parse-body (body &key documentation whole) "Parses BODY into (values remaining-forms declarations doc-string). Documentation strings are recognized only if DOCUMENTATION is true. Syntax errors in body are signalled and WHOLE is used in the signal arguments when given." (let ((doc nil) (decls nil) (current nil)) (tagbody :declarations (setf current (car body)) (when (and documentation (stringp current) (cdr body)) (if doc (error "Too many documentation strings in ~S." (or whole body)) (setf doc (pop body))) (go :declarations)) (when (and (listp current) (eql (first current) 'declare)) (push (pop body) decls) (go :declarations))) (values body (nreverse decls) doc))) (defun parse-ordinary-lambda-list (lambda-list &key (normalize t) allow-specializers (normalize-optional normalize) (normalize-keyword normalize) (normalize-auxilary normalize)) "Parses an ordinary lambda-list, returning as multiple values: 1. Required parameters. 2. Optional parameter specifications, normalized into form: (name init suppliedp) 3. Name of the rest parameter, or NIL. 4. Keyword parameter specifications, normalized into form: ((keyword-name name) init suppliedp) 5. Boolean indicating &ALLOW-OTHER-KEYS presence. 6. &AUX parameter specifications, normalized into form (name init). 7. Existence of &KEY in the lambda-list. Signals a PROGRAM-ERROR is the lambda-list is malformed." (let ((state :required) (allow-other-keys nil) (auxp nil) (required nil) (optional nil) (rest nil) (keys nil) (keyp nil) (aux nil)) (labels ((fail (elt) (simple-program-error "Misplaced ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (check-variable (elt what &optional (allow-specializers allow-specializers)) (unless (and (or (symbolp elt) (and allow-specializers (consp elt) (= 2 (length elt)) (symbolp (first elt)))) (not (constantp elt))) (simple-program-error "Invalid ~A ~S in ordinary lambda-list:~% ~S" what elt lambda-list))) (check-spec (spec what) (destructuring-bind (init suppliedp) spec (declare (ignore init)) (check-variable suppliedp what nil)))) (dolist (elt lambda-list) (case elt (&optional (if (eq state :required) (setf state elt) (fail elt))) (&rest (if (member state '(:required &optional)) (setf state elt) (fail elt))) (&key (if (member state '(:required &optional :after-rest)) (setf state elt) (fail elt)) (setf keyp t)) (&allow-other-keys (if (eq state '&key) (setf allow-other-keys t state elt) (fail elt))) (&aux (cond ((eq state '&rest) (fail elt)) (auxp (simple-program-error "Multiple ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (t (setf auxp t state elt)) )) (otherwise (when (member elt '#.(set-difference lambda-list-keywords '(&optional &rest &key &allow-other-keys &aux))) (simple-program-error "Bad lambda-list keyword ~S in ordinary lambda-list:~% ~S" elt lambda-list)) (case state (:required (check-variable elt "required parameter") (push elt required)) (&optional (cond ((consp elt) (destructuring-bind (name &rest tail) elt (check-variable name "optional parameter") (cond ((cdr tail) (check-spec tail "optional-supplied-p parameter")) (normalize-optional (setf elt (append elt '(nil))))))) (t (check-variable elt "optional parameter") (when normalize-optional (setf elt (cons elt '(nil nil)))))) (push (ensure-list elt) optional)) (&rest (check-variable elt "rest parameter") (setf rest elt state :after-rest)) (&key (cond ((consp elt) (destructuring-bind (var-or-kv &rest tail) elt (cond ((consp var-or-kv) (destructuring-bind (keyword var) var-or-kv (unless (symbolp keyword) (simple-program-error "Invalid keyword name ~S in ordinary ~ lambda-list:~% ~S" keyword lambda-list)) (check-variable var "keyword parameter"))) (t (check-variable var-or-kv "keyword parameter") (when normalize-keyword (setf var-or-kv (list (make-keyword var-or-kv) var-or-kv))))) (if (cdr tail) (check-spec tail "keyword-supplied-p parameter") (when normalize-keyword (setf tail (append tail '(nil))))) (setf elt (cons var-or-kv tail)))) (t (check-variable elt "keyword parameter") (setf elt (if normalize-keyword (list (list (make-keyword elt) elt) nil nil) elt)))) (push elt keys)) (&aux (if (consp elt) (destructuring-bind (var &optional init) elt (declare (ignore init)) (check-variable var "&aux parameter")) (progn (check-variable elt "&aux parameter") (setf elt (list* elt (when normalize-auxilary '(nil)))))) (push elt aux)) (t (simple-program-error "Invalid ordinary lambda-list:~% ~S" lambda-list))))))) (values (nreverse required) (nreverse optional) rest (nreverse keys) allow-other-keys (nreverse aux) keyp))) ;;;; DESTRUCTURING-*CASE (defun expand-destructuring-case (key clauses case) (once-only (key) `(if (typep ,key 'cons) (,case (car ,key) ,@(mapcar (lambda (clause) (destructuring-bind ((keys . lambda-list) &body body) clause `(,keys (destructuring-bind ,lambda-list (cdr ,key) ,@body)))) clauses)) (error "Invalid key to DESTRUCTURING-~S: ~S" ',case ,key)))) (defmacro destructuring-case (keyform &body clauses) "DESTRUCTURING-CASE, -CCASE, and -ECASE are a combination of CASE and DESTRUCTURING-BIND. KEYFORM must evaluate to a CONS. Clauses are of the form: ((CASE-KEYS . DESTRUCTURING-LAMBDA-LIST) FORM*) The clause whose CASE-KEYS matches CAR of KEY, as if by CASE, CCASE, or ECASE, is selected, and FORMs are then executed with CDR of KEY is destructured and bound by the DESTRUCTURING-LAMBDA-LIST. Example: (defun dcase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar, ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)) ((t &rest rest) (format nil \"unknown: ~S\" rest)))) (dcase (list :foo 1 2)) ; => \"foo: 1, 2\" (dcase (list :bar :a 1 :b 2)) ; => \"bar: 1, 2\" (dcase (list :alt1 1)) ; => \"alt: 1\" (dcase (list :alt2 2)) ; => \"alt: 2\" (dcase (list :quux 1 2 3)) ; => \"unknown: 1, 2, 3\" (defun decase (x) (destructuring-case x ((:foo a b) (format nil \"foo: ~S, ~S\" a b)) ((:bar &key a b) (format nil \"bar, ~S, ~S\" a b)) (((:alt1 :alt2) a) (format nil \"alt: ~S\" a)))) (decase (list :foo 1 2)) ; => \"foo: 1, 2\" (decase (list :bar :a 1 :b 2)) ; => \"bar: 1, 2\" (decase (list :alt1 1)) ; => \"alt: 1\" (decase (list :alt2 2)) ; => \"alt: 2\" (decase (list :quux 1 2 3)) ; =| error " (expand-destructuring-case keyform clauses 'case)) (defmacro destructuring-ccase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ccase)) (defmacro destructuring-ecase (keyform &body clauses) (expand-destructuring-case keyform clauses 'ecase)) (dolist (name '(destructuring-ccase destructuring-ecase)) (setf (documentation name 'function) (documentation 'destructuring-case 'function)))
11,941
Common Lisp
.lisp
267
30.71161
96
0.51036
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b5069db123aa2ed52b9e5b3a775f47987394225bfd5f1129b55eee6bdfcca08a
514
[ 94243 ]
515
package.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/grovel/package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- Groveler DEFPACKAGE. ;;; ;;; 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. ;;; (defpackage #:cffi-grovel (:use #:common-lisp #:alexandria) (:import-from #:cffi-sys #:native-namestring) (:export ;; Class name #:grovel-file #:process-grovel-file ;; Error condition #:missing-definition) (:export ;; Class name #:wrapper-file #:process-wrapper-file))
1,501
Common Lisp
.lisp
37
38.675676
70
0.733424
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
78d18b8a8635ef7f9081f1c002bc5ed9ef383c1ac124a5494526dd2b7397985a
515
[ -1 ]
516
asdf.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/grovel/asdf.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; asdf.lisp --- ASDF components for cffi-grovel. ;;; ;;; Copyright (C) 2005-2006, Dan Knap <[email protected]> ;;; Copyright (C) 2005-2006, Emily Backes <[email protected]> ;;; Copyright (C) 2007, Stelian Ionescu <[email protected]> ;;; Copyright (C) 2007, 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-grovel) (defun ensure-pathname (thing) (if (typep thing 'logical-pathname) (translate-logical-pathname thing) (pathname thing))) (defclass cc-flags-mixin () ((cc-flags :initform nil :accessor cc-flags-of :initarg :cc-flags))) (defmethod asdf:perform :around ((op asdf:compile-op) (file cc-flags-mixin)) (declare (ignore op)) (let ((*cc-flags* (append (ensure-list (cc-flags-of file)) *cc-flags*))) (call-next-method))) (eval-when (:compile-toplevel :load-toplevel :execute) (defclass process-op (asdf:operation) () (:documentation "This ASDF operation performs the steps necessary to generate a compilable and loadable lisp file from a PROCESS-OP-INPUT component.")) (defclass process-op-input (asdf:cl-source-file) ((generated-lisp-file-type :initarg :generated-lisp-file-type :accessor generated-lisp-file-type :documentation "The :TYPE argument to use for the generated lisp file.")) (:default-initargs :generated-lisp-file-type "generated-lisp-file") (:documentation "This ASDF component represents a file that is used as input to a function that generates lisp source file. This component acts as if it is a CL-SOURCE-FILE by applying the COMPILE-OP and LOAD-SOURCE-OP operations to the file generated by PROCESS-OP."))) (defmethod asdf:input-files ((op process-op) (c process-op-input)) (list (asdf:component-pathname c))) (defmethod asdf:component-depends-on ((op process-op) (c process-op-input)) `(#-asdf3 (asdf:load-op ,@(asdf::component-load-dependencies c)) #+asdf3 (asdf:prepare-op ,c) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:compile-op) (c process-op-input)) (declare (ignore op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:component-depends-on ((op asdf:load-source-op) (c process-op-input)) (declare (ignore op)) `((process-op ,(asdf:component-name c)) ,@(call-next-method))) (defmethod asdf:perform ((op asdf:compile-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) (defmethod asdf:perform ((op asdf:load-source-op) (c process-op-input)) (let ((generated-lisp-file (first (asdf:output-files (make-instance 'process-op) c)))) (asdf:perform op (make-instance 'asdf:cl-source-file :name (asdf:component-name c) :parent (asdf:component-parent c) :pathname generated-lisp-file)))) ;;;# ASDF component: GROVEL-FILE (eval-when (:compile-toplevel :load-toplevel :execute) (defclass grovel-file (process-op-input cc-flags-mixin) () (:default-initargs :generated-lisp-file-type "processed-grovel-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-GROVEL-FILE."))) (defmethod asdf:output-files ((op process-op) (c grovel-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file))) (list output-file c-file (exe-filename c-file)))) (defmethod asdf:perform ((op process-op) (c grovel-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-grovel-file input-file output-file))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;;;# ASDF component: WRAPPER-FILE (eval-when (:compile-toplevel :load-toplevel :execute) (defclass wrapper-file (process-op-input cc-flags-mixin) ((soname :initform nil :initarg :soname :accessor soname-of)) (:default-initargs :generated-lisp-file-type "processed-wrapper-file") (:documentation "This ASDF component represents an input file that is processed by PROCESS-WRAPPER-FILE. This generates a foreign library and matching CFFI bindings that are subsequently compiled and loaded."))) (defun wrapper-soname (c) (or (soname-of c) (asdf:component-name c))) (defmethod asdf:output-files ((op process-op) (c wrapper-file)) (let* ((input-file (asdf:component-pathname c)) (output-file (make-pathname :type (generated-lisp-file-type c) :defaults input-file)) (c-file (make-c-file-name output-file)) (lib-soname (wrapper-soname c))) (list output-file c-file (lib-filename (make-soname lib-soname output-file))))) (defmethod asdf:perform ((op process-op) (c wrapper-file)) (let ((output-file (first (asdf:output-files op c))) (input-file (asdf:component-pathname c))) (ensure-directories-exist (directory-namestring output-file)) (let ((tmp-file (process-wrapper-file input-file output-file (wrapper-soname c)))) (unwind-protect (alexandria:copy-file tmp-file output-file :if-to-exists :supersede) (delete-file tmp-file))))) ;; Allow for naked :grovel-file and :wrapper-file in asdf definitions. (eval-when (:compile-toplevel :load-toplevel :execute) (setf (find-class 'asdf::cffi-grovel-file) (find-class 'grovel-file)) (setf (find-class 'asdf::cffi-wrapper-file) (find-class 'wrapper-file)))
7,284
Common Lisp
.lisp
145
44.144828
88
0.681467
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
ac5c3acac90282c066245d08e5a4b6ece2ad534bd11bf176903cd8099583bbdf
516
[ -1 ]
517
gethostname.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/gethostname.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; gethostname.lisp --- A simple CFFI example. ;;; ;;; 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. ;;; ;;;# CFFI Example: gethostname binding ;;; ;;; This is a very simple CFFI example that illustrates calling a C ;;; function that fills in a user-supplied string buffer. (defpackage #:cffi-example-gethostname (:use #:common-lisp #:cffi) (:export #:gethostname)) (in-package #:cffi-example-gethostname) ;;; Define the Lisp function %GETHOSTNAME to call the C 'gethostname' ;;; function, which will fill BUF with up to BUFSIZE characters of the ;;; system's hostname. (defcfun ("gethostname" %gethostname) :int (buf :pointer) (bufsize :int)) ;;; Define a Lispy interface to 'gethostname'. The utility macro ;;; WITH-FOREIGN-POINTER-AS-STRING is used to allocate a temporary ;;; buffer and return it as a Lisp string. (defun gethostname () (with-foreign-pointer-as-string ((buf bufsize) 255) (%gethostname buf bufsize)))
2,112
Common Lisp
.lisp
46
44.5
70
0.744299
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6aab6c4c1b718a73f904b665b5288c548b773ba84a81201d1f9436d1d0a48a52
517
[ 99097, 189778 ]
518
translator-test.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/translator-test.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; translator-test.lisp --- Testing type translators. ;;; ;;; 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. ;;; (defpackage #:cffi-translator-test (:use #:common-lisp #:cffi)) (in-package #:cffi-translator-test) ;;;# Verbose Pointer Translator ;;; ;;; This is a silly type translator that doesn't actually do any ;;; translating, but it prints out a debug message when the pointer is ;;; converted to/from its foreign representation. (define-foreign-type verbose-pointer-type () () (:actual-type :pointer)) (defmethod translate-to-foreign (value (type verbose-pointer-type)) (format *debug-io* "~&;; to foreign: VERBOSE-POINTER: ~S~%" value) value) (defmethod translate-from-foreign (value (type verbose-pointer-type)) (format *debug-io* "~&;; from foreign: VERBOSE-POINTER: ~S~%" value) value) ;;;# Verbose String Translator ;;; ;;; A VERBOSE-STRING extends VERBOSE-POINTER and converts Lisp strings ;;; C strings. If things are working properly, both type translators ;;; should be called when converting a Lisp string to/from a C string. ;;; ;;; The translators should be called most-specific-first when ;;; translating to C, and most-specific-last when translating from C. (define-foreign-type verbose-string-type (verbose-pointer-type) () (:simple-parser verbose-string)) (defmethod translate-to-foreign ((s string) (type verbose-string-type)) (let ((value (foreign-string-alloc s))) (format *debug-io* "~&;; to foreign: VERBOSE-STRING: ~S -> ~S~%" s value) (values (call-next-method value type) t))) (defmethod translate-to-foreign (value (type verbose-string-type)) (if (pointerp value) (progn (format *debug-io* "~&;; to foreign: VERBOSE-STRING: ~S -> ~:*~S~%" value) (values (call-next-method) nil)) (error "Cannot convert ~S to a foreign string: it is not a Lisp ~ string or pointer." value))) (defmethod translate-from-foreign (ptr (type verbose-string-type)) (let ((value (foreign-string-to-lisp (call-next-method)))) (format *debug-io* "~&;; from foreign: VERBOSE-STRING: ~S -> ~S~%" ptr value) value)) (defmethod free-translated-object (ptr (type verbose-string-type) free-p) (when free-p (format *debug-io* "~&;; freeing VERBOSE-STRING: ~S~%" ptr) (foreign-string-free ptr))) (defun test-verbose-string () (foreign-funcall "getenv" verbose-string "SHELL" verbose-string))
3,565
Common Lisp
.lisp
75
45.106667
82
0.719586
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
96118651727ec0bc54a7a762fbc01bae50e84844e7e671b9d7e192cc4f6d388e
518
[ 196924, 397431 ]
519
gettimeofday.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/gettimeofday.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; gettimeofday.lisp --- Example CFFI binding to gettimeofday(2) ;;; ;;; 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. ;;; ;;;# CFFI Example: gettimeofday binding ;;; ;;; This example illustrates the use of foreign structures, typedefs, ;;; and using type translators to do checking of input and output ;;; arguments to a foreign function. (defpackage #:cffi-example-gettimeofday (:use #:common-lisp #:cffi) (:export #:gettimeofday)) (in-package #:cffi-example-gettimeofday) ;;; Define the TIMEVAL structure used by 'gettimeofday'. This assumes ;;; that 'time_t' is a 'long' --- it would be nice if CFFI could ;;; provide a proper :TIME-T type to help make this portable. (defcstruct timeval (tv-sec :long) (tv-usec :long)) ;;; A NULL-POINTER is a foreign :POINTER that must always be NULL. ;;; Both a NULL pointer and NIL are legal values---any others will ;;; result in a runtime error. (define-foreign-type null-pointer-type () () (:actual-type :pointer) (:simple-parser null-pointer)) ;;; This type translator is used to ensure that a NULL-POINTER has a ;;; null value. It also converts NIL to a null pointer. (defmethod translate-to-foreign (value (type null-pointer-type)) (cond ((null value) (null-pointer)) ((null-pointer-p value) value) (t (error "~A is not a null pointer." value)))) ;;; The SYSCALL-RESULT type is an integer type used for the return ;;; value of C functions that return -1 and set errno on errors. ;;; Someday when CFFI has a portable interface for dealing with ;;; 'errno', this error reporting can be more useful. (define-foreign-type syscall-result-type () () (:actual-type :int) (:simple-parser syscall-result)) ;;; Type translator to check a SYSCALL-RESULT and signal a Lisp error ;;; if the value is negative. (defmethod translate-from-foreign (value (type syscall-result-type)) (if (minusp value) (error "System call failed with return value ~D." value) value)) ;;; Define the Lisp function %GETTIMEOFDAY to call the C function ;;; 'gettimeofday', passing a pointer to the TIMEVAL structure to fill ;;; in. The TZP parameter is deprecated and should be NULL --- we can ;;; enforce this by using our NULL-POINTER type defined above. (defcfun ("gettimeofday" %gettimeofday) syscall-result (tp :pointer) (tzp null-pointer)) ;;; Define a Lispy interface to 'gettimeofday' that returns the ;;; seconds and microseconds as multiple values. (defun gettimeofday () (with-foreign-object (tv 'timeval) (%gettimeofday tv nil) (with-foreign-slots ((tv-sec tv-usec) tv timeval) (values tv-sec tv-usec))))
3,778
Common Lisp
.lisp
83
43.578313
70
0.735414
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0b4dd11e68cda2ba52fe5700c7111bc5f6398873dc4240a4ede2d35a9835c00d
519
[ 158612, 462280 ]
520
run-examples.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/run-examples.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; run-examples.lisp --- Simple script to run the examples. ;;; ;;; 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. ;;; (setf *load-verbose* nil *compile-verbose* nil) #+(and (not asdf) (or sbcl openmcl)) (require "asdf") #+clisp (load "~/Downloads/asdf") (asdf:operate 'asdf:load-op 'cffi-examples :verbose nil) (cffi-examples:run-examples) (force-output) (quit)
1,535
Common Lisp
.lisp
35
42.771429
70
0.743487
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
b939506a66805f70ee14ddb9782ca59484d4d5c58f7e28b47429b6b1f4c5b347
520
[ 246864, 410807 ]
521
mapping.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/mapping.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; mapping.lisp --- An example for mapping Lisp objects to ints. ;;; ;;; Copyright (C) 2007, 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. ;;; ;;; This is an example on how to tackle the problem of passing Lisp ;;; object identifiers to foreign code. It is not a great example, ;;; but might be useful nevertheless. ;;; ;;; Requires trivial-garbage: <http://cliki.net/trivial-garbage> (defpackage #:cffi-mapping-test (:use #:common-lisp #:cffi #:trivial-garbage) (:export #:run)) (in-package #:cffi-mapping-test) (define-foreign-type lisp-object-type () ((weakp :initarg :weakp)) (:actual-type :unsigned-int)) (define-parse-method lisp-object (&key weak-mapping) (make-instance 'lisp-object-type :weakp weak-mapping)) (defvar *regular-hashtable* (make-hash-table)) (defvar *weak-hashtable* (make-weak-hash-table :weakness :value)) (defvar *regular-counter* 0) (defvar *weak-counter* 0) (defun increment-counter (value) (mod (1+ value) (expt 2 (* 8 (foreign-type-size :unsigned-int))))) (define-modify-macro incf-counter () increment-counter) (defmethod translate-to-foreign (value (type lisp-object-type)) (with-slots (weakp) type (let ((id (if weakp (incf-counter *weak-counter*) (incf-counter *regular-counter*))) (ht (if weakp *weak-hashtable* *regular-hashtable*))) (setf (gethash id ht) value) id))) (defmethod translate-from-foreign (int (type lisp-object-type)) (with-slots (weakp) type (gethash int (if weakp *weak-hashtable* *regular-hashtable*)))) ;;;; Silly example. (defctype weak-mapping (lisp-object :weak-mapping t)) ;;; (run) => #<FUNCTION (LAMBDA (X)) {11AB46F5}> (defun run () (foreign-funcall "abs" weak-mapping (lambda (x) x) weak-mapping))
2,910
Common Lisp
.lisp
63
43.650794
70
0.717361
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
42d0bb7772e019d1f116479603c2c12d679bffa3e8726f34b743ed4cdce33133
521
[ 171204, 442167 ]
522
examples.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/examples/examples.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; examples.lisp --- Simple test examples of 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. ;;; (defpackage #:cffi-examples (:use #:cl #:cffi) (:export #:run-examples #:sqrtf #:getenv)) (in-package #:cffi-examples) ;; A simple libc function. (defcfun "sqrtf" :float (n :float)) ;; This definition uses the STRING type translator to automatically ;; convert Lisp strings to foreign strings and vice versa. (defcfun "getenv" :string (name :string)) ;; Calling a varargs function. (defun sprintf-test () "Test calling a varargs function." (with-foreign-pointer-as-string ((buf buf-size) 255) (foreign-funcall "snprintf" :pointer buf :int buf-size :string "%d %f #x%x!" :int 666 :double (coerce pi 'double-float) :unsigned-int #xcafebabe :void))) ;; Defining an emerated type. (defcenum test-enum (:invalid 0) (:positive 1) (:negative -1)) ;; Use the absolute value function to test keyword/enum translation. (defcfun ("abs" c-abs) test-enum (n test-enum)) (defun cffi-version () (asdf:component-version (asdf:find-system 'cffi))) (defun run-examples () (format t "~&;;; CFFI version ~A on ~A ~A:~%" (cffi-version) (lisp-implementation-type) (lisp-implementation-version)) (format t "~&;; shell: ~A~%" (getenv "SHELL")) (format t "~&;; sprintf test: ~A~%" (sprintf-test)) (format t "~&;; (c-abs :positive): ~A~%" (c-abs :positive)) (format t "~&;; (c-abs :negative): ~A~%" (c-abs :negative)) (force-output))
2,705
Common Lisp
.lisp
69
36.73913
70
0.696231
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cc8b0d5331b09d156416c0e99a09292ec30bad8603081d56b459a86cbafd31e1
522
[ 4025, 454668 ]
523
cffi-corman.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/cffi-corman.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-corman.lisp --- CFFI-SYS implementation for Corman Lisp. ;;; ;;; Copyright (C) 2005-2008, 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. ;;; ;;; This port is suffering from bitrot as of 2007-03-29. Corman Lisp ;;; is too funky with ASDF, crashes easily, makes it very painful to ;;; do any testing. -- luis ;;;# Administrivia (defpackage #:cffi-sys (:use #:common-lisp #:c-types) (:import-from #:alexandria #:with-unique-names) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set ;#:make-shareable-byte-vector ;#:with-pointer-to-vector-data #:foreign-symbol-pointer #:defcfun-helper-forms #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'no-long-long *features*) (pushnew 'no-foreign-funcall *features*) ;;;$ Symbol Case (defun canonicalize-symbol-name-case (name) (declare (string name)) (string-upcase name)) ;;;# Basic Pointer Operations (deftype foreign-pointer () 'cl::foreign) (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. Alternatively, it could implemented the ;;; same way as Lispworks' foreign-funcall. In practice, nobody uses ;;; Corman with CFFI, apparently. :) (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.")) (defun native-namestring (pathname) (namestring pathname)) ; TODO: confirm ;;;# 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))))
11,583
Common Lisp
.lisp
286
36.5
78
0.659172
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
2930419d4f8c19f2fa6fe8e811e471323b61a086bc33a4e65e8630e5218a2450
523
[ 152154, 168525 ]
524
cffi-scl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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-2007, 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. ;;; ;;;# Administrivia (defpackage #:cffi-sys (:use #:common-lisp #:alien #:c-call) (:import-from #:alexandria #:once-only #:with-unique-names) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Mis-features (pushnew 'flat-namespace *features*) ;;;# 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 (deftype foreign-pointer () 'sys:system-area-pointer) (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 args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(%%foreign-funcall ,name ,types ,fargs ,rettype))) (defmacro %foreign-funcall-pointer (ptr args &key convention) "Funcall a pointer to a foreign function." (declare (ignore convention)) (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 &key convention) (declare (ignore convention)) `(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 path) "Load the foreign library 'name." (declare (ignore name)) (ext:load-dynamic-object path)) (defun %close-foreign-library (name) "Closes the foreign library 'name." (ext:close-dynamic-object name)) (defun native-namestring (pathname) (ext:unix-namestring pathname nil)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol 'name." (declare (ignore library)) (let ((sap (sys:foreign-symbol-address name))) (if (zerop (sys:sap-int sap)) nil sap)))
11,099
Common Lisp
.lisp
279
34.480287
78
0.655377
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
397d9213fa0967225aa7dca7e1f0297c013f986efd012f8da942ff398221291a
524
[ 1696, 140107 ]
525
package.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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 #:babel-encodings) (:import-from #:alexandria #:ensure-list #:featurep #:format-symbol #:hash-table-values #:if-let #:ignore-some-conditions #:lastcar #:make-gensym-list #:make-keyword #:once-only #:parse-body #:simple-style-warning #:symbolicate #:when-let #:with-unique-names) (:export ;; Types. #:foreign-pointer #:*built-in-foreign-types* ;; Primitive pointer operations. #:foreign-free #:foreign-alloc #:mem-aptr #: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-byte-vector #:with-pointer-to-vector-data ;; Foreign string operations. #:*default-foreign-encoding* #:foreign-string-alloc #:foreign-string-free #:foreign-string-to-lisp #:lisp-string-to-foreign #:with-foreign-string #:with-foreign-strings #:with-foreign-pointer-as-string ;; Foreign function operations. #:defcfun #:foreign-funcall #:foreign-funcall-pointer #:translate-camelcase-name #:translate-name-from-foreign #:translate-name-to-foreign #:translate-underscore-separated-name ;; Foreign library operations. #:*foreign-library-directories* #:*darwin-framework-directories* #:foreign-library #:foreign-library-name #:foreign-library-pathname #:foreign-library-type #:foreign-library-loaded-p #:list-foreign-libraries #:define-foreign-library #:load-foreign-library #:load-foreign-library-error #:use-foreign-library #:close-foreign-library #:reload-foreign-libraries ;; Callbacks. #:callback #:get-callback #:defcallback ;; Foreign type operations. #:defcstruct #:defcunion #:defctype #:defcenum #:defbitfield #:define-foreign-type #:define-parse-method #:define-c-struct-wrapper #:foreign-enum-keyword #:foreign-enum-keyword-list #:foreign-enum-value #:foreign-bitfield-symbol-list #:foreign-bitfield-symbols #:foreign-bitfield-value #:foreign-slot-pointer #:foreign-slot-value #:foreign-slot-type #:foreign-slot-offset #:foreign-slot-count #:foreign-slot-names #:foreign-type-alignment #:foreign-type-size #:with-foreign-object #:with-foreign-objects #:with-foreign-slots #:convert-to-foreign #:convert-from-foreign #:convert-into-foreign-memory #:free-converted-object #:translation-forms-for-class ;; Extensible foreign type operations. #:translate-to-foreign #:translate-from-foreign #:translate-into-foreign-memory #:free-translated-object #:expand-to-foreign-dyn #:expand-to-foreign #:expand-from-foreign #:expand-into-foreign-memory ;; Foreign globals. #:defcvar #:get-var-pointer #:foreign-symbol-pointer ))
4,454
Common Lisp
.lisp
148
25.290541
70
0.681723
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
422e05d5b45d56ca1ecf66f347c24a6162dd597536bd3ec4abcedd9145e93831
525
[ -1 ]
526
foreign-vars.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/foreign-vars.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; foreign-vars.lisp --- High-level interface to foreign globals. ;;; ;;; Copyright (C) 2005-2008, 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 ;;; Called by FOREIGN-OPTIONS in functions.lisp. (defun parse-defcvar-options (options) (destructuring-bind (&key (library :default) read-only) options (list :library library :read-only read-only))) (defun get-var-pointer (symbol) "Return a pointer to the foreign global variable relative to SYMBOL." (foreign-symbol-pointer (get symbol 'foreign-var-name) :library (get symbol 'foreign-var-library))) ;;; Note: this will lookup not only variables but also functions. (defun foreign-symbol-pointer (name &key (library :default)) (check-type name string) (%foreign-symbol-pointer name (if (eq library :default) :default (foreign-library-handle (get-foreign-library library))))) (defun fs-pointer-or-lose (foreign-name library) "Like foreign-symbol-ptr but throws an error instead of returning nil when foreign-name is not found." (or (foreign-symbol-pointer foreign-name :library library) (error "Trying to access undefined foreign variable ~S." foreign-name))) (defmacro defcvar (name-and-options type &optional documentation) "Define a foreign global variable." (multiple-value-bind (lisp-name foreign-name options) (parse-name-and-options name-and-options t) (let ((fn (symbolicate '#:%var-accessor- lisp-name)) (read-only (getf options :read-only)) (library (getf options :library))) ;; We can't really setf an aggregate type. (when (aggregatep (parse-type type)) (setq read-only t)) `(progn (setf (documentation ',lisp-name 'variable) ,documentation) ;; Save foreign-name and library for posterior access by ;; GET-VAR-POINTER. (setf (get ',lisp-name 'foreign-var-name) ,foreign-name) (setf (get ',lisp-name 'foreign-var-library) ',library) ;; Getter (defun ,fn () (mem-ref (fs-pointer-or-lose ,foreign-name ',library) ',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 (fs-pointer-or-lose ,foreign-name ',library) ',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)))))))
4,066
Common Lisp
.lisp
83
42.313253
78
0.664738
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
fdef5efe5b3839aab52cbf29c2256e0db764e9cb098481a38dc1eac615450e1f
526
[ 86611, 495968 ]
527
types.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/types.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; types.lisp --- User-defined CFFI types. ;;; ;;; Copyright (C) 2005-2006, James Bielman <[email protected]> ;;; Copyright (C) 2005-2007, 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) ;;;# 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-sys::no-long-long (progn (define-built-in-foreign-type :long-long) (define-built-in-foreign-type :unsigned-long-long)) ;;; Define emulated LONG-LONG types. Needs checking whether we're ;;; using the right sizes on various platforms. ;;; ;;; A possibly better, certainly faster though more intrusive, ;;; alternative is available here: ;;; <http://article.gmane.org/gmane.lisp.cffi.devel/1091> #+cffi-sys::no-long-long (eval-when (:compile-toplevel :load-toplevel :execute) (defclass emulated-llong-type (foreign-type) ()) (defmethod foreign-type-size ((tp emulated-llong-type)) 8) (defmethod foreign-type-alignment ((tp emulated-llong-type)) ;; better than assuming that the alignment is 8 (foreign-type-alignment :long)) (defmethod aggregatep ((tp emulated-llong-type)) nil) (define-foreign-type emulated-llong (emulated-llong-type) () (:simple-parser :long-long)) (define-foreign-type emulated-ullong (emulated-llong-type) () (:simple-parser :unsigned-long-long)) (defmethod canonicalize ((tp emulated-llong)) :long-long) (defmethod unparse-type ((tp emulated-llong)) :long-long) (defmethod canonicalize ((tp emulated-ullong)) :unsigned-long-long) (defmethod unparse-type ((tp emulated-ullong)) :unsigned-long-long) (defun %emulated-mem-ref-64 (ptr type offset) (let ((value #+big-endian (+ (ash (mem-ref ptr :unsigned-long offset) 32) (mem-ref ptr :unsigned-long (+ offset 4))) #+little-endian (+ (mem-ref ptr :unsigned-long offset) (ash (mem-ref ptr :unsigned-long (+ offset 4)) 32)))) (if (and (eq type :long-long) (logbitp 63 value)) (lognot (logxor value #xFFFFFFFFFFFFFFFF)) value))) (defun %emulated-mem-set-64 (value ptr type offset) (when (and (eq type :long-long) (minusp value)) (setq value (lognot (logxor value #xFFFFFFFFFFFFFFFF)))) (%mem-set (ldb (byte 32 0) value) ptr :unsigned-long #+big-endian (+ offset 4) #+little-endian offset) (%mem-set (ldb (byte 32 32) value) ptr :unsigned-long #+big-endian offset #+little-endian (+ offset 4)) value)) ;;; When some lisp other than SCL supports :long-double we should ;;; use #-cffi-sys::no-long-double here instead. #+(and scl long-float) (define-built-in-foreign-type :long-double) ;;; Lists of built-in types ;;; LMH should these be added to documentation? (export '(*other-builtin-types* *built-in-integer-types* *built-in-float-types*)) (defparameter *possible-float-types* '(:float :double :long-double)) (defparameter *other-builtin-types* '(:pointer :void) "List of types other than integer or float built in to CFFI.") (defparameter *built-in-integer-types* (set-difference cffi:*built-in-foreign-types* (append *possible-float-types* *other-builtin-types*)) "List of integer types supported by CFFI.") (defparameter *built-in-float-types* (set-difference cffi:*built-in-foreign-types* (append *built-in-integer-types* *other-builtin-types*)) "List of real float types supported by CFFI.") ;;;# 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* ((parsed-type (parse-type type)) (ctype (canonicalize parsed-type))) #+cffi-sys::no-long-long (when (member ctype '(:long-long :unsigned-long-long)) (return-from mem-ref (translate-from-foreign (%emulated-mem-ref-64 ptr ctype offset) parsed-type))) ;; normal branch (if (aggregatep parsed-type) (if (bare-struct-type-p parsed-type) (inc-pointer ptr offset) (translate-from-foreign (inc-pointer ptr offset) parsed-type)) (translate-from-foreign (%mem-ref ptr ctype offset) parsed-type)))) (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))) (ctype (canonicalize parsed-type))) ;; Bail out when using emulated long long types. #+cffi-sys::no-long-long (when (member ctype '(:long-long :unsigned-long-long)) (return-from mem-ref form)) (if (aggregatep parsed-type) (if (bare-struct-type-p parsed-type) `(inc-pointer ,ptr ,offset) (expand-from-foreign `(inc-pointer ,ptr ,offset) parsed-type)) (expand-from-foreign `(%mem-ref ,ptr ,ctype ,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)) (ctype (canonicalize ptype))) #+cffi-sys::no-long-long (when (or (eq ctype :long-long) (eq ctype :unsigned-long-long)) (return-from mem-set (%emulated-mem-set-64 (translate-to-foreign value ptype) ptr ctype offset))) (if (aggregatep ptype) ; XXX: backwards incompatible? (translate-into-foreign-memory value ptype (inc-pointer ptr offset)) (%mem-set (translate-to-foreign value ptype) ptr ctype 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))) (ctype (canonicalize parsed-type))) ;; Bail out when using emulated long long types. #+cffi-sys::no-long-long (when (member ctype '(:long-long :unsigned-long-long)) (return-from mem-set form)) (if (aggregatep parsed-type) ; XXX: skip for now. form ; use expand-into-foreign-memory when available. `(%mem-set ,(expand-to-foreign value parsed-type) ,ptr ,ctype ,offset))) form)) ;;;# Dereferencing Foreign Arrays ;;; Maybe this should be named MEM-SVREF? [2007-02-28 LO] (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))))))) (defmethod translate-into-foreign-memory (value (type foreign-pointer-type) pointer) (setf (mem-aref pointer :pointer) value)) (defmethod translate-into-foreign-memory (value (type foreign-built-in-type) pointer) (setf (mem-aref pointer (unparse-type type)) value)) (defun mem-aptr (ptr type &optional (index 0)) "The pointer to the element." (inc-pointer ptr (* index (foreign-type-size type)))) (define-compiler-macro mem-aptr (&whole form ptr type &optional (index 0)) "The pointer to the element." (cond ((not (constantp type)) form) ((not (constantp index)) `(inc-pointer ,ptr (* ,index ,(foreign-type-size (eval type))))) ((zerop (eval index)) ptr) (t `(inc-pointer ,ptr ,(* (eval index) (foreign-type-size (eval type))))))) (define-foreign-type foreign-array-type () ((dimensions :reader dimensions :initarg :dimensions) (element-type :reader element-type :initarg :element-type)) (:actual-type :pointer)) (defmethod aggregatep ((type foreign-array-type)) t) (defmethod print-object ((type foreign-array-type) stream) "Print a FOREIGN-ARRAY-TYPE instance to STREAM unreadably." (print-unreadable-object (type stream :type t :identity nil) (format stream "~S ~S" (element-type type) (dimensions type)))) (defun array-element-size (array-type) (foreign-type-size (element-type array-type))) (defmethod foreign-type-size ((type foreign-array-type)) (* (array-element-size type) (reduce #'* (dimensions type)))) (defmethod foreign-type-alignment ((type foreign-array-type)) (foreign-type-alignment (element-type type))) (define-parse-method :array (element-type &rest dimensions) (assert (plusp (length dimensions))) (make-instance 'foreign-array-type :element-type element-type :dimensions dimensions)) (defun indexes-to-row-major-index (dimensions &rest subscripts) (apply #'+ (maplist (lambda (x y) (* (car x) (apply #'* (cdr y)))) subscripts dimensions))) (defun row-major-index-to-indexes (index dimensions) (loop with idx = index with rank = (length dimensions) with indexes = (make-list rank) for dim-index from (- rank 1) downto 0 do (setf (values idx (nth dim-index indexes)) (floor idx (nth dim-index dimensions))) finally (return indexes))) (defun lisp-array-to-foreign (array pointer array-type) "Copy elements from a Lisp array to POINTER." (let* ((type (follow-typedefs (parse-type array-type))) (el-type (element-type type)) (dimensions (dimensions type))) (loop with foreign-type-size = (array-element-size type) with size = (reduce #'* dimensions) for i from 0 below size for offset = (* i foreign-type-size) for element = (apply #'aref array (row-major-index-to-indexes i dimensions)) do (setf (mem-ref pointer el-type offset) element)))) (defun foreign-array-to-lisp (pointer array-type) "Copy elements from ptr into a Lisp array. If POINTER is a null pointer, returns NIL." (unless (null-pointer-p pointer) (let* ((type (follow-typedefs (parse-type array-type))) (el-type (element-type type)) (dimensions (dimensions type)) (array (make-array dimensions))) (loop with foreign-type-size = (array-element-size type) with size = (reduce #'* dimensions) for i from 0 below size for offset = (* i foreign-type-size) for element = (mem-ref pointer el-type offset) do (setf (apply #'aref array (row-major-index-to-indexes i dimensions)) element)) array))) (defun foreign-array-alloc (array array-type) "Allocate a foreign array containing the elements of lisp array. The foreign array must be freed with foreign-array-free." (check-type array array) (let* ((type (follow-typedefs (parse-type array-type))) (ptr (foreign-alloc (element-type type) :count (reduce #'* (dimensions type))))) (lisp-array-to-foreign array ptr array-type) ptr)) (defun foreign-array-free (ptr) "Free a foreign array allocated by foreign-array-alloc." (foreign-free ptr)) (defmacro with-foreign-array ((var lisp-array array-type) &body body) "Bind var to a foreign array containing lisp-array elements in body." (with-unique-names (type) `(let ((,type (follow-typedefs (parse-type ,array-type)))) (with-foreign-pointer (,var (* (reduce #'* (dimensions ,type)) (array-element-size ,type))) (lisp-array-to-foreign ,lisp-array ,var ,array-type) ,@body)))) (defun foreign-aref (ptr array-type &rest indexes) (let* ((type (follow-typedefs (parse-type array-type))) (offset (* (array-element-size type) (apply #'indexes-to-row-major-index (dimensions type) indexes)))) (mem-ref ptr (element-type type) offset))) (defun (setf foreign-aref) (value ptr array-type &rest indexes) (let* ((type (follow-typedefs (parse-type array-type))) (offset (* (array-element-size type) (apply #'indexes-to-row-major-index (dimensions type) indexes)))) (setf (mem-ref ptr (element-type type) offset) value))) ;;; Automatic translations for the :ARRAY type. Notice that these ;;; translators will also invoke the appropriate translators for for ;;; each of the array's elements since that's the normal behaviour of ;;; the FOREIGN-ARRAY-* operators, but there's a FIXME: **it doesn't ;;; free them yet** ;;; This used to be in a separate type but let's experiment with just ;;; one type for a while. [2008-12-30 LO] ;;; FIXME: those ugly invocations of UNPARSE-TYPE suggest that these ;;; foreign array operators should take the type and dimention ;;; arguments "unboxed". [2008-12-31 LO] (defmethod translate-to-foreign (array (type foreign-array-type)) (foreign-array-alloc array (unparse-type type))) (defmethod translate-aggregate-to-foreign (ptr value (type foreign-array-type)) (lisp-array-to-foreign value ptr (unparse-type type))) (defmethod translate-from-foreign (pointer (type foreign-array-type)) (foreign-array-to-lisp pointer (unparse-type type))) (defmethod free-translated-object (pointer (type foreign-array-type) param) (declare (ignore param)) (foreign-array-free pointer)) ;;;# 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) ;; FIXME: the type should probably be parsed? (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.")) ;;; Since MEM-REF returns a pointer for struct types we are able to ;;; chain together slot names when accessing slot values in nested ;;; structures. (defmethod foreign-struct-slot-value (ptr (slot aggregate-struct-slot)) "Return a pointer to SLOT relative to PTR." (convert-from-foreign (inc-pointer ptr (slot-offset slot)) (slot-type slot))) (defmethod foreign-struct-slot-value-form (ptr (slot aggregate-struct-slot)) "Return a form to get the value of SLOT relative to PTR." `(convert-from-foreign (inc-pointer ,ptr ,(slot-offset slot)) ',(slot-type slot))) (defmethod translate-aggregate-to-foreign (ptr value (type foreign-struct-type)) ;;; FIXME: use the block memory interface instead. (loop for i below (foreign-type-size type) do (%mem-set (%mem-ref value :char i) ptr :char i))) (defmethod (setf foreign-struct-slot-value) (value ptr (slot aggregate-struct-slot)) "Set the value of an aggregate SLOT to VALUE in PTR." (translate-aggregate-to-foreign (inc-pointer ptr (slot-offset slot)) value (parse-type (slot-type slot)))) (defmethod foreign-struct-slot-set-form (value ptr (slot aggregate-struct-slot)) "Return a form to get the value of an aggregate SLOT relative to PTR." `(setf (foreign-struct-slot-value ,ptr ',(slot-name slot)) ,value)) ;;;## 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))) (defun parse-deprecated-struct-type (name struct-or-union) (check-type struct-or-union (member :struct :union)) (let* ((struct-type-name `(,struct-or-union ,name)) (struct-type (parse-type struct-type-name))) (simple-style-warning "bare references to struct types are deprecated. ~ Please use ~S or ~S instead." `(:pointer ,struct-type-name) struct-type-name) (make-instance (class-of struct-type) :alignment (alignment struct-type) :size (size struct-type) :slots (slots struct-type) :name (name struct-type) :bare t))) ;;; 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 cases from darwin/ppc32's ABI: ;;; http://developer.apple.com/documentation/DeveloperTools/Conceptual/LowLevelABI/index.html ;;; ;;; 4. "The embedding alignment of the first element in a data ;;; structure is equal to the element's natural alignment." ;;; ;;; 5. "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 darwin ppc) (foreign-type-alignment type) #+(and darwin ppc) (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 options slots) "Parse and install a foreign structure definition." (destructuring-bind (&key size (class 'foreign-struct-type)) options (let ((struct (make-instance class :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 name struct :struct)))) (defun generate-struct-accessors (name conc-name slot-names) (loop with pointer-arg = (symbolicate '#:pointer-to- name) for slot in slot-names for accessor = (symbolicate conc-name slot) collect `(defun ,accessor (,pointer-arg) (foreign-slot-value ,pointer-arg '(:struct ,name) ',slot)) collect `(defun (setf ,accessor) (value ,pointer-arg) (foreign-slot-set value ,pointer-arg '(:struct ,name) ',slot)))) (define-parse-method :struct (name) (funcall (find-type-parser name :struct))) (defvar *defcstruct-hook* nil) (defmacro defcstruct (name-and-options &body fields) "Define the layout of a foreign structure." (discard-docstring fields) (destructuring-bind (name . options) (ensure-list name-and-options) (let ((conc-name (getf options :conc-name))) (remf options :conc-name) (unless (getf options :class) (setf (getf options :class) (symbolicate name '-tclass))) `(eval-when (:compile-toplevel :load-toplevel :execute) ;; m-f-s-t could do with this with mop:ensure-class. ,(when-let (class (getf options :class)) `(defclass ,class (foreign-struct-type translatable-foreign-type) ())) (notice-foreign-struct-definition ',name ',options ',fields) ,@(when conc-name (generate-struct-accessors name conc-name (mapcar #'car fields))) ,@(when *defcstruct-hook* ;; If non-nil, *defcstruct-hook* should be a function ;; of the arguments that returns NIL or a list of ;; forms to include in the expansion. (apply *defcstruct-hook* name-and-options fields)) (define-parse-method ,name () (parse-deprecated-struct-type ',name :struct)) '(:struct ,name))))) ;;;## 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-type (type slot-name) "Return the type of SLOT in a struct TYPE." (slot-type (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-count (type slot-name) "Return the number of items in SLOT in a struct TYPE." (slot-count (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)))) ;;; We could add an option to define a struct instead of a class, in ;;; the unlikely event someone needs something like that. (defmacro define-c-struct-wrapper (class-and-type supers &optional slots) "Define a new class with CLOS slots matching those of a foreign struct type. An INITIALIZE-INSTANCE method is defined which takes a :POINTER initarg that is used to store the slots of a foreign object. This pointer is only used for initialization and it is not retained. CLASS-AND-TYPE is either a list of the form (class-name struct-type) or a single symbol naming both. The class will inherit SUPERS. If a list of SLOTS is specified, only those slots will be defined and stored." (destructuring-bind (class-name &optional (struct-type (list :struct class-name))) (ensure-list class-and-type) (let ((slots (or slots (foreign-slot-names struct-type)))) `(progn (defclass ,class-name ,supers ,(loop for slot in slots collect `(,slot :reader ,(format-symbol t "~A-~A" class-name slot)))) ;; This could be done in a parent class by using ;; FOREIGN-SLOT-NAMES when instantiating but then the compiler ;; macros wouldn't kick in. (defmethod initialize-instance :after ((inst ,class-name) &key pointer) (with-foreign-slots (,slots pointer ,struct-type) ,@(loop for slot in slots collect `(setf (slot-value inst ',slot) ,slot)))) ',class-name)))) ;;;# Foreign Unions ;;; ;;; A union is a subclass of 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) (ensure-list name-and-options) (let ((union (make-instance 'foreign-union-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 union)) slot) (when (> size max-size) (setf max-size size)) (when (> align max-align) (setf max-align align))))) (setf (size union) (or size max-size)) (setf (alignment union) max-align) (notice-foreign-type name union :union)))) (define-parse-method :union (name) (funcall (find-type-parser name :union))) (defmacro defcunion (name-and-options &body fields) "Define the layout of a foreign union." (discard-docstring fields) (destructuring-bind (name &key size) (ensure-list name-and-options) (declare (ignore size)) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-union-definition ',name-and-options ',fields) (define-parse-method ,name () (parse-deprecated-struct-type ',name :union)) '(:union ,name)))) ;;;# 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))) ;;; Simple compiler macro that kicks in when TYPE is constant and only ;;; the COUNT argument is passed. (Note: hard-coding the type's size ;;; into the fasl will likely break CLISP fasl cross-platform ;;; compatibilty.) (define-compiler-macro foreign-alloc (&whole form type &rest args &key (count 1 count-p) &allow-other-keys) (if (or (and count-p (<= (length args) 2)) (null args)) (cond ((and (constantp type) (constantp count)) `(%foreign-alloc ,(* (eval count) (foreign-type-size (eval type))))) ((constantp type) `(%foreign-alloc (* ,count ,(foreign-type-size (eval type))))) (t form)) form)) (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 &body body) (if bindings `(with-foreign-object ,(car bindings) (with-foreign-objects ,(cdr bindings) ,@body)) `(progn ,@body))) ;;;## 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 (define-foreign-type foreign-type-wrapper () ((to-c :initarg :to-c :reader wrapper-to-c) (from-c :initarg :from-c :reader wrapper-from-c)) (:documentation "Wrapper type.")) (define-parse-method :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 translate-to-foreign (value (type foreign-type-wrapper)) (translate-to-foreign (funcall (slot-value type 'to-c) value) (actual-type type))) (defmethod translate-from-foreign (value (type foreign-type-wrapper)) (funcall (slot-value type 'from-c) (translate-from-foreign value (actual-type type)))) ;;;# Other types ;;; Boolean type. Maps to an :int by default. Only accepts integer types. (define-foreign-type foreign-boolean-type () ()) (define-parse-method :boolean (&optional (base-type :int)) (make-instance 'foreign-boolean-type :actual-type (ecase (canonicalize-foreign-type base-type) ((:char :unsigned-char :int :unsigned-int :long :unsigned-long #-cffi-sys::no-long-long :long-long #-cffi-sys::no-long-long :unsigned-long-long) base-type)))) (defmethod translate-to-foreign (value (type foreign-boolean-type)) (if value 1 0)) (defmethod translate-from-foreign (value (type foreign-boolean-type)) (not (zerop value))) (defmethod expand-to-foreign (value (type foreign-boolean-type)) "Optimization for the :boolean type." (if (constantp value) (if (eval value) 1 0) `(if ,value 1 0))) (defmethod expand-from-foreign (value (type foreign-boolean-type)) "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) (defctype :ushort :unsigned-short) (defctype :uint :unsigned-int) (defctype :ulong :unsigned-long) (defctype :llong :long-long) (defctype :ullong :unsigned-long-long) ;;; 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) (macrolet ((match-types (sized-types mtypes) `(progn ,@(loop for (type . size-or-type) in sized-types for m = (car (member (if (keywordp size-or-type) (foreign-type-size size-or-type) size-or-type) mtypes :key #'foreign-type-size)) when m collect `(defctype ,type ,m))))) ;; signed (match-types ((:int8 . 1) (:int16 . 2) (:int32 . 4) (:int64 . 8) (:intptr . :pointer)) (:char :short :int :long :long-long)) ;; unsigned (match-types ((:uint8 . 1) (:uint16 . 2) (:uint32 . 4) (:uint64 . 8) (:uintptr . :pointer)) (:unsigned-char :unsigned-short :unsigned-int :unsigned-long :unsigned-long-long))))
42,477
Common Lisp
.lisp
882
41.053288
93
0.65255
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bb0e153e6afa6277947c363eb15c4a9ae3d7e39bfffc72adc6f5bbcf8aeb8094
527
[ 420737 ]
528
cffi-mcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/cffi-mcl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-mcl.lisp --- CFFI-SYS implementation for Digitool MCL. ;;; ;;; Copyright 2010 [email protected] ;;; Copyright 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. ;;; ;;; this is a stop-gap emulation. (at least) three things are not right ;;; - integer vector arguments are copied ;;; - return values are not typed ;;; - a shared library must be packaged as a framework and statically loaded ;;; ;;; on the topic of shared libraries, see ;;; http://developer.apple.com/library/mac/#documentation/DeveloperTools/Conceptual/MachOTopics/1-Articles/loading_code.html ;;; which describes how to package a shared library as a framework. ;;; once a framework exists, load it as, eg. ;;; (ccl::add-framework-bundle "fftw.framework" :pathname "ccl:frameworks;" ) ;;;# Administrivia (defpackage #:cffi-sys (:use #:common-lisp #:ccl) (:import-from #:alexandria #:once-only #:if-let) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'flat-namespace *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. (defun %foreign-alloc (size) "Allocate SIZE bytes on the heap and return a pointer." (#_newPtr size)) (defun foreign-free (ptr) "Free a PTR allocated by FOREIGN-ALLOC." ;; TODO: Should we make this a dead macptr? (#_disposePtr 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)) (ccl:%stack-block ((,var ,size-var)) ,@body))) ;;;# Misc. Pointer Operations (deftype foreign-pointer () 'ccl:macptr) (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))) ;;; from openmcl::macros.lisp (defmacro with-pointer-to-vector-data ((ptr ivector) &body body) "Bind PTR-VAR to a foreign pointer to the data in VECTOR." (let* ((v (gensym)) (l (gensym))) `(let* ((,v ,ivector) (,l (length ,v))) (unless (typep ,v 'ccl::ivector) (ccl::report-bad-arg ,v 'ccl::ivector)) ;;;!!! this, unless it's possible to suppress gc (let ((,ptr (#_newPtr ,l))) (unwind-protect (progn (ccl::%copy-ivector-to-ptr ,v 0 ,ptr 0 ,l) (mutliple-value-prog1 (locally ,@body) (ccl::%copy-ptr-to-ivector ,ptr 0 ,v 0 ,l))) (#_disposePtr ,ptr)))))) ;;;# 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) (:long %get-signed-long) (:unsigned-long %get-unsigned-long) (: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)) (defun ccl::%get-unsigned-long-long (ptr offset) (let ((value 0) (bit 0)) (dotimes (i 8) (setf (ldb (byte 8 (shiftf bit (+ bit 8))) value) (ccl:%get-unsigned-byte ptr (+ offset i)))) value)) (setf (fdefinition 'ccl::%get-signed-long-long) (fdefinition 'ccl::%get-unsigned-long-long)) (defun (setf ccl::%get-unsigned-long-long) (value ptr offset) (let ((bit 0)) (dotimes (i 8) (setf (ccl:%get-unsigned-byte ptr (+ offset i)) (ldb (byte 8 (shiftf bit (+ bit 8))) value)))) ptr) (setf (fdefinition '(setf ccl::%get-signed-long-long)) (fdefinition '(setf ccl::%get-unsigned-long-long))) ;;;# Calling Foreign Functions (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to a ppc-ff-call type." (ecase type-keyword (:char :signed-byte) (:unsigned-char :unsigned-byte) (:short :signed-short) (:unsigned-short :unsigned-short) (:int :signed-fullword) (:unsigned-int :unsigned-fullword) (:long :signed-fullword) (:unsigned-long :unsigned-fullword) (:long-long :signed-doubleword) (:unsigned-long-long :unsigned-doubleword) (:float :single-float) (:double :double-float) (:pointer :address) (:void :void))) (defun ppc-ff-call-type=>mactype-name (type-keyword) (ecase type-keyword (:signed-byte :sint8) (:unsigned-byte :uint8) (:signed-short :sint16) (:unsigned-short :uint16) (:signed-halfword :sint16) (:unsigned-halfword :uint16) (:signed-fullword :sint32) (:unsigned-fullword :uint32) ;(:signed-doubleword :long-long) ;(:unsigned-doubleword :unsigned-long-long) (:single-float :single-float) (:double-float :double-float) (:address :pointer) (:void :void))) (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (case type-keyword ((:long-long :unsigned-long-long) 8) (t (ccl::mactype-record-size (ccl::find-mactype (ppc-ff-call-type=>mactype-name (convert-foreign-type type-keyword))))))) ;; 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." (case type-keyword ((:long-long :unsigned-long-long) 4) (t (ccl::mactype-record-size (ccl::find-mactype (ppc-ff-call-type=>mactype-name (convert-foreign-type type-keyword))))))) (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) "no '_' is necessary here, the internal lookup operators handle it" name) (defmacro %foreign-funcall (function-name args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) `(ccl::ppc-ff-call (ccl::macho-address ,(ccl::get-macho-entry-point (convert-external-name function-name))) ,@(convert-foreign-funcall-types args))) (defmacro %foreign-funcall-pointer (ptr args &key convention) (declare (ignore convention)) `(ccl::ppc-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" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (declare (ignore convention)) (let ((cb-name (intern-callback name))) `(progn (ccl::ppc-defpascal ,cb-name (;; ? ,@(when (eq convention :stdcall) '(:discard-stack-args)) ,@(mapcan (lambda (sym type) (list (ppc-ff-call-type=>mactype-name (convert-foreign-type type)) sym)) arg-names arg-types) ,(ppc-ff-call-type=>mactype-name (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 path) "Load the foreign library NAME." (declare (ignore path)) (setf name (string name)) ;; for mcl emulate this wrt frameworks (unless (and (> (length name) 10) (string-equal name ".framework" :start1 (- (length name) 10))) (setf name (concatenate 'string name ".framework"))) ;; if the framework was not registered, add it (unless (gethash name ccl::*framework-descriptors*) (ccl::add-framework-bundle name :pathname "ccl:frameworks;" )) (ccl::load-framework-bundle name)) (defun %close-foreign-library (name) "Close the foreign library NAME." ;; for mcl do nothing (declare (ignore name)) nil) (defun native-namestring (pathname) (ccl::posix-namestring (ccl:full-pathname pathname))) ;;;# Foreign Globals (deftrap-inline "_findsymbol" ((map :pointer) (name :pointer)) :pointer ()) (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (ccl::macho-address (ccl::get-macho-entry-point (convert-external-name name))))
13,656
Common Lisp
.lisp
337
35.750742
124
0.660709
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
81ec1da3fc7b6ae44d386b13b69e483440f9131bd0b63470771706c7bd659d4d
528
[ 142347, 263408 ]
529
cffi-clisp.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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]> ;;; Copyright (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 #:alexandria) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) (eval-when (:compile-toplevel :load-toplevel :execute) (unless (find-package :ffi) (error "CFFI requires CLISP compiled with dynamic FFI support."))) ;;;# 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 darwin ppc) (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 (deftype foreign-pointer () 'ffi:foreign-address) (defun pointerp (ptr) "Return true if PTR is a foreign pointer." (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." (zerop (ffi:foreign-address-unsigned ptr))) (defun inc-pointer (ptr offset) "Return a pointer pointing OFFSET bytes past PTR." (ffi:unsigned-foreign-address (+ offset (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 (if (zerop size) 1 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 ;;; %MEM-REF and its compiler macro work around CLISP's FFI:C-POINTER ;;; type and convert NILs back to null pointers. (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." (let ((value (ffi:memory-as ptr (convert-foreign-type type) offset))) (if (eq type :pointer) (or value (null-pointer)) value))) (define-compiler-macro %mem-ref (&whole form ptr type &optional (offset 0)) "Compiler macro to open-code when TYPE is constant." (if (constantp type) (let* ((ftype (convert-foreign-type (eval type))) (form `(ffi:memory-as ,ptr ',ftype ,offset))) (if (eq type :pointer) `(or ,form (null-pointer)) form)) 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)) ;;;# 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. (declaim (inline make-shareable-byte-vector)) (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))) (deftype shareable-byte-vector () `(vector (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." (with-unique-names (vector-var size-var) `(let ((,vector-var ,vector)) (check-type ,vector-var shareable-byte-vector) (with-foreign-pointer (,ptr-var (length ,vector-var) ,size-var) ;; copy-in (loop for i below ,size-var do (%mem-set (aref ,vector-var i) ,ptr-var :unsigned-char i)) (unwind-protect (progn ,@body) ;; copy-out (loop for i below ,size-var do (setf (aref ,vector-var i) (%mem-ref ,ptr-var :unsigned-char i)))))))) ;;;# 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))))) (defun convert-calling-convention (convention) (ecase convention (:stdcall :stdc-stdcall) (:cdecl :stdc))) (defun c-function-type (arg-types rettype convention) "Generate the apropriate CLISP foreign type specification. Also takes care of converting the calling convention names." `(ffi:c-function (:arguments ,@arg-types) (:return-type ,rettype) (:language ,(convert-calling-convention convention)))) ;;; Quick hack around the fact that the CFFI package is not yet ;;; defined when this file is loaded. I suppose we could arrange for ;;; the CFFI package to be defined a bit earlier, though. (defun library-handle-form (name) (flet ((find-cffi-symbol (symbol) (find-symbol (symbol-name symbol) '#:cffi))) `(,(find-cffi-symbol '#:foreign-library-handle) (,(find-cffi-symbol '#:get-foreign-library) ',name)))) (eval-when (:compile-toplevel :load-toplevel :execute) ;; version 2.40 (CVS 2006-09-03, to be more precise) added a ;; PROPERTIES argument to FFI::FOREIGN-LIBRARY-FUNCTION. (defun post-2.40-ffi-interface-p () (let ((f-l-f (find-symbol (string '#:foreign-library-function) '#:ffi))) (if (and f-l-f (= (length (ext:arglist f-l-f)) 5)) '(:and) '(:or)))) ;; FFI::FOREIGN-LIBRARY-FUNCTION and FFI::FOREIGN-LIBRARY-VARIABLE ;; were deprecated in 2.41 and removed in 2.45. (defun post-2.45-ffi-interface-p () (if (find-symbol (string '#:foreign-library-function) '#:ffi) '(:or) '(:and)))) #+#.(cffi-sys::post-2.45-ffi-interface-p) (defun %foreign-funcall-aux (name type library) `(ffi::find-foreign-function ,name ,type nil ,library nil nil)) #-#.(cffi-sys::post-2.45-ffi-interface-p) (defun %foreign-funcall-aux (name type library) `(ffi::foreign-library-function ,name ,library nil #+#.(cffi-sys::post-2.40-ffi-interface-p) nil ,type)) (defmacro %foreign-funcall (name args &key library convention) "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* ((fn (%foreign-funcall-aux name `(ffi:parse-c-type ',(c-function-type types rettype convention)) (if (eq library :default) :default (library-handle-form library)))) (form `(funcall (load-time-value (handler-case ,fn (error (err) (warn "~A" err)))) ,@fargs))) (if (eq rettype 'ffi:c-pointer) `(or ,form (null-pointer)) form)))) (defmacro %foreign-funcall-pointer (ptr args &key convention) "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 ',(c-function-type types rettype convention)))) ,@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 convention) (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 ,(convert-calling-convention convention)))))) ;;; 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 &key convention) `(register-callback ',name (lambda ,arg-names ;; Work around CLISP's FFI:C-POINTER type and convert NIL values ;; back into a null pointers. (let (,@(loop for name in arg-names and type in arg-types when (eq type :pointer) collect `(,name (or ,name (null-pointer))))) ,body)) ,(callback-type rettype arg-names arg-types convention))) ;;; 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 path) "Load a foreign library from PATH." (declare (ignore name)) #+#.(cffi-sys::post-2.45-ffi-interface-p) (ffi:open-foreign-library path) #-#.(cffi-sys::post-2.45-ffi-interface-p) (ffi::foreign-library path)) (defun %close-foreign-library (handle) "Close a foreign library." (ffi:close-foreign-library handle)) (defun native-namestring (pathname) (namestring pathname)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (prog1 (ignore-errors (ffi:foreign-address #+#.(cffi-sys::post-2.45-ffi-interface-p) (ffi::find-foreign-variable name nil library nil nil) #-#.(cffi-sys::post-2.45-ffi-interface-p) (ffi::foreign-library-variable name library nil nil)))))
15,949
Common Lisp
.lisp
376
37.24734
79
0.679255
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9057253cbcdaf5a7390c1b70e13068d903bb4ae215f5e488096cb6dfd872af5f
529
[ 179908, 336389 ]
530
enum.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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-typedef enhanced-foreign-type) ((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)) (ensure-list 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 is 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)) (ensure-list name-and-options) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (make-foreign-enum ',name ',base-type ',enum-list))))) (defun hash-keys-to-list (ht) (loop for k being the hash-keys in ht collect k)) (defun foreign-enum-keyword-list (enum-type) "Return a list of KEYWORDS defined in ENUM-TYPE." (hash-keys-to-list (keyword-values (parse-type enum-type)))) ;;; 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-to-foreign (value (type foreign-enum)) (if (keywordp value) (%foreign-enum-value type value :errorp t) value)) (defmethod translate-into-foreign-memory (value (type foreign-enum) pointer) (setf (mem-aref pointer (unparse-type (actual-type type))) (translate-to-foreign value type))) (defmethod translate-from-foreign (value (type foreign-enum)) (%foreign-enum-keyword type value :errorp t)) ;;;# 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-typedef enhanced-foreign-type) ((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)) (ensure-list 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)) (ensure-list name-and-options) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (make-foreign-bitfield ',name ',base-type ',masks))))) (defun foreign-bitfield-symbol-list (bitfield-type) "Return a list of SYMBOLS defined in BITFIELD-TYPE." (hash-keys-to-list (symbol-values (parse-type bitfield-type)))) (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-to-foreign (value (type foreign-bitfield)) (if (integerp value) value (%foreign-bitfield-value type (ensure-list value)))) (defmethod translate-from-foreign (value (type foreign-bitfield)) (%foreign-bitfield-symbols type value))
9,204
Common Lisp
.lisp
196
41.168367
77
0.683847
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
34d07efcc0d531e2e77d7b99900884dff0242b30a0277ed6387e0114c3e3318c
530
[ -1 ]
531
strings.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/strings.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; strings.lisp --- Operations on foreign strings. ;;; ;;; Copyright (C) 2005-2006, James Bielman <[email protected]> ;;; Copyright (C) 2005-2007, 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) ;;;# Foreign String Conversion ;;; ;;; Functions for converting NULL-terminated C-strings to Lisp strings ;;; and vice versa. The string functions accept an ENCODING keyword ;;; argument which is used to specify the encoding to use when ;;; converting to/from foreign strings. (defvar *default-foreign-encoding* :utf-8 "Default foreign encoding.") ;;; TODO: refactor, sigh. Also, this should probably be a function. (defmacro bget (ptr off &optional (bytes 1) (endianness :ne)) (let ((big-endian (member endianness '(:be #+big-endian :ne #+little-endian :re)))) (once-only (ptr off) (ecase bytes (1 `(mem-ref ,ptr :uint8 ,off)) (2 (if big-endian #+big-endian `(mem-ref ,ptr :uint16 ,off) #-big-endian `(dpb (mem-ref ,ptr :uint8 ,off) (byte 8 8) (mem-ref ,ptr :uint8 (1+ ,off))) #+little-endian `(mem-ref ,ptr :uint16 ,off) #-little-endian `(dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 8) (mem-ref ,ptr :uint8 ,off)))) (4 (if big-endian #+big-endian `(mem-ref ,ptr :uint32 ,off) #-big-endian `(dpb (mem-ref ,ptr :uint8 ,off) (byte 8 24) (dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 16) (dpb (mem-ref ,ptr :uint8 (+ ,off 2)) (byte 8 8) (mem-ref ,ptr :uint8 (+ ,off 3))))) #+little-endian `(mem-ref ,ptr :uint32 ,off) #-little-endian `(dpb (mem-ref ,ptr :uint8 (+ ,off 3)) (byte 8 24) (dpb (mem-ref ,ptr :uint8 (+ ,off 2)) (byte 8 16) (dpb (mem-ref ,ptr :uint8 (1+ ,off)) (byte 8 8) (mem-ref ,ptr :uint8 ,off)))))))))) (defmacro bset (val ptr off &optional (bytes 1) (endianness :ne)) (let ((big-endian (member endianness '(:be #+big-endian :ne #+little-endian :re)))) (ecase bytes (1 `(setf (mem-ref ,ptr :uint8 ,off) ,val)) (2 (if big-endian #+big-endian `(setf (mem-ref ,ptr :uint16 ,off) ,val) #-big-endian `(setf (mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 0) ,val) (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 8) ,val)) #+little-endian `(setf (mem-ref ,ptr :uint16 ,off) ,val) #-little-endian `(setf (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 0) ,val) (mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 8) ,val)))) (4 (if big-endian #+big-endian `(setf (mem-ref ,ptr :uint32 ,off) ,val) #-big-endian `(setf (mem-ref ,ptr :uint8 (+ 3 ,off)) (ldb (byte 8 0) ,val) (mem-ref ,ptr :uint8 (+ 2 ,off)) (ldb (byte 8 8) ,val) (mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 16) ,val) (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 24) ,val)) #+little-endian `(setf (mem-ref ,ptr :uint32 ,off) ,val) #-little-endian `(setf (mem-ref ,ptr :uint8 ,off) (ldb (byte 8 0) ,val) (mem-ref ,ptr :uint8 (1+ ,off)) (ldb (byte 8 8) ,val) (mem-ref ,ptr :uint8 (+ ,off 2)) (ldb (byte 8 16) ,val) (mem-ref ,ptr :uint8 (+ ,off 3)) (ldb (byte 8 24) ,val))))))) ;;; TODO: tackle optimization notes. (defparameter *foreign-string-mappings* (instantiate-concrete-mappings ;; :optimize ((speed 3) (debug 0) (compilation-speed 0) (safety 0)) :octet-seq-getter bget :octet-seq-setter bset :octet-seq-type foreign-pointer :code-point-seq-getter babel::string-get :code-point-seq-setter babel::string-set :code-point-seq-type babel:simple-unicode-string)) (defun null-terminator-len (encoding) (length (enc-nul-encoding (get-character-encoding encoding)))) (defun lisp-string-to-foreign (string buffer bufsize &key (start 0) end offset (encoding *default-foreign-encoding*)) (check-type string string) (when offset (setq buffer (inc-pointer buffer offset))) (with-checked-simple-vector ((string (coerce string 'babel:unicode-string)) (start start) (end end)) (declare (type simple-string string)) (let ((mapping (lookup-mapping *foreign-string-mappings* encoding)) (nul-len (null-terminator-len encoding))) (assert (plusp bufsize)) (multiple-value-bind (size end) (funcall (octet-counter mapping) string start end (- bufsize nul-len)) (funcall (encoder mapping) string start end buffer 0) (dotimes (i nul-len) (setf (mem-ref buffer :char (+ size i)) 0)))) buffer)) ;;; Expands into a loop that calculates the length of the foreign ;;; string at PTR plus OFFSET, using ACCESSOR and looking for a null ;;; terminator of LENGTH bytes. (defmacro %foreign-string-length (ptr offset type length) (once-only (ptr offset) `(do ((i 0 (+ i ,length))) ((zerop (mem-ref ,ptr ,type (+ ,offset i))) i) (declare (fixnum i))))) ;;; Return the length in octets of the null terminated foreign string ;;; at POINTER plus OFFSET octets, assumed to be encoded in ENCODING, ;;; a CFFI encoding. This should be smart enough to look for 8-bit vs ;;; 16-bit null terminators, as appropriate for the encoding. (defun foreign-string-length (pointer &key (encoding *default-foreign-encoding*) (offset 0)) (ecase (null-terminator-len encoding) (1 (%foreign-string-length pointer offset :uint8 1)) (2 (%foreign-string-length pointer offset :uint16 2)) (4 (%foreign-string-length pointer offset :uint32 4)))) (defun foreign-string-to-lisp (pointer &key (offset 0) count (max-chars (1- array-total-size-limit)) (encoding *default-foreign-encoding*)) "Copy at most COUNT bytes from POINTER plus OFFSET encoded in ENCODING into a Lisp string and return it. If POINTER is a null pointer, NIL is returned." (unless (null-pointer-p pointer) (let ((count (or count (foreign-string-length pointer :encoding encoding :offset offset))) (mapping (lookup-mapping *foreign-string-mappings* encoding))) (assert (plusp max-chars)) (multiple-value-bind (size new-end) (funcall (code-point-counter mapping) pointer offset (+ offset count) max-chars) (let ((string (make-string size :element-type 'babel:unicode-char))) (funcall (decoder mapping) pointer offset new-end string 0) (values string (- new-end offset))))))) ;;;# Using Foreign Strings (defun foreign-string-alloc (string &key (encoding *default-foreign-encoding*) (null-terminated-p t) (start 0) end) "Allocate a foreign string containing Lisp string STRING. The string must be freed with FOREIGN-STRING-FREE." (check-type string string) (with-checked-simple-vector ((string (coerce string 'babel:unicode-string)) (start start) (end end)) (declare (type simple-string string)) (let* ((mapping (lookup-mapping *foreign-string-mappings* encoding)) (count (funcall (octet-counter mapping) string start end 0)) (nul-length (if null-terminated-p (null-terminator-len encoding) 0)) (length (+ count nul-length)) (ptr (foreign-alloc :char :count length))) (funcall (encoder mapping) string start end ptr 0) (dotimes (i nul-length) (setf (mem-ref ptr :char (+ count i)) 0)) (values ptr length)))) (defun foreign-string-free (ptr) "Free a foreign string allocated by FOREIGN-STRING-ALLOC." (foreign-free ptr)) (defmacro with-foreign-string ((var-or-vars lisp-string &rest args) &body body) "VAR-OR-VARS is not evaluated ans should a list of the form \(VAR &OPTIONAL BYTE-SIZE-VAR) or just a VAR symbol. VAR is bound to a foreign string containing LISP-STRING in BODY. When BYTE-SIZE-VAR is specified then bind the C buffer size \(including the possible null terminator\(s)) to this variable." (destructuring-bind (var &optional size-var) (ensure-list var-or-vars) `(multiple-value-bind (,var ,@(when size-var (list size-var))) (foreign-string-alloc ,lisp-string ,@args) (unwind-protect (progn ,@body) (foreign-string-free ,var))))) (defmacro with-foreign-strings (bindings &body body) "See WITH-FOREIGN-STRING's documentation." (if bindings `(with-foreign-string ,(first bindings) (with-foreign-strings ,(rest bindings) ,@body)) `(progn ,@body))) (defmacro with-foreign-pointer-as-string ((var-or-vars size &rest args) &body body) "VAR-OR-VARS is not evaluated and should be a list of the form \(VAR &OPTIONAL SIZE-VAR) or just a VAR symbol. VAR is bound to a foreign buffer of size SIZE within BODY. The return value is constructed by calling FOREIGN-STRING-TO-LISP on the foreign buffer along with ARGS." ; fix wording, sigh (destructuring-bind (var &optional size-var) (ensure-list var-or-vars) `(with-foreign-pointer (,var ,size ,size-var) (progn ,@body (values (foreign-string-to-lisp ,var ,@args)))))) ;;;# Automatic Conversion of Foreign Strings (define-foreign-type foreign-string-type () (;; CFFI encoding of this string. (encoding :initform nil :initarg :encoding :reader encoding) ;; Should we free after translating from foreign? (free-from-foreign :initarg :free-from-foreign :reader fst-free-from-foreign-p :initform nil :type boolean) ;; Should we free after translating to foreign? (free-to-foreign :initarg :free-to-foreign :reader fst-free-to-foreign-p :initform t :type boolean)) (:actual-type :pointer) (:simple-parser :string)) ;;; describe me (defun fst-encoding (type) (or (encoding type) *default-foreign-encoding*)) ;;; Display the encoding when printing a FOREIGN-STRING-TYPE instance. (defmethod print-object ((type foreign-string-type) stream) (print-unreadable-object (type stream :type t) (format stream "~S" (fst-encoding type)))) (defmethod translate-to-foreign ((s string) (type foreign-string-type)) (values (foreign-string-alloc s :encoding (fst-encoding type)) (fst-free-to-foreign-p type))) (defmethod translate-to-foreign (obj (type foreign-string-type)) (cond ((pointerp obj) (values obj nil)) ;; FIXME: we used to support UB8 vectors but not anymore. ;; ((typep obj '(array (unsigned-byte 8))) ;; (values (foreign-string-alloc obj) t)) (t (error "~A is not a Lisp string or pointer." obj)))) (defmethod translate-from-foreign (ptr (type foreign-string-type)) (unwind-protect (values (foreign-string-to-lisp ptr :encoding (fst-encoding type))) (when (fst-free-from-foreign-p type) (foreign-free ptr)))) (defmethod free-translated-object (ptr (type foreign-string-type) free-p) (when free-p (foreign-string-free ptr))) ;;;# STRING+PTR (define-foreign-type foreign-string+ptr-type (foreign-string-type) () (:simple-parser :string+ptr)) (defmethod translate-from-foreign (value (type foreign-string+ptr-type)) (list (call-next-method) value))
13,000
Common Lisp
.lisp
267
40.602996
81
0.624557
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
0ccdd2db00958ca23b48b51921ea42a4e5843606fa78279a9b655c834d74ad34
531
[ -1 ]
532
utils.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/utils.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; utils.lisp --- Various utilities. ;;; ;;; Copyright (C) 2005-2008, 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) (defmacro discard-docstring (body-var &optional force) "Discards the first element of the list in body-var if it's a string and the only element (or if FORCE is T)." `(when (and (stringp (car ,body-var)) (or ,force (cdr ,body-var))) (pop ,body-var))) (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)))))) ;;; This function is here because it needs to be defined early. It's ;;; used by DEFINE-PARSE-METHOD and DEFCTYPE to warn users when ;;; they're defining types whose names belongs to the KEYWORD or CL ;;; packages. CFFI itself gets to use keywords without a warning. (defun warn-if-kw-or-belongs-to-cl (name) (let ((package (symbol-package name))) (when (and (not (eq *package* (find-package '#:cffi))) (member package '(#:common-lisp #:keyword) :key #'find-package)) (warn "Defining a foreign type named ~S. This symbol belongs to the ~A ~ package and that may interfere with other code using CFFI." name (package-name package))))) (define-condition obsolete-argument-warning (style-warning) ((old-arg :initarg :old-arg :reader old-arg) (new-arg :initarg :new-arg :reader new-arg)) (:report (lambda (c s) (format s "Keyword ~S is obsolete, please use ~S" (old-arg c) (new-arg c))))) (defun warn-obsolete-argument (old-arg new-arg) (warn 'obsolete-argument-warning :old-arg old-arg :new-arg new-arg))
3,043
Common Lisp
.lisp
61
45.918033
79
0.688508
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
27086a002706dd7dcba6b802a08dd3bb5e56afca49eade1ed7baeed8afc3ea86
532
[ -1 ]
533
cffi-sbcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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) (:import-from #:alexandria #:once-only #:with-unique-names #:when-let #:removef) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'flat-namespace *features*) ;;;# Symbol Case (declaim (inline canonicalize-symbol-name-case)) (defun canonicalize-symbol-name-case (name) (declare (string name)) (string-upcase name)) ;;;# Basic Pointer Operations (deftype foreign-pointer () 'sb-sys:system-area-pointer) (declaim (inline pointerp)) (defun pointerp (ptr) "Return true if PTR is a foreign pointer." (sb-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." (declare (type system-area-pointer ptr1 ptr2)) (sb-sys:sap= ptr1 ptr2)) (declaim (inline null-pointer)) (defun null-pointer () "Construct and return a null pointer." (sb-sys:int-sap 0)) (declaim (inline null-pointer-p)) (defun null-pointer-p (ptr) "Return true if PTR is a null pointer." (declare (type system-area-pointer ptr)) (zerop (sb-sys:sap-int ptr))) (declaim (inline inc-pointer)) (defun inc-pointer (ptr offset) "Return a pointer pointing OFFSET bytes past PTR." (declare (type system-area-pointer ptr) (type integer offset)) (sb-sys:sap+ ptr offset)) (declaim (inline make-pointer)) (defun make-pointer (address) "Return a pointer pointing to ADDRESS." ;; (declare (type (unsigned-byte 32) address)) (sb-sys:int-sap address)) (declaim (inline pointer-address)) (defun pointer-address (ptr) "Return the address pointed to by PTR." (declare (type system-area-pointer 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. (declaim (inline %foreign-alloc)) (defun %foreign-alloc (size) "Allocate SIZE bytes on the heap and return a pointer." ;; (declare (type (unsigned-byte 32) size)) (alien-sap (make-alien (unsigned 8) size))) (declaim (inline foreign-free)) (defun foreign-free (ptr) "Free a PTR allocated by FOREIGN-ALLOC." (declare (type system-area-pointer ptr) (optimize speed)) (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. (declaim (inline make-shareable-byte-vector)) (defun make-shareable-byte-vector (size) "Create a Lisp vector of SIZE bytes can passed to WITH-POINTER-TO-VECTOR-DATA." ; (declare (type sb-int:index size)) (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)) (declare (type (sb-kernel:simple-unboxed-array (*)) ,vector-var)) (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)))) ;;; Look up alien type information and build both define-mem-accessors form ;;; and convert-foreign-type function definition. (defmacro define-type-mapping (accessor-table alien-table) (let* ((accessible-types (remove 'void alien-table :key #'second)) (size-and-signedp-forms (mapcar (lambda (name) (list (eval `(alien-size ,(second name))) (typep -1 `(alien ,(second name))))) accessible-types))) `(progn (define-mem-accessors ,@(loop for (cffi-keyword alien-type fixed-accessor) in accessible-types and (alien-size signedp) in size-and-signedp-forms for (signed-ref unsigned-ref) = (cdr (assoc alien-size accessor-table)) collect `(,cffi-keyword ,(or fixed-accessor (if signedp signed-ref unsigned-ref) (error "No accessor found for ~S" alien-type))))) (defun convert-foreign-type (type-keyword) (ecase type-keyword ,@(loop for (cffi-keyword alien-type) in alien-table collect `(,cffi-keyword (quote ,alien-type)))))))) (define-type-mapping ((8 sb-sys:signed-sap-ref-8 sb-sys:sap-ref-8) (16 sb-sys:signed-sap-ref-16 sb-sys:sap-ref-16) (32 sb-sys:signed-sap-ref-32 sb-sys:sap-ref-32) (64 sb-sys:signed-sap-ref-64 sb-sys:sap-ref-64)) ((: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 sb-sys:sap-ref-single) (:double double-float sb-sys:sap-ref-double) (:pointer system-area-pointer sb-sys:sap-ref-sap) (:void void))) ;;;# Calling Foreign Functions (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 args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(%%foreign-funcall ,name ,types ,fargs ,rettype))) (defmacro %foreign-funcall-pointer (ptr args &key convention) "Funcall a pointer to a foreign function." (declare (ignore convention)) (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 &key convention) (check-type convention (member :stdcall :cdecl)) `(setf (gethash ',name *callbacks*) (alien-sap (sb-alien::alien-lambda #+alien-callback-conventions (,convention ,(convert-foreign-type rettype)) #-alien-callback-conventions ,(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 #+darwin (defun call-within-initial-thread (fn &rest args) (let (result error (sem (sb-thread:make-semaphore))) (sb-thread:interrupt-thread ;; KLUDGE: find a better way to get the initial thread. (car (last (sb-thread:list-all-threads))) (lambda () (multiple-value-setq (result error) (ignore-errors (apply fn args))) (sb-thread:signal-semaphore sem))) (sb-thread:wait-on-semaphore sem) (if error (signal error) result))) (declaim (inline %load-foreign-library)) (defun %load-foreign-library (name path) "Load a foreign library." (declare (ignore name)) ;; As of MacOS X 10.6.6, loading things like CoreFoundation from a ;; thread other than the initial one results in a crash. #+darwin (call-within-initial-thread 'load-shared-object path) #-darwin (load-shared-object path)) ;;; SBCL 1.0.21.15 renamed SB-ALIEN::SHARED-OBJECT-FILE but introduced ;;; SB-ALIEN:UNLOAD-SHARED-OBJECT which we can use instead. (eval-when (:compile-toplevel :load-toplevel :execute) (defun unload-shared-object-present-p () (multiple-value-bind (foundp kind) (find-symbol "UNLOAD-SHARED-OBJECT" "SB-ALIEN") (if (and foundp (eq kind :external)) '(:and) '(:or))))) (defun %close-foreign-library (handle) "Closes a foreign library." #+#.(cffi-sys::unload-shared-object-present-p) (sb-alien:unload-shared-object handle) #-#.(cffi-sys::unload-shared-object-present-p) (sb-thread:with-mutex (sb-alien::*shared-objects-lock*) (let ((obj (find (sb-ext:native-namestring handle) sb-alien::*shared-objects* :key #'sb-alien::shared-object-file :test #'string=))) (when obj (sb-alien::dlclose-or-lose obj) (removef sb-alien::*shared-objects* obj) #+(and linkage-table (not win32)) (sb-alien::update-linkage-table))))) (defun native-namestring (pathname) (sb-ext:native-namestring pathname)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (when-let (address (sb-sys:find-foreign-symbol-address name)) (sb-sys:int-sap address)))
14,821
Common Lisp
.lisp
362
34.850829
75
0.649414
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
da2e5c6e6f963b1c768a80dbd735ec7c309c1ec6d5f43ba47d3be4fb062c4d8f
533
[ 379839, 401545 ]
534
cffi-openmcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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) (:import-from #:alexandria #:once-only #:if-let) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'flat-namespace *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. (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 (deftype foreign-pointer () 'ccl:macptr) (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." #+darwin (concatenate 'string "_" name) #-darwin name) (defmacro %foreign-funcall (function-name args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) `(external-call ,(convert-external-name function-name) ,@(convert-foreign-funcall-types args))) (defmacro %foreign-funcall-pointer (ptr args &key convention) (declare (ignore convention)) `(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" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (let ((cb-name (intern-callback name))) `(progn (defcallback ,cb-name (,@(when (eq convention :stdcall) '(:discard-stack-args)) ,@(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 path) "Load the foreign library NAME." (declare (ignore name)) (open-shared-library path)) (defun %close-foreign-library (name) "Close the foreign library NAME." ;; C-S-L sometimes ends in an endless loop ;; with :COMPLETELY T (close-shared-library name :completely nil)) (defun native-namestring (pathname) (ccl::native-translated-namestring pathname)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (foreign-symbol-address (convert-external-name name)))
10,568
Common Lisp
.lisp
269
34.862454
75
0.675151
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
bf8ff4dc6636cf98533de8f5703d8c7d6d240b5e24361bdff47f0b7089c4157f
534
[ -1 ]
535
early-types.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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]> ;;; Copyright (C) 2005-2007, 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. ;;; ;;;# 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 ;;; ;;; 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-PARSE-METHOD should return a ;;; subtype of the foreign-type class. (defvar *type-parsers* (make-hash-table :test 'equal) "Hash table of defined type parsers.") (defun find-type-parser (symbol &optional (namespace :default)) "Return the type parser for SYMBOL." (or (gethash (cons namespace symbol) *type-parsers*) (if (eq namespace :default) (error "unknown CFFI type: ~S." symbol) (error "unknown CFFI type: (~S ~S)." namespace symbol)))) (defun (setf find-type-parser) (func symbol &optional (namespace :default)) "Set the type parser for SYMBOL." (setf (gethash (cons namespace symbol) *type-parsers*) func)) ;;; Using a generic function would have been nicer but generates lots ;;; of style warnings in SBCL. (Silly reason, yes.) (defmacro define-parse-method (name lambda-list &body body) "Define a type parser on NAME and lists whose CAR is NAME." (discard-docstring body) (warn-if-kw-or-belongs-to-cl name) `(eval-when (:compile-toplevel :load-toplevel :execute) (setf (find-type-parser ',name) (lambda ,lambda-list ,@body)) ',name)) ;;; Utility function for the simple case where the type takes no ;;; arguments. (defun notice-foreign-type (name type &optional (namespace :default)) (setf (find-type-parser name namespace) (lambda () type)) name) ;;;# Generic Functions on Types (defgeneric canonicalize (foreign-type) (:documentation "Return the most primitive foreign type for FOREIGN-TYPE, either a built-in type--a keyword--or a struct/union type--a list of the form (:STRUCT/:UNION name). 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 (foreign-type) (:documentation "Unparse FOREIGN-TYPE to a type specification (symbol or list).")) ;;;# Foreign Types (defclass foreign-type () () (:documentation "Base class for all foreign types.")) (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))) (defmethod foreign-type-size (type) "Return the size in bytes of a foreign type." (foreign-type-size (parse-type type))) (defclass named-foreign-type (foreign-type) ((name ;; Name of this foreign type, a symbol. :initform (error "Must specify a NAME.") :initarg :name :accessor name))) (defmethod print-object ((type named-foreign-type) stream) "Print a FOREIGN-TYPEDEF instance to STREAM unreadably." (print-unreadable-object (type stream :type t :identity nil) (format stream "~S" (name type)))) ;;; Return the type's name which can be passed to PARSE-TYPE. If ;;; that's not the case for some subclass of NAMED-FOREIGN-TYPE then ;;; it should specialize UNPARSE-TYPE. (defmethod unparse-type ((type named-foreign-type)) (name type)) ;;;# 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 unparse-type ((type foreign-built-in-type)) "Returns the symbolic representation of a built-in type." (type-keyword type)) (defmethod print-object ((type foreign-built-in-type) stream) "Print a FOREIGN-TYPE instance to STREAM unreadably." (print-unreadable-object (type stream :type t :identity nil) (format stream "~S" (type-keyword type)))) (defvar *built-in-foreign-types* nil) (defmacro define-built-in-foreign-type (keyword) "Defines a built-in foreign-type." `(eval-when (:compile-toplevel :load-toplevel :execute) (pushnew ,keyword *built-in-foreign-types*) (notice-foreign-type ,keyword (make-instance 'foreign-built-in-type :type-keyword ,keyword)))) ;;;# Foreign Pointer Types (defclass foreign-pointer-type (foreign-built-in-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 :type-keyword :pointer)) ;;; Define the type parser for the :POINTER type. If no type argument ;;; is provided, a void pointer will be created. (let ((void-pointer (make-instance 'foreign-pointer-type))) (define-parse-method :pointer (&optional type) (if type (make-instance 'foreign-pointer-type :pointer-type (parse-type type)) ;; A bit of premature optimization here. void-pointer))) ;;; Unparse a foreign pointer type when dumping to a fasl. (defmethod unparse-type ((type foreign-pointer-type)) (if (pointer-type type) `(:pointer ,(unparse-type (pointer-type 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)))) ;;;# Structure Type (defgeneric bare-struct-type-p (foreign-type) (:documentation "Return true if FOREIGN-TYPE is a bare struct type or an alias of a bare struct type. ")) (defmethod bare-struct-type-p ((type foreign-type)) "Return true if FOREIGN-TYPE is a bare struct type or an alias of a bare struct type. " nil) (defclass foreign-struct-type (named-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) (bare ;; we use this flag to support the (old, deprecated) semantics of ;; bare struct types. FOO means (:POINTER (:STRUCT FOO) in ;; functions declarations whereas FOO in a structure definition is ;; a proper aggregate type: (:STRUCT FOO), etc. :initform nil :initarg :bare :reader bare-struct-type-p))) (defun slots-in-order (structure-type) "A list of the structure's slots in order." (sort (loop for slots being the hash-value of (structure-slots structure-type) collect slots) #'< :key 'slot-offset)) (defmethod canonicalize ((type foreign-struct-type)) (if (bare-struct-type-p type) :pointer `(:struct ,(name type)))) (defmethod unparse-type ((type foreign-struct-type)) (if (bare-struct-type-p type) (name type) (canonicalize type))) (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)) (defclass foreign-union-type (foreign-struct-type) ()) (defmethod canonicalize ((type foreign-union-type)) (if (bare-struct-type-p type) :pointer `(:union ,(name type)))) ;;;# Foreign Typedefs (defclass foreign-type-alias (foreign-type) ((actual-type ;; The FOREIGN-TYPE instance this type is an alias for. :initarg :actual-type :accessor actual-type :initform (error "Must specify an ACTUAL-TYPE."))) (: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 named-foreign-type) ()) (defun follow-typedefs (type) (if (eq (type-of type) 'foreign-typedef) (follow-typedefs (actual-type type)) type)) (defmethod bare-struct-type-p ((type foreign-typedef)) (bare-struct-type-p (follow-typedefs type))) (defun structure-slots (type) "The hash table of slots for the structure type." (slots (follow-typedefs type))) ;;;# Type Translators ;;; ;;; Type translation is done with generic functions at runtime for ;;; subclasses of TRANSLATABLE-FOREIGN-TYPE. ;;; ;;; The main interface for defining type translations is through the ;;; generic functions TRANSLATE-{TO,FROM}-FOREIGN and ;;; FREE-TRANSLATED-OBJECT. (defclass translatable-foreign-type (foreign-type) ()) ;;; ENHANCED-FOREIGN-TYPE is used to define translations on top of ;;; previously defined foreign types. (defclass enhanced-foreign-type (translatable-foreign-type foreign-type-alias) ((unparsed-type :accessor unparsed-type))) ;;; If actual-type isn't parsed already, let's parse it. This way we ;;; don't have to export PARSE-TYPE and users don't have to worry ;;; about this in DEFINE-FOREIGN-TYPE or DEFINE-PARSE-METHOD. (defmethod initialize-instance :after ((type enhanced-foreign-type) &key) (unless (typep (actual-type type) 'foreign-type) (setf (actual-type type) (parse-type (actual-type type))))) (defmethod unparse-type ((type enhanced-foreign-type)) (unparsed-type type)) ;;; Checks NAMEs, not object identity. (defun check-for-typedef-cycles (type) (let ((seen (make-hash-table :test 'eq))) (labels ((%check (cur-type) (when (typep cur-type 'foreign-typedef) (when (gethash (name cur-type) seen) (error "Detected cycle in type ~S." type)) (setf (gethash (name cur-type) seen) t) (%check (actual-type cur-type))))) (%check type)))) ;;; Only now we define PARSE-TYPE because it needs to do some extra ;;; work for ENHANCED-FOREIGN-TYPES. (defun parse-type (type) (let* ((spec (ensure-list type)) (ptype (apply (find-type-parser (car spec)) (cdr spec)))) (when (typep ptype 'foreign-typedef) (check-for-typedef-cycles ptype)) (when (typep ptype 'enhanced-foreign-type) (setf (unparsed-type ptype) type)) ptype)) (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))) ;;; Translate VALUE to a foreign object of the type represented by ;;; TYPE, which will be a subclass of TRANSLATABLE-FOREIGN-TYPE. ;;; Returns the foreign value and an optional second value which will ;;; be passed to FREE-TRANSLATED-OBJECT as the PARAM argument. (defgeneric translate-to-foreign (value type) (:method (value type) (declare (ignore type)) value)) (defgeneric translate-into-foreign-memory (value type pointer) (:documentation "Translate the Lisp value into the foreign memory location given by pointer. Return value is not used.") (:argument-precedence-order type value pointer)) ;;; Similar to TRANSLATE-TO-FOREIGN, used exclusively by ;;; (SETF FOREIGN-STRUCT-SLOT-VALUE). (defgeneric translate-aggregate-to-foreign (ptr value type)) ;;; Translate the foreign object VALUE from the type repsented by ;;; TYPE, which will be a subclass of TRANSLATABLE-FOREIGN-TYPE. ;;; Returns the converted Lisp value. (defgeneric translate-from-foreign (value type) (:argument-precedence-order type value) (:method (value type) (declare (ignore type)) value)) ;;; Free an object allocated by TRANSLATE-TO-FOREIGN. VALUE is a ;;; foreign object of the type represented by TYPE, which will be a ;;; TRANSLATABLE-FOREIGN-TYPE subclass. PARAM, if present, contains ;;; the second value returned by TRANSLATE-TO-FOREIGN, and is used to ;;; communicate between the two functions. ;;; ;;; FIXME: I don't think this PARAM argument is necessary anymore ;;; because the TYPE object can contain that information. [2008-12-31 LO] (defgeneric free-translated-object (value type param) (:method (value type param) (declare (ignore value type 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. ;;; 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*) ;;; EXPAND-FROM-FOREIGN (defgeneric expand-from-foreign (value type) (:method (value type) (declare (ignore type)) value)) (defmethod expand-from-foreign :around (value (type translatable-foreign-type)) (let ((*runtime-translator-form* `(translate-from-foreign ,value ,type))) (call-next-method))) (defmethod expand-from-foreign (value (type translatable-foreign-type)) (declare (ignore value)) *runtime-translator-form*) ;;; EXPAND-TO-FOREIGN ;; The second return value is used to tell EXPAND-TO-FOREIGN-DYN that ;; an unspecialized method was called. (defgeneric expand-to-foreign (value type) (:method (value type) (declare (ignore type)) (values value t))) (defmethod expand-to-foreign :around (value (type translatable-foreign-type)) (let ((*runtime-translator-form* `(translate-to-foreign ,value ,type))) (call-next-method))) (defmethod expand-to-foreign (value (type translatable-foreign-type)) (declare (ignore value)) (values *runtime-translator-form* t)) ;;; EXPAND-TO-FOREIGN-DYN (defgeneric expand-to-foreign-dyn (value var body type) (:method (value var body type) (declare (ignore type)) `(let ((,var ,value)) ,@body))) (defmethod expand-to-foreign-dyn :around (value var body (type enhanced-foreign-type)) (let ((*runtime-translator-form* (with-unique-names (param) `(multiple-value-bind (,var ,param) (translate-to-foreign ,value ,type) (unwind-protect (progn ,@body) (free-translated-object ,var ,type ,param)))))) (call-next-method))) ;;; If this method is called it means the user hasn't defined a ;;; to-foreign-dyn expansion, so we use the to-foreign expansion. ;;; ;;; However, we do so *only* if there's a specialized ;;; EXPAND-TO-FOREIGN for TYPE because otherwise we want to use the ;;; above *RUNTIME-TRANSLATOR-FORM* which includes a call to ;;; FREE-TRANSLATED-OBJECT. (Or else there would occur no translation ;;; at all.) (defun foreign-expand-runtime-translator-or-binding (value var body type) (multiple-value-bind (expansion default-etp-p) (expand-to-foreign value type) (if default-etp-p *runtime-translator-form* `(let ((,var ,expansion)) ,@body)))) (defmethod expand-to-foreign-dyn (value var body (type enhanced-foreign-type)) (foreign-expand-runtime-translator-or-binding value var body type)) ;;; EXPAND-TO-FOREIGN-DYN-INDIRECT ;;; Like expand-to-foreign-dyn, but always give form that returns a ;;; pointer to the object, even if it's directly representable in ;;; CL, e.g. numbers. (defgeneric expand-to-foreign-dyn-indirect (value var body type) (:method (value var body type) (declare (ignore type)) `(let ((,var ,value)) ,@body))) (defmethod expand-to-foreign-dyn-indirect :around (value var body (type translatable-foreign-type)) (let ((*runtime-translator-form* `(with-foreign-object (,var ',(unparse-type type)) (translate-into-foreign-memory ,value ,type ,var) ,@body))) (call-next-method))) (defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-pointer-type)) `(with-foreign-object (,var :pointer) (translate-into-foreign-memory ,value ,type ,var) ,@body)) (defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-built-in-type)) `(with-foreign-object (,var :pointer) (translate-into-foreign-memory ,value ,type ,var) ,@body)) (defmethod expand-to-foreign-dyn-indirect (value var body (type translatable-foreign-type)) (foreign-expand-runtime-translator-or-binding value var body type)) (defmethod expand-to-foreign-dyn-indirect (value var body (type foreign-type-alias)) (expand-to-foreign-dyn-indirect value var body (actual-type type))) ;;; User interface for converting values from/to foreign using the ;;; type translators. The compiler macros use the expanders when ;;; possible. (defun convert-to-foreign (value type) (translate-to-foreign value (parse-type type))) (define-compiler-macro convert-to-foreign (value type) (if (constantp type) (expand-to-foreign value (parse-type (eval type))) `(translate-to-foreign ,value (parse-type ,type)))) (defun convert-from-foreign (value type) (translate-from-foreign value (parse-type type))) (define-compiler-macro convert-from-foreign (value type) (if (constantp type) (expand-from-foreign value (parse-type (eval type))) `(translate-from-foreign ,value (parse-type ,type)))) (defun free-converted-object (value type param) (free-translated-object value (parse-type type) param)) ;;;# Enhanced typedefs (defclass enhanced-typedef (foreign-typedef) ()) (defmethod translate-to-foreign (value (type enhanced-typedef)) (translate-to-foreign value (actual-type type))) (defmethod translate-into-foreign-memory (value (type enhanced-typedef) pointer) (translate-into-foreign-memory value (actual-type type) pointer)) (defmethod translate-from-foreign (value (type enhanced-typedef)) (translate-from-foreign value (actual-type type))) (defmethod free-translated-object (value (type enhanced-typedef) param) (free-translated-object value (actual-type type) param)) (defmethod expand-from-foreign (value (type enhanced-typedef)) (expand-from-foreign value (actual-type type))) (defmethod expand-to-foreign (value (type enhanced-typedef)) (expand-to-foreign value (actual-type type))) (defmethod expand-to-foreign-dyn (value var body (type enhanced-typedef)) (expand-to-foreign-dyn value var body (actual-type type))) ;;;# User-defined Types and Translations. (defmacro define-foreign-type (name supers slots &rest options) (multiple-value-bind (new-options simple-parser actual-type initargs) (let ((keywords '(:simple-parser :actual-type :default-initargs))) (apply #'values (remove-if (lambda (opt) (member (car opt) keywords)) options) (mapcar (lambda (kw) (cdr (assoc kw options))) keywords))) `(eval-when (:compile-toplevel :load-toplevel :execute) (defclass ,name ,(or supers '(enhanced-foreign-type)) ,slots (:default-initargs ,@(when actual-type `(:actual-type ',actual-type)) ,@initargs) ,@new-options) ,(when simple-parser `(define-parse-method ,(car simple-parser) (&rest args) (apply #'make-instance ',name args))) ',name))) (defmacro defctype (name base-type &optional documentation) "Utility macro for simple C-like typedefs." (declare (ignore documentation)) (warn-if-kw-or-belongs-to-cl name) (let* ((btype (parse-type base-type)) (dtype (if (typep btype 'enhanced-foreign-type) 'enhanced-typedef 'foreign-typedef))) `(eval-when (:compile-toplevel :load-toplevel :execute) (notice-foreign-type ',name (make-instance ',dtype :name ',name :actual-type ,btype))))) ;;; For Verrazano. We memoize the type this way to help detect cycles. (defmacro defctype* (name base-type) "Like DEFCTYPE but defers instantiation until parse-time." `(eval-when (:compile-toplevel :load-toplevel :execute) (let (memoized-type) (define-parse-method ,name () (unless memoized-type (setf memoized-type (make-instance 'foreign-typedef :name ',name :actual-type nil) (actual-type memoized-type) (parse-type ',base-type))) memoized-type))))
23,448
Common Lisp
.lisp
516
41.55814
108
0.716521
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
943fe5fbac2d87f5a9b057ae48f99396aa991eb8ebe34caf82ccff31f3f1686d
535
[ -1 ]
536
cffi-cmucl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/cffi-cmucl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-cmucl.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) (:import-from #:alexandria #:once-only #:with-unique-names #:if-let) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures (pushnew 'flat-namespace *features*) ;;;# Symbol Case (defun canonicalize-symbol-name-case (name) (declare (string name)) (string-upcase name)) ;;;# Basic Pointer Operations (deftype foreign-pointer () 'sys:system-area-pointer) (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 args &key library convention) "Perform a foreign function call, document it more later." (declare (ignore library convention)) (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(%%foreign-funcall ,name ,types ,fargs ,rettype))) (defmacro %foreign-funcall-pointer (ptr args &key convention) "Funcall a pointer to a foreign function." (declare (ignore convention)) (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" (if-let (package (symbol-package name)) (package-name package) name) (symbol-name name)) '#:cffi-callbacks))) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (declare (ignore convention)) (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)) ;;; CMUCL makes new callback trampolines when it reloads, so we need ;;; to update CFFI's copies. (defun reset-callbacks () (loop for k being the hash-keys of *callbacks* do (setf (gethash k *callbacks*) (alien::symbol-trampoline (intern-callback k))))) ;; Needs to be after cmucl's restore-callbacks, so put at the end... (unless (member 'reset-callbacks ext:*after-save-initializations*) (setf ext:*after-save-initializations* (append ext:*after-save-initializations* (list 'reset-callbacks)))) ;;;# 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 path) "Load the foreign library NAME." ;; On some platforms SYS::LOAD-OBJECT-FILE signals an error when ;; loading fails, but on others (Linux for instance) it returns ;; two values: NIL and an error string. (declare (ignore name)) (multiple-value-bind (ret message) (sys::load-object-file path) (cond ;; Loading failed. ((stringp message) (error "~A" message)) ;; The library was already loaded. ((null ret) (cdr (rassoc path sys::*global-table* :test #'string=))) ;; The library has been loaded, but since SYS::LOAD-OBJECT-FILE ;; returns an alist of *all* loaded libraries along with their addresses ;; we return only the handler associated with the library just loaded. (t (cdr (rassoc path ret :test #'string=)))))) ;;; 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 (handler) "Closes a foreign library." (let ((lib (rassoc (ext:unix-namestring handler) sys::*global-table* :test #'string=))) (sys::dlclose (car lib)) (setf (car lib) (sys:int-sap 0)))) (defun native-namestring (pathname) (ext:unix-namestring pathname nil)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (let ((address (sys:alternate-get-global-address (vm:extern-alien-name name)))) (if (zerop address) nil (sys:int-sap address))))
13,220
Common Lisp
.lisp
335
34.579104
78
0.667653
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
74bb4acf33974364d39ead6589888ef7c902385b5375dfbc93981afacf9d1bbc
536
[ 72399, 468745 ]
537
features.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/features.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; features.lisp --- CFFI-specific features. ;;; ;;; Copyright (C) 2006-2007, 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*)) ;;; CFFI-SYS backends take care of pushing the appropriate features to ;;; *features*. See each cffi-*.lisp file. ;;; ;;; Not anymore, I think we should use TRIVIAL-FEATURES for the ;;; platform features instead. Less pain. CFFI-FEATURES is now ;;; deprecated and this code will stay here for a while for backwards ;;; compatibility purposes, to be removed in a future release. (defpackage #:cffi-features (:use #:cl) (:export #:cffi-feature-p ;; Features related to the CFFI-SYS backend. Why no-*? This ;; reflects the hope that these symbols will go away completely ;; meaning that at some point all lisps will support long-longs, ;; the foreign-funcall primitive, etc... #:no-long-long #:no-foreign-funcall #:no-stdcall #:flat-namespace ;; Only SCL supports long-double... ;;#:no-long-double ;; Features related to the operating system. ;; More should be added. #:darwin #:unix #:windows ;; Features related to the processor. ;; More should be added. #:ppc32 #:x86 #:x86-64 #:sparc #:sparc64 #:hppa #:hppa64)) (in-package #:cffi-features) (defun cffi-feature-p (feature-expression) "Matches a FEATURE-EXPRESSION against those symbols in *FEATURES* that belong to the CFFI-FEATURES package." (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)))))))))) ;;; for backwards compatibility (mapc (lambda (sym) (pushnew sym *features*)) '(#+darwin darwin #+unix unix #+windows windows #+ppc ppc32 #+x86 x86 #+x86-64 x86-64 #+sparc sparc #+sparc64 sparc64 #+hppa hppa #+hppa64 hppa64 #+cffi-sys::no-long-long no-long-long #+cffi-sys::flat-namespace flat-namespace #+cffi-sys::no-foreign-funcall no-foreign-funcall #+cffi-sys::no-stdcall no-stdcall ))
3,952
Common Lisp
.lisp
100
34.96
72
0.681854
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
100649301ba0aafec03201bffd60c06c883afbc8a35d320600fb7b91dcc1b6ee
537
[ 175817 ]
538
cffi-gcl.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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 #:alexandria) (: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,297
Common Lisp
.lisp
268
35.097015
75
0.663862
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
6fa304a52b311f647762fd8bfb19838170c9209850841cbef4dda2292bbb451c
538
[ 114501, 340508 ]
539
functions.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/functions.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; functions.lisp --- High-level interface to foreign functions. ;;; ;;; Copyright (C) 2005-2006, James Bielman <[email protected]> ;;; Copyright (C) 2005-2007, 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) ;;;# 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-FORM argument) instead of ;;; CFFI-SYS:%FOREIGN-FUNCALL to call the foreign-function. (defun translate-objects (syms args types rettype call-form &optional indirect) "Helper function for FOREIGN-FUNCALL and DEFCFUN. If 'indirect is T, all arguments are represented by foreign pointers, even those that can be represented by CL objects." (if (null args) (expand-from-foreign call-form (parse-type rettype)) (funcall (if indirect #'expand-to-foreign-dyn-indirect #'expand-to-foreign-dyn) (car args) (car syms) (list (translate-objects (cdr syms) (cdr args) (cdr types) rettype call-form indirect)) (parse-type (car types))))) (defun parse-args-and-types (args) "Returns 4 values. Types, canonicalized types, args and return type." (let* ((len (length args)) (return-type (if (oddp len) (lastcar args) :void))) (loop repeat (floor len 2) for (type arg) on args by #'cddr collect type into types collect (canonicalize-foreign-type type) into ctypes collect arg into fargs finally (return (values types ctypes fargs return-type))))) ;;; While the options passed directly to DEFCFUN/FOREIGN-FUNCALL have ;;; precedence, we also grab its library's options, if possible. (defun parse-function-options (options &key pointer) (destructuring-bind (&key (library :default libraryp) (cconv nil cconv-p) (calling-convention cconv calling-convention-p) (convention calling-convention)) options (when cconv-p (warn-obsolete-argument :cconv :convention)) (when calling-convention-p (warn-obsolete-argument :calling-convention :convention)) (list* :convention (or convention (when libraryp (let ((lib-options (foreign-library-options (get-foreign-library library)))) (getf lib-options :convention))) :cdecl) ;; Don't pass the library option if we're dealing with ;; FOREIGN-FUNCALL-POINTER. (unless pointer (list :library library))))) (defun structure-by-value-p (ctype) "A structure or union is to be called or returned by value." (let ((actual-type (follow-typedefs (parse-type ctype)))) (or (and (typep actual-type 'foreign-struct-type) (not (bare-struct-type-p actual-type))) #+cffi::no-long-long (typep actual-type 'emulated-llong-type)))) (defun fn-call-by-value-p (argument-types return-type) "One or more structures in the arguments or return from the function are called by value." (or (some 'structure-by-value-p argument-types) (structure-by-value-p return-type))) (defvar *foreign-structures-by-value* (lambda (&rest args) (declare (ignore args)) (restart-case (error "Unable to call structures by value without cffi-libffi loaded.") (load-cffi-libffi () :report "Load cffi-libffi." (asdf:operate 'asdf:load-op 'cffi-libffi)))) "A function that produces a form suitable for calling structures by value.") (defun foreign-funcall-form (thing options args pointerp) (multiple-value-bind (types ctypes fargs rettype) (parse-args-and-types args) (let ((syms (make-gensym-list (length fargs))) (fsbvp (fn-call-by-value-p ctypes rettype))) (translate-objects syms fargs types rettype (if fsbvp ;; Structures by value call through *foreign-structures-by-value* (funcall *foreign-structures-by-value* thing syms rettype ctypes pointerp) `(,(if pointerp '%foreign-funcall-pointer '%foreign-funcall) ;; No structures by value, direct call ,thing (,@(mapcan #'list ctypes syms) ,(canonicalize-foreign-type rettype)) ,@(parse-function-options options :pointer pointerp))) fsbvp)))) (defmacro foreign-funcall (name-and-options &rest args) "Wrapper around %FOREIGN-FUNCALL that translates its arguments." (let ((name (car (ensure-list name-and-options))) (options (cdr (ensure-list name-and-options)))) (foreign-funcall-form name options args nil))) (defmacro foreign-funcall-pointer (pointer options &rest args) (foreign-funcall-form pointer options args t)) (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))) (defun foreign-funcall-varargs-form (thing options fixed-args varargs pointerp) (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 pointerp '%foreign-funcall-pointer '%foreign-funcall) ,thing ,(append (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))) (list (canonicalize-foreign-type rettype))) ,@options)))))) ;;; For now, 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-and-options fixed-args &rest varargs) "Wrapper around %FOREIGN-FUNCALL that translates its arguments and does type promotion for the variadic arguments." (let ((name (car (ensure-list name-and-options))) (options (cdr (ensure-list name-and-options)))) (foreign-funcall-varargs-form name options fixed-args varargs nil))) (defmacro foreign-funcall-pointer-varargs (pointer options fixed-args &rest varargs) "Wrapper around %FOREIGN-FUNCALL-POINTER that translates its arguments and does type promotion for the variadic arguments." (foreign-funcall-varargs-form pointer options fixed-args varargs t)) ;;;# Defining Foreign Functions ;;; ;;; The DEFCFUN macro provides a declarative interface for defining ;;; Lisp functions that call foreign functions. ;; 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 options) (declare (ignore lisp-name)) (values '() `(%foreign-funcall ,name ,(append (mapcan #'list types args) (list rettype)) ,@options))))) (defun %defcfun (lisp-name foreign-name return-type args options docstring) (let* ((arg-names (mapcar #'first args)) (arg-types (mapcar #'second args)) (syms (make-gensym-list (length args))) (call-by-value (fn-call-by-value-p arg-types return-type))) (multiple-value-bind (prelude caller) (if call-by-value (values nil nil) (defcfun-helper-forms foreign-name lisp-name (canonicalize-foreign-type return-type) syms (mapcar #'canonicalize-foreign-type arg-types) options)) `(progn ,prelude (defun ,lisp-name ,arg-names ,@(ensure-list docstring) ,(if call-by-value `(foreign-funcall ,(cons foreign-name options) ,@(append (mapcan #'list arg-types arg-names) (list return-type))) (translate-objects syms arg-names arg-types return-type caller))))))) (defun %defcfun-varargs (lisp-name foreign-name return-type args options doc) (with-unique-names (varargs) (let ((arg-names (mapcar #'car args))) `(defmacro ,lisp-name (,@arg-names &rest ,varargs) ,@(ensure-list doc) `(foreign-funcall-varargs ,'(,foreign-name ,@options) ,,`(list ,@(loop for (name type) in args collect `',type collect name)) ,@,varargs ,',return-type))))) (defgeneric translate-underscore-separated-name (name) (:method ((name string)) (values (intern (canonicalize-symbol-name-case (substitute #\- #\_ name))))) (:method ((name symbol)) (substitute #\_ #\- (string-downcase (symbol-name name))))) (defun collapse-prefix (l special-words) (unless (null l) (multiple-value-bind (newpre skip) (check-prefix l special-words) (cons newpre (collapse-prefix (nthcdr skip l) special-words))))) (defun check-prefix (l special-words) (let ((pl (loop for i from (1- (length l)) downto 0 collect (apply #'concatenate 'simple-string (butlast l i))))) (loop for w in special-words for p = (position-if #'(lambda (s) (string= s w)) pl) when p do (return-from check-prefix (values (nth p pl) (1+ p)))) (values (first l) 1))) (defun split-if (test seq &optional (dir :before)) (remove-if #'(lambda (x) (equal x (subseq seq 0 0))) (loop for start fixnum = 0 then (if (eq dir :before) stop (the fixnum (1+ (the fixnum stop)))) while (< start (length seq)) for stop = (position-if test seq :start (if (eq dir :elide) start (the fixnum (1+ start)))) collect (subseq seq start (if (and stop (eq dir :after)) (the fixnum (1+ (the fixnum stop))) stop)) while stop))) (defgeneric translate-camelcase-name (name &key upper-initial-p special-words) (:method ((name string) &key upper-initial-p special-words) (declare (ignore upper-initial-p)) (values (intern (reduce #'(lambda (s1 s2) (concatenate 'simple-string s1 "-" s2)) (mapcar #'string-upcase (collapse-prefix (split-if #'(lambda (ch) (or (upper-case-p ch) (digit-char-p ch))) name) special-words)))))) (:method ((name symbol) &key upper-initial-p special-words) (apply #'concatenate 'string (loop for str in (split-if #'(lambda (ch) (eq ch #\-)) (string name) :elide) for first-word-p = t then nil for e = (member str special-words :test #'equal :key #'string-upcase) collect (cond ((and first-word-p (not upper-initial-p)) (string-downcase str)) (e (first e)) (t (string-capitalize str))))))) (defgeneric translate-name-from-foreign (foreign-name package &optional varp) (:method (foreign-name package &optional varp) (declare (ignore package)) (let ((sym (translate-underscore-separated-name foreign-name))) (if varp (values (intern (format nil "*~A*" (canonicalize-symbol-name-case (symbol-name sym))))) sym)))) (defgeneric translate-name-to-foreign (lisp-name package &optional varp) (:method (lisp-name package &optional varp) (declare (ignore package)) (let ((name (translate-underscore-separated-name lisp-name))) (if varp (string-trim '(#\*) name) name)))) (defun lisp-name (spec varp) (check-type spec string) (translate-name-from-foreign spec *package* varp)) (defun foreign-name (spec varp) (check-type spec (and symbol (not null))) (translate-name-to-foreign spec *package* varp)) (defun foreign-options (opts varp) (if varp (funcall 'parse-defcvar-options opts) (parse-function-options opts))) (defun lisp-name-p (name) (and name (symbolp name) (not (keywordp name)))) (defun %parse-name-and-options (spec varp) (cond ((stringp spec) (values (lisp-name spec varp) spec nil)) ((symbolp spec) (assert (not (null spec))) (values spec (foreign-name spec varp) nil)) ((and (consp spec) (stringp (first spec))) (destructuring-bind (foreign-name &rest options) spec (cond ((or (null options) (keywordp (first options))) (values (lisp-name foreign-name varp) foreign-name options)) (t (assert (lisp-name-p (first options))) (values (first options) foreign-name (rest options)))))) ((and (consp spec) (lisp-name-p (first spec))) (destructuring-bind (lisp-name &rest options) spec (cond ((or (null options) (keywordp (first options))) (values lisp-name (foreign-name spec varp) options)) (t (assert (stringp (first options))) (values lisp-name (first options) (rest options)))))) (t (error "Not a valid foreign function specifier: ~A" spec)))) ;;; DEFCFUN's first argument has can have the following syntax: ;;; ;;; 1. string ;;; 2. symbol ;;; 3. \( string [symbol] options* ) ;;; 4. \( symbol [string] options* ) ;;; ;;; The string argument denotes the foreign function's name. The ;;; symbol argument is used to name the Lisp function. If one isn't ;;; present, its name is derived from the other. See the user ;;; documentation for an explanation of the derivation rules. (defun parse-name-and-options (spec &optional varp) (multiple-value-bind (lisp-name foreign-name options) (%parse-name-and-options spec varp) (values lisp-name foreign-name (foreign-options options varp)))) ;;; If we find a &REST token at the end of ARGS, it means this is a ;;; varargs foreign function therefore we define a lisp macro using ;;; %DEFCFUN-VARARGS. Otherwise, a lisp function is defined with ;;; %DEFCFUN. (defmacro defcfun (name-and-options return-type &body args) "Defines a Lisp function that calls a foreign function." (let ((docstring (when (stringp (car args)) (pop args)))) (multiple-value-bind (lisp-name foreign-name options) (parse-name-and-options name-and-options) (if (eq (lastcar args) '&rest) (%defcfun-varargs lisp-name foreign-name return-type (butlast args) options docstring) (%defcfun lisp-name foreign-name return-type args options docstring))))) ;;;# 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-from-foreign arg (parse-type type))))) ,@declarations ,(expand-to-foreign call (parse-type rettype)))) (defun parse-defcallback-options (options) (destructuring-bind (&key (cconv :cdecl cconv-p) (calling-convention cconv calling-convention-p) (convention calling-convention)) options (when cconv-p (warn-obsolete-argument :cconv :convention)) (when calling-convention-p (warn-obsolete-argument :calling-convention :convention)) (list :convention convention))) (defmacro defcallback (name-and-options return-type args &body body) (multiple-value-bind (body declarations) (parse-body body :documentation t) (let ((arg-names (mapcar #'car args)) (arg-types (mapcar #'cadr args)) (name (car (ensure-list name-and-options))) (options (cdr (ensure-list name-and-options)))) `(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)) ,@(parse-defcallback-options options)) ',name)))) (declaim (inline get-callback)) (defun get-callback (symbol) (%callback symbol)) (defmacro callback (name) `(%callback ',name))
19,487
Common Lisp
.lisp
411
37.43309
173
0.612386
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
24c6a8186442ea174e1fecf0a6cf22c0f592134616bbcc80ae4d124a52dcf317
539
[ -1 ]
540
libraries.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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-2007, 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 (:or "libGL.so" "libGL.so.1" ;;; #p"/myhome/mylibGL.so")) ;;; (:windows "opengl32.dll") ;;; ;; an hypothetical example of a particular platform ;;; ((:and :some-system :some-cpu) "libGL-support.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 (or ;;; USE-FOREIGN-LIBRARY) the first clause matched by FEATUREP is ;;; processed. (defvar *foreign-libraries* (make-hash-table :test 'eq) "Hashtable of defined libraries.") (defclass foreign-library () ((name :initform nil :initarg :name :accessor foreign-library-name) (type :initform :system :initarg :type) (spec :initarg :spec) (options :initform nil :initarg :options) (handle :initform nil :initarg :handle :accessor foreign-library-handle) (pathname :initform nil))) (defmethod print-object ((library foreign-library) stream) (with-slots (name pathname) library (print-unreadable-object (library stream :type t) (when name (format stream "~A" name)) (when pathname (format stream " ~S" (file-namestring pathname)))))) (define-condition foreign-library-undefined-error (error) ((name :initarg :name :reader fl-name)) (:report (lambda (c s) (format s "Undefined foreign library: ~S" (fl-name c))))) (defun get-foreign-library (lib) "Look up a library by NAME, signalling an error if not found." (if (typep lib 'foreign-library) lib (or (gethash lib *foreign-libraries*) (error 'foreign-library-undefined-error :name lib)))) (defun (setf get-foreign-library) (value name) (setf (gethash name *foreign-libraries*) value)) (defun foreign-library-type (lib) (slot-value (get-foreign-library lib) 'type)) (defun foreign-library-pathname (lib) (slot-value (get-foreign-library lib) 'pathname)) (defun %foreign-library-spec (lib) (assoc-if (lambda (feature) (or (eq feature t) (featurep feature))) (slot-value lib 'spec))) (defun foreign-library-spec (lib) (second (%foreign-library-spec lib))) (defun foreign-library-options (lib) (append (cddr (%foreign-library-spec lib)) (slot-value lib 'options))) (defun foreign-library-search-path (lib) (loop for (opt val) on (foreign-library-options lib) by #'cddr when (eql opt :search-path) append (ensure-list val) into search-path finally (return (mapcar #'pathname search-path)))) (defun foreign-library-loaded-p (lib) (not (null (slot-value (get-foreign-library lib) 'handle)))) (defun list-foreign-libraries (&key (loaded-only t) type) "Return a list of defined foreign libraries. If LOADED-ONLY is non-null only loaded libraries are returned. TYPE restricts the output to a specific library type: if NIL all libraries are returned." (let ((libs (hash-table-values *foreign-libraries*))) (remove-if (lambda (lib) (or (and type (not (eql type (foreign-library-type lib)))) (and loaded-only (not (foreign-library-loaded-p lib))))) libs))) ;; :CONVENTION, :CALLING-CONVENTION and :CCONV are coalesced, ;; the former taking priority ;; options with NULL values are removed (defun clean-spec-up (spec) (mapcar (lambda (x) (list* (first x) (second x) (let* ((opts (cddr x)) (cconv (getf opts :cconv)) (calling-convention (getf opts :calling-convention)) (convention (getf opts :convention)) (search-path (getf opts :search-path))) (remf opts :cconv) (remf opts :calling-convention) (when cconv (warn-obsolete-argument :cconv :convention)) (when calling-convention (warn-obsolete-argument :calling-convention :convention)) (setf (getf opts :convention) (or convention calling-convention cconv)) (setf (getf opts :search-path) (mapcar #'pathname (ensure-list search-path))) (loop for (opt val) on opts by #'cddr when val append (list opt val) into new-opts finally (return new-opts))))) spec)) (defmethod initialize-instance :after ((lib foreign-library) &key search-path (cconv :cdecl cconv-p) (calling-convention cconv calling-convention-p) (convention calling-convention)) (with-slots (type options spec) lib (check-type type (member :system :test :grovel-wrapper)) (setf spec (clean-spec-up spec)) (let ((all-options (apply #'append options (mapcar #'cddr spec)))) (assert (subsetp (loop for (key . nil) on all-options by #'cddr collect key) '(:convention :search-path))) (when cconv-p (warn-obsolete-argument :cconv :convention)) (when calling-convention-p (warn-obsolete-argument :calling-convention :convention)) (flet ((set-option (key value) (when value (setf (getf options key) value)))) (set-option :convention convention) (set-option :search-path (mapcar #'pathname (ensure-list search-path))))))) (defun register-foreign-library (name spec &rest options) (let ((old-handle (when-let ((old-lib (gethash name *foreign-libraries*))) (foreign-library-handle old-lib)))) (setf (get-foreign-library name) (apply #'make-instance 'foreign-library :name name :spec spec :handle old-handle options)) name)) (defmacro define-foreign-library (name-and-options &body pairs) "Defines a foreign library NAME that can be posteriorly used with the USE-FOREIGN-LIBRARY macro." (destructuring-bind (name . options) (ensure-list name-and-options) (check-type name symbol) `(register-foreign-library ',name ',pairs ,@options))) ;;;# 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. (define-condition load-foreign-library-error (simple-error) ()) (defun read-new-value () (format *query-io* "~&Enter a new value (unevaluated): ") (force-output *query-io*) (read *query-io*)) (defun fl-error (control &rest arguments) (error 'load-foreign-library-error :format-control control :format-arguments arguments)) ;;;# Loading Foreign Libraries (defun load-darwin-framework (name 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-path name (native-namestring framework)) (fl-error "Unable to find framework ~A" framework-name)))) (defun report-simple-error (name error) (fl-error "Unable to load foreign library (~A).~% ~A" name (format nil "~?" (simple-condition-format-control error) (simple-condition-format-arguments error)))) ;;; FIXME: haven't double checked whether all Lisps signal a ;;; SIMPLE-ERROR on %load-foreign-library failure. In any case they ;;; should be throwing a more specific error. (defun load-foreign-library-path (name path &optional search-path) "Tries to load PATH 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." (handler-case (values (%load-foreign-library name path) (pathname path)) (error (error) (if-let (file (find-file path (append search-path *foreign-library-directories*))) (handler-case (values (%load-foreign-library name (native-namestring file)) file) (simple-error (error) (report-simple-error name error))) (report-simple-error name error))))) (defun try-foreign-library-alternatives (name library-list) "Goes through a list of alternatives and only signals an error when none of alternatives were successfully loaded." (dolist (lib library-list) (multiple-value-bind (handle pathname) (ignore-errors (load-foreign-library-helper name lib)) (when handle (return-from try-foreign-library-alternatives (values handle pathname))))) ;; Perhaps we should show the error messages we got for each ;; alternative if we can figure out a nice way to do that. (fl-error "Unable to load any of the alternatives:~% ~S" library-list)) (defparameter *cffi-feature-suffix-map* '((:windows . ".dll") (:darwin . ".dylib") (:unix . ".so") (t . ".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 #'featurep *cffi-feature-suffix-map*)) (fl-error "Unable to determine the default library suffix on this OS."))) (defun load-foreign-library-helper (name thing &optional search-path) (etypecase thing ((or pathname string) (load-foreign-library-path (filter-pathname name) thing search-path)) (cons (ecase (first thing) (:framework (load-darwin-framework name (second thing))) (:default (unless (stringp (second thing)) (fl-error "Argument to :DEFAULT must be a string.")) (let ((library-path (concatenate 'string (second thing) (default-library-suffix)))) (load-foreign-library-path name library-path search-path))) (:or (try-foreign-library-alternatives name (rest thing))))))) (defun %do-load-foreign-library (library search-path) (flet ((%do-load (lib name spec) (when (foreign-library-spec lib) (with-slots (handle pathname) lib (setf (values handle pathname) (load-foreign-library-helper name spec (foreign-library-search-path lib))))) (print (slot-value lib 'pathname)) ;;; test/check lib)) (etypecase library (symbol (let* ((lib (get-foreign-library library)) (spec (foreign-library-spec lib))) (%do-load lib library spec))) ((or string list) (let* ((lib-name (gensym (format nil "~:@(~A~)-" (if (listp library) (first library) (file-namestring library))))) (lib (make-instance 'foreign-library :type :system :name lib-name :spec `((t ,library)) :search-path search-path))) ;; first try to load the anonymous library ;; and register it only if that worked (%do-load lib lib-name library) (setf (get-foreign-library lib-name) lib)))))) (defun filter-pathname (thing) (typecase thing (pathname (namestring thing)) (t thing))) (defun load-foreign-library (library &key search-path) "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>)." (let ((library (filter-pathname library))) (restart-case (progn (ignore-some-conditions (foreign-library-undefined-error) (close-foreign-library library)) (%do-load-foreign-library library search-path)) ;; Offer these restarts that will retry the call to ;; %LOAD-FOREIGN-LIBRARY. (retry () :report "Try loading the foreign library again." (load-foreign-library library :search-path search-path)) (use-value (new-library) :report "Use another library instead." :interactive read-new-value (load-foreign-library new-library :search-path search-path))))) (defmacro use-foreign-library (name) `(load-foreign-library ',name)) ;;;# Closing Foreign Libraries (defun close-foreign-library (library) "Closes a foreign library." (let* ((library (filter-pathname library)) (lib (get-foreign-library library)) (handle (foreign-library-handle lib))) (when handle (%close-foreign-library handle) (setf (foreign-library-handle lib) nil) t))) (defun reload-foreign-libraries (&key (test #'foreign-library-loaded-p)) "(Re)load all currently loaded foreign libraries." (let ((libs (list-foreign-libraries))) (loop :for l :in libs :for name := (foreign-library-name l) :do (when (funcall test name) (load-foreign-library name))) libs))
17,335
Common Lisp
.lisp
379
38.287599
79
0.649459
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
faa43dd6d3736c3f5104af09f0ae99cd27969179fe83c530a714f6a0186c760d
540
[ -1 ]
541
cffi-allegro.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/cffi-allegro.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-allegro.lisp --- CFFI-SYS implementation for Allegro CL. ;;; ;;; Copyright (C) 2005-2009, 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) (:import-from #:alexandria #:if-let #:with-unique-names #:once-only) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:defcfun-helper-forms #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Mis-features #-64bit (pushnew 'no-long-long *features*) (pushnew 'flat-namespace *features*) ;;;# 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 (deftype foreign-pointer () 'ff:foreign-address) (defun pointerp (ptr) "Return true if PTR is a foreign pointer." (ff:foreign-address-p 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." (check-type address ff:foreign-address) address) (defun pointer-address (ptr) "Return the address pointed to by PTR." (check-type ptr ff:foreign-address) 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"))) #+(version>= 8 1) (when (and (constantp size) (<= (eval size) ff:*max-stack-fobject-bytes*)) (return-from with-foreign-pointer `(let ((,size-var ,(eval size))) (declare (ignorable ,size-var)) (ff:with-static-fobject (,var '(:array :char ,(eval size)) :allocation :foreign-static-gc) ;; (excl::stack-allocated-p var) => T (let ((,var (ff:fslot-address ,var))) ,@body))))) `(let* ((,size-var ,size) (,var (ff:allocate-fobject :char :c ,size-var))) (unwind-protect (progn ,@body) (ff:free-fobject ,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) :allocation :static-reclaimable)) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind PTR-VAR to a foreign pointer to the data in VECTOR." ;; An array allocated in static-reclamable is a non-simple array in ;; the normal Lisp allocation area, pointing to a simple array in ;; the static-reclaimable allocation area. Therefore we have to get ;; out the simple-array to find the pointer to the actual contents. (with-unique-names (simple-vec) `(excl:with-underlying-simple-vector (,vector ,simple-vec) (let ((,ptr-var (ff:fslot-address-typed :unsigned-char :lisp ,simple-vec))) ,@body)))) ;;;# Dereferencing (defun convert-foreign-type (type-keyword) "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) (:long-long #+64bit :nat #-64bit (error "this platform does not support :long-long.")) (:unsigned-long-long #+64bit :unsigned-nat #-64bit (error "this platform does not support :unsigned-long-long")) (:float :float) (:double :double) (:pointer :unsigned-nat) (: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 type into types and collect arg into fargs else do (setf return-type type) finally (return (values types fargs return-type))))) (defun convert-to-lisp-type (type) (ecase type ((:char :short :int :long :nat) `(signed-byte ,(* 8 (ff:sizeof-fobject type)))) ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long :unsigned-nat) `(unsigned-byte ,(* 8 (ff:sizeof-fobject type)))) (:float 'single-float) (:double 'double-float) (:void 'null))) (defun allegro-type-pair (cffi-type) ;; the :FOREIGN-ADDRESS pseudo-type accepts both pointers and ;; arrays. We need the latter for shareable byte vector support. (if (eq cffi-type :pointer) (list :foreign-address) (let ((ftype (convert-foreign-type cffi-type))) (list ftype (convert-to-lisp-type ftype))))) #+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 rettype) ;; arg types '({(:c-type lisp-type)}*) '(,@(mapcar #'allegro-type-pair types)) nil ; arg-checking ff::ep-flag-never-release)))) (defmacro %foreign-funcall (name args &key convention library) (declare (ignore convention library)) (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 options) "Return 2 values for DEFCFUN. A prelude form and a caller form." (declare (ignore options)) (let ((ff-name (intern (format nil "%cffi-foreign-function/~A" lisp-name)))) (values `(ff:def-foreign-call (,ff-name ,name) ,(loop for type in types collect (list* (gensym) (allegro-type-pair type))) :returning ,(allegro-type-pair rettype) ;; 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 args &key convention) (declare (ignore convention)) (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" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks)) (defun convert-calling-convention (convention) (ecase convention (:cdecl :c) (:stdcall :stdcall))) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (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 ,(convert-calling-convention convention))) ,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 path) "Load a foreign library." ;; 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. (declare (ignore name)) (let ((excl::*load-foreign-types* (list (pathname-type (parse-namestring path))))) (handler-case (progn #+(version>= 7) (load path :foreign t) #-(version>= 7) (load path)) (file-error (fe) (error (change-class fe 'simple-error)))) path)) (defun %close-foreign-library (name) "Close the foreign library NAME." (ff:unload-foreign-library name)) (defun native-namestring (pathname) (namestring pathname)) ;;;# 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 library) "Returns a pointer to a foreign symbol NAME." (declare (ignore library)) (prog1 (ff:get-entry-point (convert-external-name name))))
16,048
Common Lisp
.lisp
386
36.106218
80
0.660707
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
cede3eecb4e591e261f8c4a6a59cee62407512262425c8941d215b0544b5644c
541
[ -1 ]
542
cffi-lispworks.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/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 #:alexandria) (:export #:canonicalize-symbol-name-case #:foreign-pointer #: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 #:native-namestring #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:%foreign-symbol-pointer #:defcfun-helper-forms #:%defcallback #:%callback)) (in-package #:cffi-sys) ;;;# Misfeatures #-lispworks-64bit (pushnew 'no-long-long *features*) ;;;# Symbol Case (defun canonicalize-symbol-name-case (name) (declare (string name)) (string-upcase name)) ;;;# Basic Pointer Operations (deftype foreign-pointer () 'fli::pointer) (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." (check-type ptr fli::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." #+(or lispworks3 lispworks4 lispworks5.0) (sys:in-static-area (make-array size :element-type '(unsigned-byte 8))) #-(or lispworks3 lispworks4 lispworks5.0) (make-array size :element-type '(unsigned-byte 8) :allocation :static)) (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)) ;; On 32-bit platforms, Lispworks 5.0+ supports long-long for ;; DEFCFUN and FOREIGN-FUNCALL. (:long-long '(:long :long)) (:unsigned-long-long '(:unsigned :long :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 #+lispworks-64bit :long-long) `(signed-byte ,(* 8 (%foreign-type-size cffi-type)))) ((:unsigned-char :unsigned-short :unsigned-int :unsigned-long #+lispworks-64bit :unsigned-long-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))) ;; Lispworks 5.0 on 64-bit platforms doesn't have [u]int64 support in ;; FOREIGN-TYPED-AREF. That was implemented in 5.1. #+(and lispworks-64bit lispworks5.0) (defun 64-bit-type-p (type) (member type '(:long :unsigned-long :long-long :unsigned-long-long))) ;;; 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 (or #+(and lispworks-64bit lispworks5.0) (64-bit-type-p type) (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 (or #+(and lispworks-64bit lispworks5.0) (64-bit-type-p type) (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 convention) "Creates a foreign funcallable for the signature TYPES -> RETTYPE." #+mac (declare (ignore convention)) (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 ,@(list :calling-convention convention))))) internal-name)) (defun get-foreign-funcallable (types rettype convention) "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 convention))))) (defmacro %%foreign-funcall (foreign-function args convention) "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 ',convention)) ,foreign-function ,@fargs))) (defmacro %foreign-funcall (name args &key library convention) "Calls a foreign function named NAME passing arguments ARGS." `(%%foreign-funcall (fli:make-pointer :symbol-name ,name :module ',(if (eq library :default) nil library)) ,args ,convention)) (defmacro %foreign-funcall-pointer (ptr args &key convention) "Calls a foreign function pointed at by PTR passing arguments ARGS." `(%%foreign-funcall ,ptr ,args ,convention)) (defun defcfun-helper-forms (name lisp-name rettype args types options) "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 :module ',(let ((lib (getf options :library))) (if (eq lib :default) nil lib)) ;; avoid warning about cdecl not being supported on mac platforms #-mac ,@(list :calling-convention (getf options :convention))) `(,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" (if-let (package (symbol-package name)) (package-name package) "#") (symbol-name name)) '#:cffi-callbacks))) (defmacro %defcallback (name rettype arg-names arg-types body &key convention) (let ((cb-name (intern-callback name))) `(progn (fli:define-foreign-callable (,cb-name :encode :lisp :result-type ,(convert-foreign-type rettype) :calling-convention ,convention :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 path) "Load the foreign library NAME." (fli:register-module (or name path) :connection-style :immediate :real-name path)) (defun %close-foreign-library (name) "Close the foreign library NAME." (fli:disconnect-module name :remove t)) (defun native-namestring (pathname) (namestring pathname)) ;;;# Foreign Globals (defun %foreign-symbol-pointer (name library) "Returns a pointer to a foreign symbol NAME." (values (ignore-errors (fli:make-pointer :symbol-name name :type :void :module (if (eq library :default) nil library)))))
15,917
Common Lisp
.lisp
360
38.452778
80
0.658494
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
7f7b0b3fdb94f105f8d588be422b2f699a470dd197beb7080b33c2112076827f
542
[ 317394, 399169 ]
543
structures.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/src/structures.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; structures.lisp --- Methods for translating foreign structures. ;;; ;;; Copyright (C) 2011, Liam M. Healy <[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) ;;; Definitions for conversion of foreign structures. (defmethod translate-into-foreign-memory ((object list) (type foreign-struct-type) p) (unless (bare-struct-type-p type) (loop for (name value) on object by #'cddr do (setf (foreign-slot-value p (unparse-type type) name) (let ((slot (gethash name (structure-slots type)))) (convert-to-foreign value (slot-type slot))))))) (defun convert-into-foreign-memory (value type ptr) (let ((ptype (parse-type type))) (if (typep ptype 'foreign-built-in-type) value (translate-into-foreign-memory value ptype ptr))) ptr) (defmethod translate-to-foreign (value (type foreign-struct-type)) (let ((ptr (foreign-alloc type))) (translate-into-foreign-memory value type ptr) ptr)) (defmethod translate-from-foreign (p (type foreign-struct-type)) ;; Iterate over slots, make plist (if (bare-struct-type-p type) p (let ((plist (list))) (loop for slot being the hash-value of (structure-slots type) for name = (slot-name slot) do (setf (getf plist name) (foreign-struct-slot-value p slot))) plist))) (defmethod free-translated-object (ptr (type foreign-struct-type) freep) (unless (bare-struct-type-p type) ;; Look for any pointer slots and free them first (loop for slot being the hash-value of (structure-slots type) when (and (listp (slot-type slot)) (eq (first (slot-type slot)) :pointer)) do ;; Free if the pointer is to a specific type, not generic :pointer (free-translated-object (foreign-slot-value ptr type (slot-name slot)) (rest (slot-type slot)) freep)) (foreign-free ptr))) (export 'define-translation-method) (defmacro define-translation-method ((object type method) &body body) "Define a translation method for the foreign structure type; 'method is one of :into, :from, or :to, meaning relation to foreign memory. If :into, the variable 'pointer is the foreign pointer. Note: type must be defined and loaded before this macro is expanded, and just the bare name (without :struct) should be specified." (let ((tclass (class-name (class-of (cffi::parse-type `(:struct ,type)))))) (when (eq tclass 'foreign-struct-type) (error "Won't replace existing translation method for foreign-struct-type")) `(defmethod ,(case method (:into 'translate-into-foreign-memory) (:from 'translate-from-foreign) (:to 'translate-to-foreign)) ;; Arguments to the method (,object (type ,tclass) ,@(when (eq method :into) '(pointer))) ; is intentional variable capture a good idea? ;; The body (declare (ignorable type)) ; I can't think of a reason why you'd want to use this ,@body))) (defmacro translation-forms-for-class (class type-class) "Make forms for translation of foreign structures to and from a standard class. The class slots are assumed to have the same name as the foreign structure." ;; Possible improvement: optional argument to map structure slot names to/from class slot names. `(progn (defmethod translate-from-foreign (pointer (type ,type-class)) ;; Make the instance from the plist (apply 'make-instance ',class (call-next-method))) (defmethod translate-into-foreign-memory ((object ,class) (type ,type-class) pointer) (call-next-method ;; Translate into a plist and call the general method (loop for slot being the hash-value of (structure-slots type) for name = (slot-name slot) append (list slot-name (slot-value object slot-name))) type pointer)))) ;;; For a class already defined and loaded, and a defcstruct already defined, use ;;; (translation-forms-for-class class type-class) ;;; to connnect the two. It would be nice to have a macro to do all three simultaneously. ;;; (defmacro define-foreign-structure (class )) #| (defmacro define-structure-conversion (value-symbol type lisp-class slot-names to-form from-form &optional (struct-name type)) "Define the functions necessary to convert to and from a foreign structure. The to-form sets each of the foreign slots in succession, assume the foreign object exists. The from-form creates the Lisp object, making it with the correct value by reference to foreign slots." `(flet ((map-slots (fn val) (maphash (lambda (name slot-struct) (funcall fn (foreign-slot-value val ',type name) (slot-type slot-struct))) (slots (follow-typedefs (parse-type ',type)))))) ;; Convert this to a separate function so it doesn't have to be recomputed on the fly each time. (defmethod translate-to-foreign ((,value-symbol ,lisp-class) (type ,type)) (let ((p (foreign-alloc ',struct-name))) ;;(map-slots #'translate-to-foreign ,value-symbol) ; recursive translation of slots (with-foreign-slots (,slot-names p ,struct-name) ,to-form) (values p t))) ; second value is passed to FREE-TRANSLATED-OBJECT (defmethod free-translated-object (,value-symbol (p ,type) freep) (when freep ;; Is this redundant? (map-slots #'free-translated-object value) ; recursively free slots (foreign-free ,value-symbol))) (defmethod translate-from-foreign (,value-symbol (type ,type)) (with-foreign-slots (,slot-names ,value-symbol ,struct-name) ,from-form)))) |#
7,014
Common Lisp
.lisp
130
47.023077
328
0.674429
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
103c5c2c21bd83914d50d345a021cec68a5d619b494703ef87fa64a34c52cbac
543
[ -1 ]
544
fsbv.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/fsbv.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; fsbv.lisp --- Tests of foreign structure by value calls. ;;; ;;; Copyright (C) 2011, Liam M. Healy ;;; ;;; 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-tests) ;; Requires struct.lisp (defcfun "sumpair" :int (p (:struct struct-pair))) (defcfun "doublepair" (:struct struct-pair) (p (:struct struct-pair))) (defcfun "prodsumpair" :double (p (:struct struct-pair+double))) (defcfun "doublepairdouble" (:struct struct-pair+double) (p (:struct struct-pair+double))) ;;; Call struct by value (deftest fsbv.1 (sumpair '(1 . 2)) 3) ;;; Call and return struct by value (deftest fsbv.2 (doublepair '(1 . 2)) (2 . 4)) ;;; Call recursive structure by value (deftest fsbv.3 (prodsumpair '(pr (a 4 b 5) dbl 2.5d0)) 22.5d0) ;;; Call and return recursive structure by value (deftest fsbv.4 (let ((ans (doublepairdouble '(pr (a 4 b 5) dbl 2.5d0)))) (values (getf (getf ans 'pr) 'a) (getf (getf ans 'pr) 'b) (getf ans 'dbl))) 8 10 5.0d0) ;;; Typedef fsbv test (defcfun ("sumpair" sumpair2) :int (p struct-pair-typedef1)) (deftest fsbv.5 (sumpair2 '(1 . 2)) 3) ;;; Test ulonglong on no-long-long implementations. (defcfun "ullsum" :unsigned-long-long (a :unsigned-long-long) (b :unsigned-long-long)) (deftest fsbv.6 (ullsum #x10DEADBEEF #x2300000000) #x33DEADBEEF)
2,461
Common Lisp
.lisp
69
33.391304
70
0.709596
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8ed64bebad8bb799c43cb4298508d87d5ef2ab049602f5d2bfbd0f8cd6af6938
544
[ -1 ]
545
package.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/package.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; package.lisp --- CFFI-TESTS package definition. ;;; ;;; 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-tests (:use #:cl #:cffi #:cffi-sys #:regression-test) (:export #:do-tests))
1,403
Common Lisp
.lisp
30
45.566667
70
0.738147
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
522a4cc7bbe9aef4d5686b79ec2a8a5ba453d2b3a110c799b553f66d127a664d
545
[ -1 ]
546
defcfun.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/defcfun.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; defcfun.lisp --- Tests function definition and calling. ;;; ;;; Copyright (C) 2005-2007, 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-tests) (deftest defcfun.parse-name-and-options.1 (multiple-value-bind (lisp-name foreign-name) (let ((*package* (find-package '#:cffi-tests))) (cffi::parse-name-and-options "foo_bar")) (list lisp-name foreign-name)) (foo-bar "foo_bar")) (deftest defcfun.parse-name-and-options.2 (multiple-value-bind (lisp-name foreign-name) (let ((*package* (find-package '#:cffi-tests))) (cffi::parse-name-and-options "foo_bar" t)) (list lisp-name foreign-name)) (*foo-bar* "foo_bar")) (deftest defcfun.parse-name-and-options.3 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options 'foo-bar) (list lisp-name foreign-name)) (foo-bar "foo_bar")) (deftest defcfun.parse-name-and-options.4 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options '*foo-bar* t) (list lisp-name foreign-name)) (*foo-bar* "foo_bar")) (deftest defcfun.parse-name-and-options.5 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options '("foo_bar" foo-baz)) (list lisp-name foreign-name)) (foo-baz "foo_bar")) (deftest defcfun.parse-name-and-options.6 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options '("foo_bar" *foo-baz*) t) (list lisp-name foreign-name)) (*foo-baz* "foo_bar")) (deftest defcfun.parse-name-and-options.7 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options '(foo-baz "foo_bar")) (list lisp-name foreign-name)) (foo-baz "foo_bar")) (deftest defcfun.parse-name-and-options.8 (multiple-value-bind (lisp-name foreign-name) (cffi::parse-name-and-options '(*foo-baz* "foo_bar") t) (list lisp-name foreign-name)) (*foo-baz* "foo_bar")) ;;;# Name translation (deftest translate-underscore-separated-name.to-symbol (let ((*package* (find-package '#:cffi-tests))) (translate-underscore-separated-name "some_name_with_underscores")) some-name-with-underscores) (deftest translate-underscore-separated-name.to-string (translate-underscore-separated-name 'some-name-with-underscores) "some_name_with_underscores") (deftest translate-camelcase-name.to-symbol (let ((*package* (find-package '#:cffi-tests))) (translate-camelcase-name "someXmlFunction")) some-xml-function) (deftest translate-camelcase-name.to-string (translate-camelcase-name 'some-xml-function) "someXmlFunction") (deftest translate-camelcase-name.to-string-upper (translate-camelcase-name 'some-xml-function :upper-initial-p t) "SomeXmlFunction") (deftest translate-camelcase-name.to-symbol-special (let ((*package* (find-package '#:cffi-tests))) (translate-camelcase-name "someXMLFunction" :special-words '("XML"))) some-xml-function) (deftest translate-camelcase-name.to-string-special (translate-camelcase-name 'some-xml-function :special-words '("XML")) "someXMLFunction") (deftest translate-name-from-foreign.function (let ((*package* (find-package '#:cffi-tests))) (translate-name-from-foreign "some_xml_name" *package*)) some-xml-name) (deftest translate-name-from-foreign.var (let ((*package* (find-package '#:cffi-tests))) (translate-name-from-foreign "some_xml_name" *package* t)) *some-xml-name*) (deftest translate-name-to-foreign.function (translate-name-to-foreign 'some-xml-name *package*) "some_xml_name") (deftest translate-name-to-foreign.var (translate-name-to-foreign '*some-xml-name* *package* t) "some_xml_name") ;;;# Calling with built-in c types ;;; ;;; Tests calling standard C library functions both passing ;;; and returning each built-in type. (adapted from funcall.lisp) (defcfun "toupper" :char "toupper docstring" (char :char)) (deftest defcfun.char (toupper (char-code #\a)) #.(char-code #\A)) (deftest defcfun.docstring (documentation 'toupper 'function) "toupper docstring") (defcfun ("abs" c-abs) :int (n :int)) (deftest defcfun.int (c-abs -100) 100) (defcfun "labs" :long (n :long)) (deftest defcfun.long (labs -131072) 131072) #-cffi-features:no-long-long (progn (defcfun "my_llabs" :long-long (n :long-long)) (deftest defcfun.long-long (my-llabs -9223372036854775807) 9223372036854775807) (defcfun "ullong" :unsigned-long-long (n :unsigned-long-long)) #+allegro ; lp#914500 (pushnew 'defcfun.unsigned-long-long rt::*expected-failures*) (deftest defcfun.unsigned-long-long (let ((ullong-max (1- (expt 2 (* 8 (foreign-type-size :unsigned-long-long)))))) (eql ullong-max (ullong ullong-max))) t)) (defcfun "my_sqrtf" :float (n :float)) (deftest defcfun.float (my-sqrtf 16.0) 4.0) (defcfun ("sqrt" c-sqrt) :double (n :double)) (deftest defcfun.double (c-sqrt 36.0d0) 6.0d0) #+(and scl long-float) (defcfun ("sqrtl" c-sqrtl) :long-double (n :long-double)) #+(and scl long-float) (deftest defcfun.long-double (c-sqrtl 36.0l0) 6.0l0) (defcfun "strlen" :int (n :string)) (deftest defcfun.string.1 (strlen "Hello") 5) (defcfun "strcpy" (:pointer :char) (dest (:pointer :char)) (src :string)) (defcfun "strcat" (:pointer :char) (dest (:pointer :char)) (src :string)) (deftest defcfun.string.2 (with-foreign-pointer-as-string (s 100) (setf (mem-ref s :char) 0) (strcpy s "Hello") (strcat s ", world!")) "Hello, world!") (defcfun "strerror" :string (n :int)) (deftest defcfun.string.3 (typep (strerror 1) 'string) t) ;;; Regression test. Allegro would warn on direct calls to ;;; functions with no arguments. ;;; ;;; Also, let's check if void functions will return NIL. ;;; ;;; Check if a docstring without arguments doesn't cause problems. (defcfun "noargs" :int "docstring") (deftest defcfun.noargs (noargs) 42) (defcfun "noop" :void) #+(or allegro openmcl ecl) (pushnew 'defcfun.noop rt::*expected-failures*) (deftest defcfun.noop (noop) #|no values|#) ;;;# Calling varargs functions (defcfun "sprintf" :int "sprintf docstring" (str (:pointer :char)) (control :string) &rest) ;;; CLISP and ABCL discard macro docstrings. #+(or clisp abcl) (pushnew 'defcfun.varargs.docstrings rt::*expected-failures*) (deftest defcfun.varargs.docstrings (documentation 'sprintf 'function) "sprintf docstring") (deftest defcfun.varargs.char (with-foreign-pointer-as-string (s 100) (sprintf s "%c" :char 65)) "A") (deftest defcfun.varargs.short (with-foreign-pointer-as-string (s 100) (sprintf s "%d" :short 42)) "42") (deftest defcfun.varargs.int (with-foreign-pointer-as-string (s 100) (sprintf s "%d" :int 1000)) "1000") (deftest defcfun.varargs.long (with-foreign-pointer-as-string (s 100) (sprintf s "%ld" :long 131072)) "131072") (deftest defcfun.varargs.float (with-foreign-pointer-as-string (s 100) (sprintf s "%.2f" :float (float pi))) "3.14") (deftest defcfun.varargs.double (with-foreign-pointer-as-string (s 100) (sprintf s "%.2f" :double (float pi 1.0d0))) "3.14") #+(and scl long-float) (deftest defcfun.varargs.long-double (with-foreign-pointer-as-string (s 100) (setf (mem-ref s :char) 0) (sprintf s "%.2Lf" :long-double pi)) "3.14") (deftest defcfun.varargs.string (with-foreign-pointer-as-string (s 100) (sprintf s "%s, %s!" :string "Hello" :string "world")) "Hello, world!") ;;; (let ((rettype (find-type :long)) ;;; (arg-types (n-random-types-no-ll 127))) ;;; (c-function rettype arg-types) ;;; (gen-function-test rettype arg-types)) #+(and (not ecl) #.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:and) '(:or))) (progn (defcfun "sum_127_no_ll" :long (a1 :long) (a2 :unsigned-long) (a3 :short) (a4 :unsigned-short) (a5 :float) (a6 :double) (a7 :unsigned-long) (a8 :float) (a9 :unsigned-char) (a10 :unsigned-short) (a11 :short) (a12 :unsigned-long) (a13 :double) (a14 :long) (a15 :unsigned-int) (a16 :pointer) (a17 :unsigned-int) (a18 :unsigned-short) (a19 :long) (a20 :float) (a21 :pointer) (a22 :float) (a23 :int) (a24 :int) (a25 :unsigned-short) (a26 :long) (a27 :long) (a28 :double) (a29 :unsigned-char) (a30 :unsigned-int) (a31 :unsigned-int) (a32 :int) (a33 :unsigned-short) (a34 :unsigned-int) (a35 :pointer) (a36 :double) (a37 :double) (a38 :long) (a39 :short) (a40 :unsigned-short) (a41 :long) (a42 :char) (a43 :long) (a44 :unsigned-short) (a45 :pointer) (a46 :int) (a47 :unsigned-int) (a48 :double) (a49 :unsigned-char) (a50 :unsigned-char) (a51 :float) (a52 :int) (a53 :unsigned-short) (a54 :double) (a55 :short) (a56 :unsigned-char) (a57 :unsigned-long) (a58 :float) (a59 :float) (a60 :float) (a61 :pointer) (a62 :pointer) (a63 :unsigned-int) (a64 :unsigned-long) (a65 :char) (a66 :short) (a67 :unsigned-short) (a68 :unsigned-long) (a69 :pointer) (a70 :float) (a71 :double) (a72 :long) (a73 :unsigned-long) (a74 :short) (a75 :unsigned-int) (a76 :unsigned-short) (a77 :int) (a78 :unsigned-short) (a79 :char) (a80 :double) (a81 :short) (a82 :unsigned-char) (a83 :float) (a84 :char) (a85 :int) (a86 :double) (a87 :unsigned-char) (a88 :int) (a89 :unsigned-long) (a90 :double) (a91 :short) (a92 :short) (a93 :unsigned-int) (a94 :unsigned-char) (a95 :float) (a96 :long) (a97 :float) (a98 :long) (a99 :long) (a100 :int) (a101 :int) (a102 :unsigned-int) (a103 :char) (a104 :char) (a105 :unsigned-short) (a106 :unsigned-int) (a107 :unsigned-short) (a108 :unsigned-short) (a109 :int) (a110 :long) (a111 :char) (a112 :double) (a113 :unsigned-int) (a114 :char) (a115 :short) (a116 :unsigned-long) (a117 :unsigned-int) (a118 :short) (a119 :unsigned-char) (a120 :float) (a121 :pointer) (a122 :double) (a123 :int) (a124 :long) (a125 :char) (a126 :unsigned-short) (a127 :float)) (deftest defcfun.bff.1 (sum-127-no-ll 1442906394 520035521 -4715 50335 -13557.0 -30892.0d0 24061483 -23737.0 22 2348 4986 104895680 8073.0d0 -571698147 102484400 (make-pointer 507907275) 12733353 7824 -1275845284 13602.0 (make-pointer 286958390) -8042.0 -773681663 -1289932452 31199 -154985357 -170994216 16845.0d0 177 218969221 2794350893 6068863 26327 127699339 (make-pointer 184352771) 18512.0d0 -12345.0d0 -179853040 -19981 37268 -792845398 116 -1084653028 50494 (make-pointer 2105239646) -1710519651 1557813312 2839.0d0 90 180 30580.0 -532698978 8623 9537.0d0 -10882 54 184357206 14929.0 -8190.0 -25615.0 (make-pointer 235310526) (make-pointer 220476977) 7476055 1576685 -117 -11781 31479 23282640 (make-pointer 8627281) -17834.0 10391.0d0 -1904504370 114393659 -17062 637873619 16078 -891210259 8107 0 760.0d0 -21268 104 14133.0 10 588598141 310.0d0 20 1351785456 16159552 -10121.0d0 -25866 24821 68232851 60 -24132.0 -1660411658 13387.0 -786516668 -499825680 -1128144619 111849719 2746091587 -2 95 14488 326328135 64781 18204 150716680 -703859275 103 16809.0d0 852235610 -43 21088 242356110 324325428 -22380 23 24814.0 (make-pointer 40362014) -14322.0d0 -1864262539 523684371 -21 49995 -29175.0) 796447501)) ;;; (let ((rettype (find-type :long-long)) ;;; (arg-types (n-random-types 127))) ;;; (c-function rettype arg-types) ;;; (gen-function-test rettype arg-types)) #-(or ecl cffi-sys::no-long-long #.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:or) '(:and))) (progn (defcfun "sum_127" :long-long (a1 :pointer) (a2 :pointer) (a3 :float) (a4 :unsigned-long) (a5 :pointer) (a6 :long-long) (a7 :double) (a8 :double) (a9 :unsigned-short) (a10 :int) (a11 :long-long) (a12 :long) (a13 :short) (a14 :unsigned-int) (a15 :long) (a16 :unsigned-char) (a17 :int) (a18 :double) (a19 :short) (a20 :short) (a21 :long-long) (a22 :unsigned-int) (a23 :unsigned-short) (a24 :short) (a25 :pointer) (a26 :short) (a27 :unsigned-short) (a28 :unsigned-short) (a29 :int) (a30 :long-long) (a31 :pointer) (a32 :int) (a33 :unsigned-long) (a34 :unsigned-long) (a35 :pointer) (a36 :unsigned-long-long) (a37 :float) (a38 :int) (a39 :short) (a40 :pointer) (a41 :unsigned-long-long) (a42 :long-long) (a43 :unsigned-long) (a44 :unsigned-long) (a45 :unsigned-long-long) (a46 :unsigned-long) (a47 :char) (a48 :double) (a49 :long) (a50 :unsigned-int) (a51 :int) (a52 :short) (a53 :pointer) (a54 :long) (a55 :unsigned-long-long) (a56 :int) (a57 :unsigned-short) (a58 :unsigned-long-long) (a59 :float) (a60 :pointer) (a61 :float) (a62 :unsigned-short) (a63 :unsigned-long) (a64 :float) (a65 :unsigned-int) (a66 :unsigned-long-long) (a67 :pointer) (a68 :double) (a69 :unsigned-long-long) (a70 :double) (a71 :double) (a72 :long-long) (a73 :pointer) (a74 :unsigned-short) (a75 :long) (a76 :pointer) (a77 :short) (a78 :double) (a79 :long) (a80 :unsigned-char) (a81 :pointer) (a82 :unsigned-char) (a83 :long) (a84 :double) (a85 :pointer) (a86 :int) (a87 :double) (a88 :unsigned-char) (a89 :double) (a90 :short) (a91 :long) (a92 :int) (a93 :long) (a94 :double) (a95 :unsigned-short) (a96 :unsigned-int) (a97 :int) (a98 :char) (a99 :long-long) (a100 :double) (a101 :float) (a102 :unsigned-long) (a103 :short) (a104 :pointer) (a105 :float) (a106 :long-long) (a107 :int) (a108 :long-long) (a109 :long-long) (a110 :double) (a111 :unsigned-long-long) (a112 :double) (a113 :unsigned-long) (a114 :char) (a115 :char) (a116 :unsigned-long) (a117 :short) (a118 :unsigned-char) (a119 :unsigned-char) (a120 :int) (a121 :int) (a122 :float) (a123 :unsigned-char) (a124 :unsigned-char) (a125 :double) (a126 :unsigned-long-long) (a127 :char)) (deftest defcfun.bff.2 (sum-127 (make-pointer 2746181372) (make-pointer 177623060) -32334.0 3158055028 (make-pointer 242315091) 4288001754991016425 -21047.0d0 287.0d0 18722 243379286 -8677366518541007140 581399424 -13872 4240394881 1353358999 226 969197676 -26207.0d0 6484 11150 1241680089902988480 106068320 61865 2253 (make-pointer 866809333) -31613 35616 11715 1393601698 8940888681199591845 (make-pointer 1524606024) 805638893 3315410736 3432596795 (make-pointer 1490355706) 696175657106383698 -25438.0 1294381547 26724 (make-pointer 3196569545) 2506913373410783697 -4405955718732597856 4075932032 3224670123 2183829215657835866 1318320964 -22 -3786.0d0 -2017024146 1579225515 -626617701 -1456 (make-pointer 3561444187) 395687791 1968033632506257320 -1847773261 48853 142937735275669133 -17974.0 (make-pointer 2791749948) -14140.0 2707 3691328585 3306.0 1132012981 303633191773289330 (make-pointer 981183954) 9114.0d0 8664374572369470 -19013.0d0 -10288.0d0 -3679345119891954339 (make-pointer 3538786709) 23761 -154264605 (make-pointer 2694396308) 7023 997.0d0 1009561368 241 (make-pointer 2612292671) 48 1431872408 -32675.0d0 (make-pointer 1587599336) 958916472 -9857.0d0 111 -14370.0d0 -7308 -967514912 488790941 2146978095 -24111.0d0 13711 86681861 717987770 111 1013402998690933877 17234.0d0 -8772.0 3959216275 -8711 (make-pointer 3142780851) 9480.0 -3820453146461186120 1616574376 -3336232268263990050 -1906114671562979758 -27925.0d0 9695970875869913114 27033.0d0 1096518219 -12 104 3392025403 -27911 60 89 509297051 -533066551 29158.0 110 54 -9802.0d0 593950442165910888 -79) 7758614658402721936)) ;;; regression test: defining an undefined foreign function should only ;;; throw some sort of warning, not signal an error. #+(or cmu (and sbcl (or (not linkage-table) win32))) (pushnew 'defcfun.undefined rt::*expected-failures*) (deftest defcfun.undefined (progn (eval '(defcfun ("undefined_foreign_function" undefined-foreign-function) :void)) (compile 'undefined-foreign-function) t) t) ;;; Test whether all doubles are passed correctly. On some platforms, eg. ;;; darwin/ppc, some are passed on registers others on the stack. (defcfun "sum_double26" :double (a1 :double) (a2 :double) (a3 :double) (a4 :double) (a5 :double) (a6 :double) (a7 :double) (a8 :double) (a9 :double) (a10 :double) (a11 :double) (a12 :double) (a13 :double) (a14 :double) (a15 :double) (a16 :double) (a17 :double) (a18 :double) (a19 :double) (a20 :double) (a21 :double) (a22 :double) (a23 :double) (a24 :double) (a25 :double) (a26 :double)) (deftest defcfun.double26 (sum-double26 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0 3.14d0) 81.64d0) ;;; Same as above for floats. (defcfun "sum_float26" :float (a1 :float) (a2 :float) (a3 :float) (a4 :float) (a5 :float) (a6 :float) (a7 :float) (a8 :float) (a9 :float) (a10 :float) (a11 :float) (a12 :float) (a13 :float) (a14 :float) (a15 :float) (a16 :float) (a17 :float) (a18 :float) (a19 :float) (a20 :float) (a21 :float) (a22 :float) (a23 :float) (a24 :float) (a25 :float) (a26 :float)) (deftest defcfun.float26 (sum-float26 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0) 130.0) ;;;# Namespaces #-cffi-sys::flat-namespace (progn (defcfun ("ns_function" ns-fun1 :library libtest) :boolean) (defcfun ("ns_function" ns-fun2 :library libtest2) :boolean) (deftest defcfun.namespace.1 (values (ns-fun1) (ns-fun2)) t nil)) ;;;# stdcall #+(and x86 windows (not cffi-sys::no-stdcall)) (progn (defcfun ("stdcall_fun@12" stdcall-fun :convention :stdcall) :int (a :int) (b :int) (c :int)) (deftest defcfun.stdcall.1 (loop repeat 100 do (stdcall-fun 1 2 3) finally (return (stdcall-fun 1 2 3))) 6))
19,291
Common Lisp
.lisp
427
40.873536
87
0.683554
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
410b3262ad5d3b534a76ec176fe7172b3b4ef7327d98122afe12ebc03fec680a
546
[ -1 ]
547
callbacks.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/callbacks.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; callbacks.lisp --- Tests on callbacks. ;;; ;;; 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-tests) (defcfun "expect_char_sum" :int (f :pointer)) (defcfun "expect_unsigned_char_sum" :int (f :pointer)) (defcfun "expect_short_sum" :int (f :pointer)) (defcfun "expect_unsigned_short_sum" :int (f :pointer)) (defcfun "expect_int_sum" :int (f :pointer)) (defcfun "expect_unsigned_int_sum" :int (f :pointer)) (defcfun "expect_long_sum" :int (f :pointer)) (defcfun "expect_unsigned_long_sum" :int (f :pointer)) (defcfun "expect_float_sum" :int (f :pointer)) (defcfun "expect_double_sum" :int (f :pointer)) (defcfun "expect_pointer_sum" :int (f :pointer)) (defcfun "expect_strcat" :int (f :pointer)) #-cffi-sys::no-long-long (progn (defcfun "expect_long_long_sum" :int (f :pointer)) (defcfun "expect_unsigned_long_long_sum" :int (f :pointer))) #+(and scl long-float) (defcfun "expect_long_double_sum" :int (f :pointer)) (defcallback sum-char :char ((a :char) (b :char)) "Test if the named block is present and the docstring too." ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (return-from sum-char (+ a b))) (defcallback sum-unsigned-char :unsigned-char ((a :unsigned-char) (b :unsigned-char)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) (defcallback sum-short :short ((a :short) (b :short)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) (defcallback sum-unsigned-short :unsigned-short ((a :unsigned-short) (b :unsigned-short)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) (defcallback sum-int :int ((a :int) (b :int)) (+ a b)) (defcallback sum-unsigned-int :unsigned-int ((a :unsigned-int) (b :unsigned-int)) (+ a b)) (defcallback sum-long :long ((a :long) (b :long)) (+ a b)) (defcallback sum-unsigned-long :unsigned-long ((a :unsigned-long) (b :unsigned-long)) (+ a b)) #-cffi-sys::no-long-long (progn (defcallback sum-long-long :long-long ((a :long-long) (b :long-long)) (+ a b)) (defcallback sum-unsigned-long-long :unsigned-long-long ((a :unsigned-long-long) (b :unsigned-long-long)) (+ a b))) (defcallback sum-float :float ((a :float) (b :float)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) (defcallback sum-double :double ((a :double) (b :double)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) #+(and scl long-float) (defcallback sum-long-double :long-double ((a :long-double) (b :long-double)) ;(format t "~%}}} a: ~A, b: ~A {{{~%" a b) (+ a b)) (defcallback sum-pointer :pointer ((ptr :pointer) (offset :int)) (inc-pointer ptr offset)) (defcallback lisp-strcat :string ((a :string) (b :string)) (concatenate 'string a b)) (deftest callbacks.char (expect-char-sum (get-callback 'sum-char)) 1) (deftest callbacks.unsigned-char (expect-unsigned-char-sum (get-callback 'sum-unsigned-char)) 1) (deftest callbacks.short (expect-short-sum (callback sum-short)) 1) (deftest callbacks.unsigned-short (expect-unsigned-short-sum (callback sum-unsigned-short)) 1) (deftest callbacks.int (expect-int-sum (callback sum-int)) 1) (deftest callbacks.unsigned-int (expect-unsigned-int-sum (callback sum-unsigned-int)) 1) (deftest callbacks.long (expect-long-sum (callback sum-long)) 1) (deftest callbacks.unsigned-long (expect-unsigned-long-sum (callback sum-unsigned-long)) 1) #-cffi-sys::no-long-long (progn #+openmcl (push 'callbacks.long-long rt::*expected-failures*) (deftest callbacks.long-long (expect-long-long-sum (callback sum-long-long)) 1) (deftest callbacks.unsigned-long-long (expect-unsigned-long-long-sum (callback sum-unsigned-long-long)) 1)) (deftest callbacks.float (expect-float-sum (callback sum-float)) 1) (deftest callbacks.double (expect-double-sum (callback sum-double)) 1) #+(and scl long-float) (deftest callbacks.long-double (expect-long-double-sum (callback sum-long-double)) 1) (deftest callbacks.pointer (expect-pointer-sum (callback sum-pointer)) 1) (deftest callbacks.string (expect-strcat (callback lisp-strcat)) 1) #-cffi-sys::no-foreign-funcall (defcallback return-a-string-not-nil :string () "abc") #-cffi-sys::no-foreign-funcall (deftest callbacks.string-not-docstring (foreign-funcall-pointer (callback return-a-string-not-nil) () :string) "abc") (defcallback check-for-nil :boolean ((pointer :pointer)) (null pointer)) #-cffi-sys::no-foreign-funcall (deftest callbacks.nil-for-null (foreign-funcall-pointer (callback check-for-nil) nil :pointer (null-pointer) :boolean) nil) ;;; This one tests mem-aref too. (defcfun "qsort" :void (base :pointer) (nmemb :int) (size :int) (fun-compar :pointer)) (defcallback < :int ((a :pointer) (b :pointer)) (let ((x (mem-ref a :int)) (y (mem-ref b :int))) (cond ((> x y) 1) ((< x y) -1) (t 0)))) (deftest callbacks.qsort (with-foreign-object (array :int 10) ;; Initialize array. (loop for i from 0 and n in '(7 2 10 4 3 5 1 6 9 8) do (setf (mem-aref array :int i) n)) ;; Sort it. (qsort array 10 (foreign-type-size :int) (callback <)) ;; Return it as a list. (loop for i from 0 below 10 collect (mem-aref array :int i))) (1 2 3 4 5 6 7 8 9 10)) ;;; void callback (defparameter *int* -1) (defcfun "pass_int_ref" :void (f :pointer)) ;;; CMUCL chokes on this one for some reason. #-(and darwin cmu) (defcallback read-int-from-pointer :void ((a :pointer)) (setq *int* (mem-ref a :int))) #+(and darwin cmu) (pushnew 'callbacks.void rt::*expected-failures*) (deftest callbacks.void (progn (pass-int-ref (callback read-int-from-pointer)) *int*) 1984) ;;; test funcalling of a callback and also declarations inside ;;; callbacks. #-cffi-sys::no-foreign-funcall (progn (defcallback sum-2 :int ((a :int) (b :int) (c :int)) (declare (ignore c)) (+ a b)) (deftest callbacks.funcall.1 (foreign-funcall-pointer (callback sum-2) () :int 2 :int 3 :int 1 :int) 5) (defctype foo-float :float) (defcallback sum-2f foo-float ((a foo-float) (b foo-float) (c foo-float) (d foo-float) (e foo-float)) "This one ignores the middle 3 arguments." (declare (ignore b c)) (declare (ignore d)) (+ a e)) (deftest callbacks.funcall.2 (foreign-funcall-pointer (callback sum-2f) () foo-float 1.0 foo-float 2.0 foo-float 3.0 foo-float 4.0 foo-float 5.0 foo-float) 6.0)) ;;; (cb-test :no-long-long t) (defcfun "call_sum_127_no_ll" :long (cb :pointer)) ;;; CMUCL, ECL and CCL choke on this one. #-(or ecl cmu clozure #.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:or) '(:and))) (defcallback sum-127-no-ll :long ((a1 :unsigned-long) (a2 :pointer) (a3 :long) (a4 :double) (a5 :unsigned-long) (a6 :float) (a7 :float) (a8 :int) (a9 :unsigned-int) (a10 :double) (a11 :double) (a12 :double) (a13 :pointer) (a14 :unsigned-short) (a15 :unsigned-short) (a16 :pointer) (a17 :long) (a18 :long) (a19 :int) (a20 :short) (a21 :unsigned-short) (a22 :unsigned-short) (a23 :char) (a24 :long) (a25 :pointer) (a26 :pointer) (a27 :char) (a28 :unsigned-char) (a29 :unsigned-long) (a30 :short) (a31 :int) (a32 :int) (a33 :unsigned-char) (a34 :short) (a35 :long) (a36 :long) (a37 :pointer) (a38 :unsigned-short) (a39 :char) (a40 :double) (a41 :unsigned-short) (a42 :pointer) (a43 :short) (a44 :unsigned-long) (a45 :unsigned-short) (a46 :float) (a47 :unsigned-char) (a48 :short) (a49 :float) (a50 :short) (a51 :char) (a52 :unsigned-long) (a53 :unsigned-long) (a54 :char) (a55 :float) (a56 :long) (a57 :pointer) (a58 :short) (a59 :float) (a60 :unsigned-int) (a61 :float) (a62 :unsigned-int) (a63 :double) (a64 :unsigned-int) (a65 :unsigned-char) (a66 :int) (a67 :long) (a68 :char) (a69 :short) (a70 :double) (a71 :int) (a72 :pointer) (a73 :char) (a74 :unsigned-short) (a75 :pointer) (a76 :unsigned-short) (a77 :pointer) (a78 :unsigned-long) (a79 :double) (a80 :pointer) (a81 :long) (a82 :float) (a83 :unsigned-short) (a84 :unsigned-short) (a85 :pointer) (a86 :float) (a87 :int) (a88 :unsigned-int) (a89 :double) (a90 :float) (a91 :long) (a92 :pointer) (a93 :unsigned-short) (a94 :float) (a95 :unsigned-char) (a96 :unsigned-char) (a97 :float) (a98 :unsigned-int) (a99 :float) (a100 :unsigned-short) (a101 :double) (a102 :unsigned-short) (a103 :unsigned-long) (a104 :unsigned-int) (a105 :unsigned-long) (a106 :pointer) (a107 :unsigned-char) (a108 :char) (a109 :char) (a110 :unsigned-short) (a111 :unsigned-long) (a112 :float) (a113 :short) (a114 :pointer) (a115 :long) (a116 :unsigned-short) (a117 :short) (a118 :double) (a119 :short) (a120 :int) (a121 :char) (a122 :unsigned-long) (a123 :long) (a124 :int) (a125 :pointer) (a126 :double) (a127 :unsigned-char)) (let ((args (list a1 (pointer-address a2) a3 (floor a4) a5 (floor a6) (floor a7) a8 a9 (floor a10) (floor a11) (floor a12) (pointer-address a13) a14 a15 (pointer-address a16) a17 a18 a19 a20 a21 a22 a23 a24 (pointer-address a25) (pointer-address a26) a27 a28 a29 a30 a31 a32 a33 a34 a35 a36 (pointer-address a37) a38 a39 (floor a40) a41 (pointer-address a42) a43 a44 a45 (floor a46) a47 a48 (floor a49) a50 a51 a52 a53 a54 (floor a55) a56 (pointer-address a57) a58 (floor a59) a60 (floor a61) a62 (floor a63) a64 a65 a66 a67 a68 a69 (floor a70) a71 (pointer-address a72) a73 a74 (pointer-address a75) a76 (pointer-address a77) a78 (floor a79) (pointer-address a80) a81 (floor a82) a83 a84 (pointer-address a85) (floor a86) a87 a88 (floor a89) (floor a90) a91 (pointer-address a92) a93 (floor a94) a95 a96 (floor a97) a98 (floor a99) a100 (floor a101) a102 a103 a104 a105 (pointer-address a106) a107 a108 a109 a110 a111 (floor a112) a113 (pointer-address a114) a115 a116 a117 (floor a118) a119 a120 a121 a122 a123 a124 (pointer-address a125) (floor a126) a127))) #-(and) (loop for i from 1 and arg in args do (format t "a~A: ~A~%" i arg)) (reduce #'+ args))) #+(or openmcl cmu ecl (and darwin (or allegro lispworks))) (push 'callbacks.bff.1 regression-test::*expected-failures*) #+#.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(:and) '(:or)) (deftest callbacks.bff.1 (call-sum-127-no-ll (callback sum-127-no-ll)) 2008547941) ;;; (cb-test) #-(or cffi-sys::no-long-long #.(cl:if (cl:>= cl:lambda-parameters-limit 127) '(or) '(and))) (progn (defcfun "call_sum_127" :long-long (cb :pointer)) ;;; CMUCL, ECL and CCL choke on this one. #-(or cmu ecl clozure) (defcallback sum-127 :long-long ((a1 :short) (a2 :char) (a3 :pointer) (a4 :float) (a5 :long) (a6 :double) (a7 :unsigned-long-long) (a8 :unsigned-short) (a9 :unsigned-char) (a10 :char) (a11 :char) (a12 :unsigned-short) (a13 :unsigned-long-long) (a14 :unsigned-short) (a15 :long-long) (a16 :unsigned-short) (a17 :unsigned-long-long) (a18 :unsigned-char) (a19 :unsigned-char) (a20 :unsigned-long-long) (a21 :long-long) (a22 :char) (a23 :float) (a24 :unsigned-int) (a25 :float) (a26 :float) (a27 :unsigned-int) (a28 :float) (a29 :char) (a30 :unsigned-char) (a31 :long) (a32 :long-long) (a33 :unsigned-char) (a34 :double) (a35 :long) (a36 :double) (a37 :unsigned-int) (a38 :unsigned-short) (a39 :long-long) (a40 :unsigned-int) (a41 :int) (a42 :unsigned-long-long) (a43 :long) (a44 :short) (a45 :unsigned-int) (a46 :unsigned-int) (a47 :unsigned-long-long) (a48 :unsigned-int) (a49 :long) (a50 :pointer) (a51 :unsigned-char) (a52 :char) (a53 :long-long) (a54 :unsigned-short) (a55 :unsigned-int) (a56 :float) (a57 :unsigned-char) (a58 :unsigned-long) (a59 :long-long) (a60 :float) (a61 :long) (a62 :float) (a63 :int) (a64 :float) (a65 :unsigned-short) (a66 :unsigned-long-long) (a67 :short) (a68 :unsigned-long) (a69 :long) (a70 :char) (a71 :unsigned-short) (a72 :long-long) (a73 :short) (a74 :double) (a75 :pointer) (a76 :unsigned-int) (a77 :char) (a78 :unsigned-int) (a79 :pointer) (a80 :pointer) (a81 :unsigned-char) (a82 :pointer) (a83 :unsigned-short) (a84 :unsigned-char) (a85 :long) (a86 :pointer) (a87 :char) (a88 :long) (a89 :unsigned-short) (a90 :unsigned-char) (a91 :double) (a92 :unsigned-long-long) (a93 :unsigned-short) (a94 :unsigned-short) (a95 :unsigned-int) (a96 :long) (a97 :char) (a98 :long) (a99 :char) (a100 :short) (a101 :unsigned-short) (a102 :unsigned-long) (a103 :unsigned-long) (a104 :short) (a105 :long-long) (a106 :long-long) (a107 :long-long) (a108 :double) (a109 :unsigned-short) (a110 :unsigned-char) (a111 :short) (a112 :unsigned-char) (a113 :long) (a114 :long-long) (a115 :unsigned-long-long) (a116 :unsigned-int) (a117 :unsigned-long) (a118 :unsigned-char) (a119 :long-long) (a120 :unsigned-char) (a121 :unsigned-long-long) (a122 :double) (a123 :unsigned-char) (a124 :long-long) (a125 :unsigned-char) (a126 :char) (a127 :long-long)) (+ a1 a2 (pointer-address a3) (values (floor a4)) a5 (values (floor a6)) a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22 (values (floor a23)) a24 (values (floor a25)) (values (floor a26)) a27 (values (floor a28)) a29 a30 a31 a32 a33 (values (floor a34)) a35 (values (floor a36)) a37 a38 a39 a40 a41 a42 a43 a44 a45 a46 a47 a48 a49 (pointer-address a50) a51 a52 a53 a54 a55 (values (floor a56)) a57 a58 a59 (values (floor a60)) a61 (values (floor a62)) a63 (values (floor a64)) a65 a66 a67 a68 a69 a70 a71 a72 a73 (values (floor a74)) (pointer-address a75) a76 a77 a78 (pointer-address a79) (pointer-address a80) a81 (pointer-address a82) a83 a84 a85 (pointer-address a86) a87 a88 a89 a90 (values (floor a91)) a92 a93 a94 a95 a96 a97 a98 a99 a100 a101 a102 a103 a104 a105 a106 a107 (values (floor a108)) a109 a110 a111 a112 a113 a114 a115 a116 a117 a118 a119 a120 a121 (values (floor a122)) a123 a124 a125 a126 a127)) #+(or openmcl cmu ecl) (push 'callbacks.bff.2 rt::*expected-failures*) (deftest callbacks.bff.2 (call-sum-127 (callback sum-127)) 8166570665645582011)) ;;; regression test: (callback non-existant-callback) should throw an error (deftest callbacks.non-existant (not (null (nth-value 1 (ignore-errors (callback doesnt-exist))))) t) ;;; Handling many arguments of type double. Many lisps (used to) fail ;;; this one on darwin/ppc. This test might be bogus due to floating ;;; point arithmetic rounding errors. ;;; ;;; CMUCL chokes on this one. #-(and darwin cmu) (defcallback double26 :double ((a1 :double) (a2 :double) (a3 :double) (a4 :double) (a5 :double) (a6 :double) (a7 :double) (a8 :double) (a9 :double) (a10 :double) (a11 :double) (a12 :double) (a13 :double) (a14 :double) (a15 :double) (a16 :double) (a17 :double) (a18 :double) (a19 :double) (a20 :double) (a21 :double) (a22 :double) (a23 :double) (a24 :double) (a25 :double) (a26 :double)) (let ((args (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26))) #-(and) (loop for i from 1 and arg in args do (format t "a~A: ~A~%" i arg)) (reduce #'+ args))) (defcfun "call_double26" :double (f :pointer)) #+(and darwin (or allegro cmu)) (pushnew 'callbacks.double26 rt::*expected-failures*) (deftest callbacks.double26 (call-double26 (callback double26)) 81.64d0) #+(and darwin cmu) (pushnew 'callbacks.double26.funcall rt::*expected-failures*) #-cffi-sys::no-foreign-funcall (deftest callbacks.double26.funcall (foreign-funcall-pointer (callback double26) () :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double 3.14d0 :double) 81.64d0) ;;; Same as above, for floats. #-(and darwin cmu) (defcallback float26 :float ((a1 :float) (a2 :float) (a3 :float) (a4 :float) (a5 :float) (a6 :float) (a7 :float) (a8 :float) (a9 :float) (a10 :float) (a11 :float) (a12 :float) (a13 :float) (a14 :float) (a15 :float) (a16 :float) (a17 :float) (a18 :float) (a19 :float) (a20 :float) (a21 :float) (a22 :float) (a23 :float) (a24 :float) (a25 :float) (a26 :float)) (let ((args (list a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12 a13 a14 a15 a16 a17 a18 a19 a20 a21 a22 a23 a24 a25 a26))) #-(and) (loop for i from 1 and arg in args do (format t "a~A: ~A~%" i arg)) (reduce #'+ args))) (defcfun "call_float26" :float (f :pointer)) #+(and darwin (or lispworks openmcl cmu)) (pushnew 'callbacks.float26 regression-test::*expected-failures*) (deftest callbacks.float26 (call-float26 (callback float26)) 130.0) #+(and darwin (or lispworks openmcl cmu)) (pushnew 'callbacks.float26.funcall regression-test::*expected-failures*) #-cffi-sys::no-foreign-funcall (deftest callbacks.float26.funcall (foreign-funcall-pointer (callback float26) () :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float 5.0 :float) 130.0) ;;; Defining a callback as a non-toplevel form. Not portable. Doesn't ;;; work for CMUCL or Allegro. #-(and) (let ((n 42)) (defcallback non-toplevel-cb :int () n)) #-(and) (deftest callbacks.non-toplevel (foreign-funcall (callback non-toplevel-cb) :int) 42) ;;;# Stdcall #+(and x86 (not cffi-sys::no-stdcall)) (progn (defcallback (stdcall-cb :convention :stdcall) :int ((a :int) (b :int) (c :int)) (+ a b c)) (defcfun "call_stdcall_fun" :int (f :pointer)) (deftest callbacks.stdcall.1 (call-stdcall-fun (callback stdcall-cb)) 42)) ;;; RT: many of the %DEFCALLBACK implementations wouldn't handle ;;; uninterned symbols. (deftest callbacks.uninterned (values (defcallback #1=#:foo :void ()) (pointerp (callback #1#))) #1# t)
20,295
Common Lisp
.lisp
445
40.582022
81
0.641726
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
46f353d2abdbd66d95bc1166451044d0296561a88d74c0445ea012a4510a9344
547
[ 263650 ]
548
foreign-globals.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/foreign-globals.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; foreign-globals.lisp --- Tests on foreign globals. ;;; ;;; Copyright (C) 2005-2007, 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-tests) (defcvar ("var_char" *char-var*) :char) (defcvar "var_unsigned_char" :unsigned-char) (defcvar "var_short" :short) (defcvar "var_unsigned_short" :unsigned-short) (defcvar "var_int" :int) (defcvar "var_unsigned_int" :unsigned-int) (defcvar "var_long" :long) (defcvar "var_unsigned_long" :unsigned-long) (defcvar "var_float" :float) (defcvar "var_double" :double) (defcvar "var_pointer" :pointer) (defcvar "var_string" :string) (defcvar "var_long_long" :long-long) (defcvar "var_unsigned_long_long" :unsigned-long-long) ;;; The expected failures marked below result from this odd behaviour: ;;; ;;; (foreign-symbol-pointer "var_char") => NIL ;;; ;;; (foreign-symbol-pointer "var_char" :library 'libtest) ;;; => #<Pointer to type :VOID = #xF7F50740> ;;; ;;; Why is this happening? --luis #+lispworks (mapc (lambda (x) (pushnew x rtest::*expected-failures*)) '(foreign-globals.ref.char foreign-globals.get-var-pointer.1 foreign-globals.get-var-pointer.2 foreign-globals.symbol-name foreign-globals.read-only.1 )) (deftest foreign-globals.ref.char *char-var* -127) (deftest foreign-globals.ref.unsigned-char *var-unsigned-char* 255) (deftest foreign-globals.ref.short *var-short* -32767) (deftest foreign-globals.ref.unsigned-short *var-unsigned-short* 65535) (deftest foreign-globals.ref.int *var-int* -32767) (deftest foreign-globals.ref.unsigned-int *var-unsigned-int* 65535) (deftest foreign-globals.ref.long *var-long* -2147483647) (deftest foreign-globals.ref.unsigned-long *var-unsigned-long* 4294967295) (deftest foreign-globals.ref.float *var-float* 42.0) (deftest foreign-globals.ref.double *var-double* 42.0d0) (deftest foreign-globals.ref.pointer (null-pointer-p *var-pointer*) t) (deftest foreign-globals.ref.string *var-string* "Hello, foreign world!") #+openmcl (push 'foreign-globals.set.long-long rt::*expected-failures*) (deftest foreign-globals.ref.long-long *var-long-long* -9223372036854775807) (deftest foreign-globals.ref.unsigned-long-long *var-unsigned-long-long* 18446744073709551615) ;; The *.set.* tests restore the old values so that the *.ref.* ;; don't fail when re-run. (defmacro with-old-value-restored ((place) &body body) (let ((old (gensym))) `(let ((,old ,place)) (prog1 (progn ,@body) (setq ,place ,old))))) (deftest foreign-globals.set.int (with-old-value-restored (*var-int*) (setq *var-int* 42) *var-int*) 42) (deftest foreign-globals.set.string (with-old-value-restored (*var-string*) (setq *var-string* "Ehxosxangxo") (prog1 *var-string* ;; free the string we just allocated (foreign-free (mem-ref (get-var-pointer '*var-string*) :pointer)))) "Ehxosxangxo") (deftest foreign-globals.set.long-long (with-old-value-restored (*var-long-long*) (setq *var-long-long* -9223000000000005808) *var-long-long*) -9223000000000005808) (deftest foreign-globals.get-var-pointer.1 (pointerp (get-var-pointer '*char-var*)) t) (deftest foreign-globals.get-var-pointer.2 (mem-ref (get-var-pointer '*char-var*) :char) -127) ;;; Symbol case. (defcvar "UPPERCASEINT1" :int) (defcvar "UPPER_CASE_INT1" :int) (defcvar "MiXeDCaSeInT1" :int) (defcvar "MiXeD_CaSe_InT1" :int) (deftest foreign-globals.ref.uppercaseint1 *uppercaseint1* 12345) (deftest foreign-globals.ref.upper-case-int1 *upper-case-int1* 23456) (deftest foreign-globals.ref.mixedcaseint1 *mixedcaseint1* 34567) (deftest foreign-globals.ref.mixed-case-int1 *mixed-case-int1* 45678) (when (string= (symbol-name 'nil) "NIL") (let ((*readtable* (copy-readtable))) (setf (readtable-case *readtable*) :invert) (eval (read-from-string "(defcvar \"UPPERCASEINT2\" :int)")) (eval (read-from-string "(defcvar \"UPPER_CASE_INT2\" :int)")) (eval (read-from-string "(defcvar \"MiXeDCaSeInT2\" :int)")) (eval (read-from-string "(defcvar \"MiXeD_CaSe_InT2\" :int)")) (setf (readtable-case *readtable*) :preserve) (eval (read-from-string "(DEFCVAR \"UPPERCASEINT3\" :INT)")) (eval (read-from-string "(DEFCVAR \"UPPER_CASE_INT3\" :INT)")) (eval (read-from-string "(DEFCVAR \"MiXeDCaSeInT3\" :INT)")) (eval (read-from-string "(DEFCVAR \"MiXeD_CaSe_InT3\" :INT)")))) ;;; EVAL gets rid of SBCL's unreachable code warnings. (when (string= (symbol-name (eval nil)) "nil") (let ((*readtable* (copy-readtable))) (setf (readtable-case *readtable*) :invert) (eval (read-from-string "(DEFCVAR \"UPPERCASEINT2\" :INT)")) (eval (read-from-string "(DEFCVAR \"UPPER_CASE_INT2\" :INT)")) (eval (read-from-string "(DEFCVAR \"MiXeDCaSeInT2\" :INT)")) (eval (read-from-string "(DEFCVAR \"MiXeD_CaSe_InT2\" :INT)")) (setf (readtable-case *readtable*) :downcase) (eval (read-from-string "(defcvar \"UPPERCASEINT3\" :int)")) (eval (read-from-string "(defcvar \"UPPER_CASE_INT3\" :int)")) (eval (read-from-string "(defcvar \"MiXeDCaSeInT3\" :int)")) (eval (read-from-string "(defcvar \"MiXeD_CaSe_InT3\" :int)")))) (deftest foreign-globals.ref.uppercaseint2 *uppercaseint2* 12345) (deftest foreign-globals.ref.upper-case-int2 *upper-case-int2* 23456) (deftest foreign-globals.ref.mixedcaseint2 *mixedcaseint2* 34567) (deftest foreign-globals.ref.mixed-case-int2 *mixed-case-int2* 45678) (deftest foreign-globals.ref.uppercaseint3 *uppercaseint3* 12345) (deftest foreign-globals.ref.upper-case-int3 *upper-case-int3* 23456) (deftest foreign-globals.ref.mixedcaseint3 *mixedcaseint3* 34567) (deftest foreign-globals.ref.mixed-case-int3 *mixed-case-int3* 45678) ;;; regression test: ;;; gracefully accept symbols in defcvar (defcvar *var-char* :char) (defcvar var-char :char) (deftest foreign-globals.symbol-name (values *var-char* var-char) -127 -127) ;;;# Namespace #-cffi-sys::flat-namespace (progn (deftest foreign-globals.namespace.1 (values (mem-ref (foreign-symbol-pointer "var_char" :library 'libtest) :char) (foreign-symbol-pointer "var_char" :library 'libtest2)) -127 nil) (deftest foreign-globals.namespace.2 (values (mem-ref (foreign-symbol-pointer "ns_var" :library 'libtest) :boolean) (mem-ref (foreign-symbol-pointer "ns_var" :library 'libtest2) :boolean)) t nil) ;; For its "default" module, Lispworks seems to cache lookups from ;; the newest module tried. If a lookup happens to have failed ;; subsequent lookups will fail even the symbol exists in other ;; modules. So this test fails. #+lispworks (pushnew 'foreign-globals.namespace.3 regression-test::*expected-failures*) (deftest foreign-globals.namespace.3 (values (foreign-symbol-pointer "var_char" :library 'libtest2) (mem-ref (foreign-symbol-pointer "var_char") :char)) nil -127) (defcvar ("ns_var" *ns-var1* :library libtest) :boolean) (defcvar ("ns_var" *ns-var2* :library libtest2) :boolean) (deftest foreign-globals.namespace.4 (values *ns-var1* *ns-var2*) t nil)) ;;;# Read-only (defcvar ("var_char" *var-char-ro* :read-only t) :char "docstring") (deftest foreign-globals.read-only.1 (values *var-char-ro* (ignore-errors (setf *var-char-ro* 12))) -127 nil) (deftest defcvar.docstring (documentation '*var-char-ro* 'variable) "docstring") ;;;# Other tests ;;; RT: FOREIGN-SYMBOL-POINTER shouldn't signal an error when passed ;;; an undefined variable. (deftest foreign-globals.undefined.1 (foreign-symbol-pointer "surely-undefined?") nil) (deftest foreign-globals.error.1 (handler-case (foreign-symbol-pointer 'not-a-string) (type-error () t)) t)
9,271
Common Lisp
.lisp
251
33.541833
79
0.690917
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
1d75345ebd8a6e2d54b73c4d5c9c27b2cd95e50fe0b90d6dc5b2dc69302e674c
548
[ 113539, 166931 ]
549
memory.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/memory.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; memory.lisp --- Tests for memory referencing. ;;; ;;; 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-tests) (deftest deref.char (with-foreign-object (p :char) (setf (mem-ref p :char) -127) (mem-ref p :char)) -127) (deftest deref.unsigned-char (with-foreign-object (p :unsigned-char) (setf (mem-ref p :unsigned-char) 255) (mem-ref p :unsigned-char)) 255) (deftest deref.short (with-foreign-object (p :short) (setf (mem-ref p :short) -32767) (mem-ref p :short)) -32767) (deftest deref.unsigned-short (with-foreign-object (p :unsigned-short) (setf (mem-ref p :unsigned-short) 65535) (mem-ref p :unsigned-short)) 65535) (deftest deref.int (with-foreign-object (p :int) (setf (mem-ref p :int) -131072) (mem-ref p :int)) -131072) (deftest deref.unsigned-int (with-foreign-object (p :unsigned-int) (setf (mem-ref p :unsigned-int) 262144) (mem-ref p :unsigned-int)) 262144) (deftest deref.long (with-foreign-object (p :long) (setf (mem-ref p :long) -536870911) (mem-ref p :long)) -536870911) (deftest deref.unsigned-long (with-foreign-object (p :unsigned-long) (setf (mem-ref p :unsigned-long) 536870912) (mem-ref p :unsigned-long)) 536870912) #+(and darwin openmcl) (pushnew 'deref.long-long rt::*expected-failures*) (deftest deref.long-long (with-foreign-object (p :long-long) (setf (mem-ref p :long-long) -9223372036854775807) (mem-ref p :long-long)) -9223372036854775807) (deftest deref.unsigned-long-long (with-foreign-object (p :unsigned-long-long) (setf (mem-ref p :unsigned-long-long) 18446744073709551615) (mem-ref p :unsigned-long-long)) 18446744073709551615) (deftest deref.float.1 (with-foreign-object (p :float) (setf (mem-ref p :float) 0.0) (mem-ref p :float)) 0.0) (deftest deref.float.2 (with-foreign-object (p :float) (setf (mem-ref p :float) *float-max*) (mem-ref p :float)) #.*float-max*) (deftest deref.float.3 (with-foreign-object (p :float) (setf (mem-ref p :float) *float-min*) (mem-ref p :float)) #.*float-min*) (deftest deref.double.1 (with-foreign-object (p :double) (setf (mem-ref p :double) 0.0d0) (mem-ref p :double)) 0.0d0) (deftest deref.double.2 (with-foreign-object (p :double) (setf (mem-ref p :double) *double-max*) (mem-ref p :double)) #.*double-max*) (deftest deref.double.3 (with-foreign-object (p :double) (setf (mem-ref p :double) *double-min*) (mem-ref p :double)) #.*double-min*) ;;; TODO: use something like *DOUBLE-MIN/MAX* above once we actually ;;; have an available lisp that supports long double. ;#-cffi-sys::no-long-float #+(and scl long-double) (progn (deftest deref.long-double.1 (with-foreign-object (p :long-double) (setf (mem-ref p :long-double) 0.0l0) (mem-ref p :long-double)) 0.0l0) (deftest deref.long-double.2 (with-foreign-object (p :long-double) (setf (mem-ref p :long-double) most-positive-long-float) (mem-ref p :long-double)) #.most-positive-long-float) (deftest deref.long-double.3 (with-foreign-object (p :long-double) (setf (mem-ref p :long-double) least-positive-long-float) (mem-ref p :long-double)) #.least-positive-long-float)) ;;; make sure the lisp doesn't convert NULL to NIL (deftest deref.pointer.null (with-foreign-object (p :pointer) (setf (mem-ref p :pointer) (null-pointer)) (null-pointer-p (mem-ref p :pointer))) t) ;;; regression test. lisp-string-to-foreign should handle empty strings (deftest lisp-string-to-foreign.empty (with-foreign-pointer (str 2) (setf (mem-ref str :unsigned-char) 42) (lisp-string-to-foreign "" str 1) (mem-ref str :unsigned-char)) 0) ;;; regression test. with-foreign-pointer shouldn't evaluate ;;; the size argument twice. (deftest with-foreign-pointer.evalx2 (let ((count 0)) (with-foreign-pointer (x (incf count) size-var) (values count size-var))) 1 1) (defconstant +two+ 2) ;;; regression test. cffi-allegro's with-foreign-pointer wasn't ;;; handling constants properly. (deftest with-foreign-pointer.constant-size (with-foreign-pointer (p +two+ size) size) 2) (deftest mem-ref.left-to-right (let ((i 0)) (with-foreign-object (p :char 3) (setf (mem-ref p :char 0) 66 (mem-ref p :char 1) 92) (setf (mem-ref p :char (incf i)) (incf i)) (values (mem-ref p :char 0) (mem-ref p :char 1) i))) 66 2 2) ;;; This needs to be in a real function for at least Allegro CL or the ;;; compiler macro on %MEM-REF is not expanded and the test doesn't ;;; actually test anything! (defun %mem-ref-left-to-right () (let ((result nil)) (with-foreign-object (p :char) (%mem-set 42 p :char) (%mem-ref (progn (push 1 result) p) :char (progn (push 2 result) 0)) (nreverse result)))) ;;; Test left-to-right evaluation of the arguments to %MEM-REF when ;;; optimized by the compiler macro. (deftest %mem-ref.left-to-right (%mem-ref-left-to-right) (1 2)) ;;; This needs to be in a top-level function for at least Allegro CL ;;; or the compiler macro on %MEM-SET is not expanded and the test ;;; doesn't actually test anything! (defun %mem-set-left-to-right () (let ((result nil)) (with-foreign-object (p :char) (%mem-set (progn (push 1 result) 0) (progn (push 2 result) p) :char (progn (push 3 result) 0)) (nreverse result)))) ;;; Test left-to-right evaluation of the arguments to %MEM-SET when ;;; optimized by the compiler macro. (deftest %mem-set.left-to-right (%mem-set-left-to-right) (1 2 3)) ;; regression test. mem-aref's setf expansion evaluated its type argument twice. (deftest mem-aref.eval-type-x2 (let ((count 0)) (with-foreign-pointer (p 1) (setf (mem-aref p (progn (incf count) :char) 0) 127)) count) 1) (deftest mem-aref.left-to-right (let ((count -1)) (with-foreign-pointer (p 2) (values (setf (mem-aref p (progn (incf count) :char) (incf count)) (incf count)) (setq count -1) (mem-aref (progn (incf count) p) :char (incf count)) count))) 2 -1 2 1) ;; regression tests. nested mem-ref's and mem-aref's had bogus getters (deftest mem-ref.nested (with-foreign-object (p :pointer) (with-foreign-object (i :int) (setf (mem-ref p :pointer) i) (setf (mem-ref i :int) 42) (setf (mem-ref (mem-ref p :pointer) :int) 1984) (mem-ref i :int))) 1984) (deftest mem-aref.nested (with-foreign-object (p :pointer) (with-foreign-object (i :int 2) (setf (mem-aref p :pointer 0) i) (setf (mem-aref i :int 1) 42) (setf (mem-aref (mem-ref p :pointer 0) :int 1) 1984) (mem-aref i :int 1))) 1984) (cffi:defcstruct mem-aref.bare-struct (a :uint8)) ;;; regression test: although mem-aref was dealing with bare struct ;;; types as though they were pointers, it wasn't calculating the ;;; proper offsets. The offsets for bare structs types should be ;;; calculated as aggregate types. (deftest mem-aref.bare-struct (with-foreign-object (a 'mem-aref.bare-struct 2) (eql (- (pointer-address (cffi:mem-aref a 'mem-aref.bare-struct 1)) (pointer-address (cffi:mem-aref a 'mem-aref.bare-struct 0))) (foreign-type-size '(:struct mem-aref.bare-struct)))) t) ;;; regression tests. dereferencing an aggregate type. dereferencing a ;;; struct should return a pointer to the struct itself, not return the ;;; first 4 bytes (or whatever the size of :pointer is) as a pointer. ;;; ;;; This important for accessing an array of structs, which is ;;; what the deref.array-of-aggregates test does. (defcstruct some-struct (x :int)) (deftest deref.aggregate (with-foreign-object (s 'some-struct) (pointer-eq s (mem-ref s 'some-struct))) t) (deftest deref.array-of-aggregates (with-foreign-object (arr 'some-struct 3) (loop for i below 3 do (setf (foreign-slot-value (mem-aref arr 'some-struct i) 'some-struct 'x) 112)) (loop for i below 3 collect (foreign-slot-value (mem-aref arr 'some-struct i) 'some-struct 'x))) (112 112 112)) ;;; pointer operations (deftest pointer.1 (pointer-address (make-pointer 42)) 42) ;;; I suppose this test is not very good. --luis (deftest pointer.2 (pointer-address (null-pointer)) 0) (deftest pointer.null (nth-value 0 (ignore-errors (null-pointer-p nil))) nil) (deftest foreign-pointer-type.nil (typep nil 'foreign-pointer) nil) ;;; Ensure that a pointer to the highest possible address can be ;;; created using MAKE-POINTER. Regression test for CLISP/X86-64. (deftest make-pointer.high (let* ((pointer-length (foreign-type-size :pointer)) (high-address (1- (expt 2 (* pointer-length 8)))) (pointer (make-pointer high-address))) (- high-address (pointer-address pointer))) 0) ;;; Ensure that incrementing a pointer by zero bytes returns an ;;; equivalent pointer. (deftest inc-pointer.zero (with-foreign-object (x :int) (pointer-eq x (inc-pointer x 0))) t) ;;; Test the INITIAL-ELEMENT keyword argument to FOREIGN-ALLOC. (deftest foreign-alloc.1 (let ((ptr (foreign-alloc :int :initial-element 42))) (unwind-protect (mem-ref ptr :int) (foreign-free ptr))) 42) ;;; Test the INITIAL-ELEMENT and COUNT arguments to FOREIGN-ALLOC. (deftest foreign-alloc.2 (let ((ptr (foreign-alloc :int :count 4 :initial-element 100))) (unwind-protect (loop for i from 0 below 4 collect (mem-aref ptr :int i)) (foreign-free ptr))) (100 100 100 100)) ;;; Test the INITIAL-CONTENTS and COUNT arguments to FOREIGN-ALLOC, ;;; passing a list of initial values. (deftest foreign-alloc.3 (let ((ptr (foreign-alloc :int :count 4 :initial-contents '(4 3 2 1)))) (unwind-protect (loop for i from 0 below 4 collect (mem-aref ptr :int i)) (foreign-free ptr))) (4 3 2 1)) ;;; Test INITIAL-CONTENTS and COUNT with FOREIGN-ALLOC passing a ;;; vector of initial values. (deftest foreign-alloc.4 (let ((ptr (foreign-alloc :int :count 4 :initial-contents #(10 20 30 40)))) (unwind-protect (loop for i from 0 below 4 collect (mem-aref ptr :int i)) (foreign-free ptr))) (10 20 30 40)) ;;; Ensure calling FOREIGN-ALLOC with both INITIAL-ELEMENT and ;;; INITIAL-CONTENTS signals an error. (deftest foreign-alloc.5 (values (ignore-errors (let ((ptr (foreign-alloc :int :initial-element 1 :initial-contents '(1)))) (foreign-free ptr)) t)) nil) ;;; Regression test: FOREIGN-ALLOC shouldn't actually perform translation ;;; on initial-element/initial-contents since MEM-AREF will do that already. (define-foreign-type not-an-int () () (:actual-type :int) (:simple-parser not-an-int)) (defmethod translate-to-foreign (value (type not-an-int)) (assert (not (integerp value))) 0) (deftest foreign-alloc.6 (let ((ptr (foreign-alloc 'not-an-int :initial-element 'foooo))) (foreign-free ptr) t) t) ;;; Ensure calling FOREIGN-ALLOC with NULL-TERMINATED-P and a non-pointer ;;; type signals an error. (deftest foreign-alloc.7 (values (ignore-errors (let ((ptr (foreign-alloc :int :null-terminated-p t))) (foreign-free ptr)) t)) nil) ;;; The opposite of the above test. (defctype pointer-alias :pointer) (deftest foreign-alloc.8 (progn (foreign-free (foreign-alloc 'pointer-alias :count 0 :null-terminated-p t)) t) t) ;;; Ensure calling FOREIGN-ALLOC with NULL-TERMINATED-P actually places ;;; a null pointer at the end. Not a very reliable test apparently. (deftest foreign-alloc.9 (let ((ptr (foreign-alloc :pointer :count 0 :null-terminated-p t))) (unwind-protect (null-pointer-p (mem-ref ptr :pointer)) (foreign-free ptr))) t) ;;; RT: FOREIGN-ALLOC with :COUNT 0 on CLISP signalled an error. (deftest foreign-alloc.10 (foreign-free (foreign-alloc :char :count 0)) nil) ;;; Tests for mem-ref with a non-constant type. This is a way to test ;;; the functional interface (without compiler macros). (deftest deref.nonconst.char (let ((type :char)) (with-foreign-object (p type) (setf (mem-ref p type) -127) (mem-ref p type))) -127) (deftest deref.nonconst.unsigned-char (let ((type :unsigned-char)) (with-foreign-object (p type) (setf (mem-ref p type) 255) (mem-ref p type))) 255) (deftest deref.nonconst.short (let ((type :short)) (with-foreign-object (p type) (setf (mem-ref p type) -32767) (mem-ref p type))) -32767) (deftest deref.nonconst.unsigned-short (let ((type :unsigned-short)) (with-foreign-object (p type) (setf (mem-ref p type) 65535) (mem-ref p type))) 65535) (deftest deref.nonconst.int (let ((type :int)) (with-foreign-object (p type) (setf (mem-ref p type) -131072) (mem-ref p type))) -131072) (deftest deref.nonconst.unsigned-int (let ((type :unsigned-int)) (with-foreign-object (p type) (setf (mem-ref p type) 262144) (mem-ref p type))) 262144) (deftest deref.nonconst.long (let ((type :long)) (with-foreign-object (p type) (setf (mem-ref p type) -536870911) (mem-ref p type))) -536870911) (deftest deref.nonconst.unsigned-long (let ((type :unsigned-long)) (with-foreign-object (p type) (setf (mem-ref p type) 536870912) (mem-ref p type))) 536870912) #+(and darwin openmcl) (pushnew 'deref.nonconst.long-long rt::*expected-failures*) (deftest deref.nonconst.long-long (let ((type :long-long)) (with-foreign-object (p type) (setf (mem-ref p type) -9223372036854775807) (mem-ref p type))) -9223372036854775807) (deftest deref.nonconst.unsigned-long-long (let ((type :unsigned-long-long)) (with-foreign-object (p type) (setf (mem-ref p type) 18446744073709551615) (mem-ref p type))) 18446744073709551615) (deftest deref.nonconst.float.1 (let ((type :float)) (with-foreign-object (p type) (setf (mem-ref p type) 0.0) (mem-ref p type))) 0.0) (deftest deref.nonconst.float.2 (let ((type :float)) (with-foreign-object (p type) (setf (mem-ref p type) *float-max*) (mem-ref p type))) #.*float-max*) (deftest deref.nonconst.float.3 (let ((type :float)) (with-foreign-object (p type) (setf (mem-ref p type) *float-min*) (mem-ref p type))) #.*float-min*) (deftest deref.nonconst.double.1 (let ((type :double)) (with-foreign-object (p type) (setf (mem-ref p type) 0.0d0) (mem-ref p type))) 0.0d0) (deftest deref.nonconst.double.2 (let ((type :double)) (with-foreign-object (p type) (setf (mem-ref p type) *double-max*) (mem-ref p type))) #.*double-max*) (deftest deref.nonconst.double.3 (let ((type :double)) (with-foreign-object (p type) (setf (mem-ref p type) *double-min*) (mem-ref p type))) #.*double-min*) ;;; regression tests: lispworks's %mem-ref and %mem-set compiler ;;; macros were misbehaving. (defun mem-ref-rt-1 () (with-foreign-object (a :int 2) (setf (mem-aref a :int 0) 123 (mem-aref a :int 1) 456) (values (mem-aref a :int 0) (mem-aref a :int 1)))) (deftest mem-ref.rt.1 (mem-ref-rt-1) 123 456) (defun mem-ref-rt-2 () (with-foreign-object (a :double 2) (setf (mem-aref a :double 0) 123.0d0 (mem-aref a :double 1) 456.0d0) (values (mem-aref a :double 0) (mem-aref a :double 1)))) (deftest mem-ref.rt.2 (mem-ref-rt-2) 123.0d0 456.0d0) (deftest incf-pointer.1 (let ((ptr (null-pointer))) (incf-pointer ptr) (pointer-address ptr)) 1) (deftest incf-pointer.2 (let ((ptr (null-pointer))) (incf-pointer ptr 42) (pointer-address ptr)) 42) (deftest pointerp.1 (values (pointerp (null-pointer)) (null-pointer-p (null-pointer)) (typep (null-pointer) 'foreign-pointer)) t t t) (deftest pointerp.2 (let ((p (make-pointer #xFEFF))) (values (pointerp p) (typep p 'foreign-pointer))) t t) (deftest pointerp.3 (pointerp 'not-a-pointer) nil) (deftest pointerp.4 (pointerp 42) nil) (deftest pointerp.5 (pointerp 0) nil) (deftest pointerp.6 (pointerp nil) nil) (deftest mem-ref.setf.1 (with-foreign-object (p :char) (setf (mem-ref p :char) 42)) 42) (define-foreign-type int+1 () () (:actual-type :int) (:simple-parser int+1)) (defmethod translate-to-foreign (value (type int+1)) (1+ value)) (defmethod translate-from-foreign (value (type int+1)) (1+ value)) (deftest mem-ref.setf.2 (with-foreign-object (p 'int+1) (values (setf (mem-ref p 'int+1) 42) (mem-ref p 'int+1))) 42 ; should this be 43? 44) (deftest pointer-eq.non-pointers.1 (expecting-error (pointer-eq 1 2)) :error) (deftest pointer-eq.non-pointers.2 (expecting-error (pointer-eq 'a 'b)) :error) (deftest null-pointer-p.non-pointer.1 (expecting-error (null-pointer-p 'not-a-pointer)) :error) (deftest null-pointer-p.non-pointer.2 (expecting-error (null-pointer-p 0)) :error) (deftest null-pointer-p.non-pointer.3 (expecting-error (null-pointer-p nil)) :error)
19,015
Common Lisp
.lisp
557
29.251346
81
0.653176
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
9fecdce945e438efe8fc482dc09e183deb4989384eb17bf02b4ff6c86daf5ca0
549
[ 166080, 394980 ]
550
enum.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/enum.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; enum.lisp --- Tests on C enums. ;;; ;;; 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-tests) (defcenum numeros (:one 1) :two :three :four (:forty-one 41) :forty-two) (defcfun "check_enums" :int (one numeros) (two numeros) (three numeros) (four numeros) (forty-one numeros) (forty-two numeros)) (deftest enum.1 (check-enums :one :two :three 4 :forty-one :forty-two) 1) (defcenum another-boolean :false :true) (defcfun "return_enum" another-boolean (x :int)) (deftest enum.2 (and (eq :false (return-enum 0)) (eq :true (return-enum 1))) t) (defctype yet-another-boolean another-boolean) (defcfun ("return_enum" return-enum2) yet-another-boolean (x yet-another-boolean)) (deftest enum.3 (and (eq :false (return-enum2 :false)) (eq :true (return-enum2 :true))) t) ;;;# Bitfield tests ;;; Regression test: defbitfield was misbehaving when the first value ;;; was provided. (deftest bitfield.1 (eval '(defbitfield bf1 (:foo 0))) bf1) (defbitfield bf2 one two four eight sixteen thirty-two sixty-four) (deftest bitfield.2 (mapcar (lambda (symbol) (foreign-bitfield-value 'bf2 (list symbol))) '(one two four eight sixteen thirty-two sixty-four)) (1 2 4 8 16 32 64)) (defbitfield bf3 (three 3) one (seven 7) two (eight 8) sixteen) ;;; Non-single-bit numbers must not influence the progression of ;;; implicit values. Single bits larger than any before *must* ;;; influence said progression. (deftest bitfield.3 (mapcar (lambda (symbol) (foreign-bitfield-value 'bf3 (list symbol))) '(one two sixteen)) (1 2 16)) (defbitfield bf4 (zero 0) one) ;;; Yet another edge case with the 0... (deftest bitfield.4 (foreign-bitfield-value 'bf4 '(one)) 1)
3,033
Common Lisp
.lisp
99
27.646465
73
0.701851
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
e039d6b69f1dbd75b7a15ea682571827a9d259af466e55bc89a3a5233cc6ff72
550
[ -1 ]
551
strings.lisp
cac-t-u-s_om-sharp/src/api/foreign-interface/ffi/CFFI/tests/strings.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; strings.lisp --- Tests for foreign string conversion. ;;; ;;; Copyright (C) 2005, James Bielman <[email protected]> ;;; Copyright (C) 2007, 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-tests) ;;;# Foreign String Conversion Tests ;;; ;;; With the implementation of encoding support, there are a lot of ;;; things that can go wrong with foreign string conversions. This is ;;; a start at defining tests for strings and encoding conversion, but ;;; there needs to be a lot more. (babel:enable-sharp-backslash-syntax) ;;; *ASCII-TEST-STRING* contains the characters in the ASCII character ;;; set that we will convert to a foreign string and check against ;;; *ASCII-TEST-BYTES*. We don't bother with control characters. ;;; ;;; FIXME: It would probably be good to move these tables into files ;;; in "tests/", especially if we ever want to get fancier and have ;;; tests for more encodings. (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *ascii-test-string* (concatenate 'string " !\"#$%&'()*+,-./0123456789:;" "<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]" "^_`abcdefghijklmnopqrstuvwxyz{|}~"))) ;;; *ASCII-TEST-BYTES* contains the expected ASCII encoded values ;;; for each character in *ASCII-TEST-STRING*. (eval-when (:compile-toplevel :load-toplevel :execute) (defparameter *ascii-test-bytes* (let ((vector (make-array 95 :element-type '(unsigned-byte 8)))) (loop for i from 0 for code from 32 below 127 do (setf (aref vector i) code) finally (return vector))))) ;;; Test basic consistency converting a string to and from Lisp using ;;; the default encoding. (deftest string.conversion.basic (with-foreign-string (s *ascii-test-string*) (foreign-string-to-lisp s)) #.*ascii-test-string* 95) (deftest string.conversion.basic.2 (with-foreign-string ((ptr size) "123" :null-terminated-p nil) (values (foreign-string-to-lisp ptr :count 3) size)) "123" 3) ;;; Ensure that conversion of *ASCII-TEST-STRING* to a foreign buffer ;;; and back preserves ASCII encoding. (deftest string.encoding.ascii (with-foreign-string (s *ascii-test-string* :encoding :ascii) (let ((vector (make-array 95 :element-type '(unsigned-byte 8)))) (loop for i from 0 below (length vector) do (setf (aref vector i) (mem-ref s :unsigned-char i))) vector)) #.*ascii-test-bytes*) ;;; FIXME: bogus test. We need support for BOM or UTF-16{BE,LE}. (pushnew 'string.encoding.utf-16.basic rtest::*expected-failures*) ;;; Test UTF-16 conversion of a string back and forth. Tests proper ;;; null terminator handling for wide character strings and ensures no ;;; byte order marks are added. (Why no BOM? --luis) ;;; ;;; FIXME: an identical test using :UTF-16 wouldn't work because on ;;; little-endian architectures, :UTF-16 defaults to little-endian ;;; when writing and big-endian on reading because the BOM is ;;; suppressed. #-babel::8-bit-chars (progn (deftest string.encoding.utf-16le.basic (with-foreign-string (s *ascii-test-string* :encoding :utf-16le) (foreign-string-to-lisp s :encoding :utf-16le)) #.*ascii-test-string* 190) (deftest string.encoding.utf-16be.basic (with-foreign-string (s *ascii-test-string* :encoding :utf-16be) (foreign-string-to-lisp s :encoding :utf-16be)) #.*ascii-test-string* 190)) ;;; Ensure that writing a long string into a short buffer does not ;;; attempt to write beyond the edge of the buffer, and that the ;;; resulting string is still null terminated. (deftest string.short-write.1 (with-foreign-pointer (buf 6) (setf (mem-ref buf :unsigned-char 5) 70) (lisp-string-to-foreign "ABCDE" buf 5 :encoding :ascii) (values (mem-ref buf :unsigned-char 4) (mem-ref buf :unsigned-char 5))) 0 70) #-babel::8-bit-chars (deftest string.encoding.utf-8.basic (with-foreign-pointer (buf 7 size) (let ((string (concatenate 'babel:unicode-string '(#\u03bb #\u00e3 #\u03bb)))) (lisp-string-to-foreign string buf size :encoding :utf-8) (loop for i from 0 below size collect (mem-ref buf :unsigned-char i)))) (206 187 195 163 206 187 0)) (defparameter *basic-latin-alphabet* "abcdefghijklmnopqrstuvwxyz") (deftest string.encodings.all.basic (let (failed) ;;; FIXME: UTF-{32,16} and friends fail due to lack of BOM. See ;;; STRING.ENCODING.UTF-16.BASIC for more details. (dolist (encoding (remove-if (lambda (x) (member x '(:utf-32 :utf-16 :ucs-2))) (babel:list-character-encodings))) ;; (format t "Testing ~S~%" encoding) (with-foreign-string (ptr *basic-latin-alphabet* :encoding encoding) (let ((string (foreign-string-to-lisp ptr :encoding encoding))) ;; (format t " got ~S~%" string) (unless (string= *basic-latin-alphabet* string) (push encoding failed))))) failed) nil) ;;; rt: make sure *default-foreign-enconding* binds to a keyword (deftest string.encodings.default (keywordp *default-foreign-encoding*) t)
6,395
Common Lisp
.lisp
134
43.029851
76
0.68807
cac-t-u-s/om-sharp
167
14
31
GPL-3.0
9/19/2024, 11:25:22 AM (Europe/Amsterdam)
8bab70e8ee37a4cfc491c5b13562c237570fc6677184593cd9212e9502d50a00
551
[ 302082, 446442 ]