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
32,206
chapter-2.lisp
andlys_ansi-common-lisp/chapters/chapter-2.lisp
(defvar l (list 'a 'b 'c 'd 'e)) (car l) (cdr l) (car (cdr (cdr l))) (third l) (listp '(a b c)) (not (listp 1)) (and (member 'a l) t) (defun is-even(n) (if (numberp n) (= (mod n 2) 0) nil)) (member 'f '('a 'b 'c 'd 'e 'f 6 7 8)) (member-if #'is-even '('a 'b 'c 'd 'e 'f)) (print (is-even 10)) (print (is-even 9)) (print (is-even 'a)) (null '()) (null '(a)) (defun our-member(obj lst) (if (null lst) nil (if (eql obj (car lst)) lst (our-member obj (cdr lst))))) (terpri) (print (our-member 'a '(e c b a))) (print (our-member 'b '(a b c))) (print (our-member 'z '(a b c))) (format t "~A plus ~A equals ~A.~%" 2 3 (+ 2 3)) (defun askem (string) (format t "~A~%" string) (let ((n (read))) (if (not (numberp n)) (askem string) n))) ;(askem "How old are you?") (defparameter *glob* 99) (defconstant limit (+ *glob* 1)) (boundp `*glob*) (setf lst (list 'a 'b 'c)) (setf (car lst) 'n) (setf a 'aaa b 'bbb c 'ccc) (defun my-reverse(lst) (let ((new-lst '())) (do ((n 0 (+ n 1))) ((> n (- (length lst) 1)) new-lst) (setf new-lst (cons (nth n lst) new-lst))))) (print (my-reverse '(h e l l o))) (function +) #'+ (apply #'+ '(1 2 3)) (funcall #'+ 1 2 3) (load "test.lisp") (func 'a 'b) (defvar sym (read)) (apply sym '(1 2 3 4 5)) ; #'max ; #'+ ; #'*
1,425
Common Lisp
.lisp
62
18.967742
57
0.505263
andlys/ansi-common-lisp
0
1
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
05895e0a53e686da3a68f7013becd4f6e0687bbb87d63e10867390b67b6f10e2
32,206
[ -1 ]
32,207
chapter-6-ex.lisp
andlys_ansi-common-lisp/chapters/chapter-6-ex.lisp
;;; ex-3 (defun len (&rest args) (length args)) (len) (len nil) (len 'a) (len 'a 'b) (len 'a 'b 'c) ;;; ex-6 ;; closure technique used ;; description: function that takes one number and returns the greatest number ;; passed to it so far (let (lst) (defun highest (n) (reduce #'max (push n lst)))) (highest 0) (highest 1) (highest -1) (highest 3) (highest 2) ;;; ex-7 ;; closure technique used ;; description: function that takes one number and returns true if it is ;; greater than the last number passed to it (let (last) (defun greater-than-last? (n) (prog1 (> n (if last last n)) (setf last n)))) (greater-than-last? 0) (greater-than-last? -1) (greater-than-last? 4) (greater-than-last? 6) (greater-than-last? 6) (greater-than-last? 5)
765
Common Lisp
.lisp
33
21.393939
78
0.68088
andlys/ansi-common-lisp
0
1
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
b820d34b221f3f8144deed7ce56b6d9bce40956c61de0c6de0019f58df176b47
32,207
[ -1 ]
32,208
chapter-6-utils.lisp
andlys_ansi-common-lisp/chapters/chapter-6-utils.lisp
; *** fn *** (defun single? (lst) (and (consp lst) (null (cdr lst)))) (defun append1 (lst obj) (append lst (list obj))) (defun map-int (fn n) (let ((acc nil)) (dotimes (i n) (push (funcall fn i) acc)) (nreverse acc))) (defun filter (fn lst) (let ((acc nil)) (dolist (x lst) (let ((val (funcall fn x))) (if val (push val acc)))) (nreverse acc)))
394
Common Lisp
.lisp
16
20.5625
37
0.557641
andlys/ansi-common-lisp
0
1
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
65796588a87fdd9b041b58591d786d9ca1a1ff663fe879a77cb5613706b696b9
32,208
[ -1 ]
32,209
chapter-4-tree.lisp
andlys_ansi-common-lisp/chapters/chapter-4-tree.lisp
;;; code from the book retyped here by me (defstruct (node (:print-function (lambda (node stream depth) (format stream "#<~A>" (node-value node))))) value (left nil) (right nil)) (defun bst-insert (obj bst less-cmp) (if (null bst) (make-node :value obj) (let ((val (node-value bst))) (if (eql obj val) bst (if (funcall less-cmp obj val) (make-node :value val :left (bst-insert obj (node-left bst) less-cmp) :right (node-right bst)) (make-node :value val :left (node-left bst) :right (bst-insert obj (node-right bst) less-cmp))))))) (defun bst-find (obj bst less-cmp) (if (null bst) nil (let ((val (node-value bst))) (if (eql obj val) bst (if (funcall less-cmp obj val) (bst-find obj (node-left bst) less-cmp) (bst-find obj (node-right bst) less-cmp)))))) (defun bst-find-min (bst) (if (null bst) nil (let ((left (node-left bst))) (if (null left) bst (bst-find-min left))))) (defun bst-find-max (bst) (if (null bst) nil (let ((right (node-right bst))) (if (null right) bst (bst-find-max right))))) (defun bst-remove (obj bst less-cmp) (if (null bst) nil (let ((val (node-value bst))) (if (eql obj val) (percolate bst) (if (funcall less-cmp obj val) (make-node :value val :left (bst-remove obj (node-left bst) less-cmp) :right (node-right bst)) (make-node :value val :left (node-left bst) :right (bst-remove obj (node-right bst) less-cmp))))))) (defun percolate (bst) (cond ((null (node-left bst)) (if (null (node-right bst)) nil (rpec bst))) ((null (node-right bst)) (lperc bst)) (t (if (zerop (random 2)) (lperc bst) (rperc bst))))) (defun rperc (bst) (make-node :value (node-value (node-right bst)) :left (node-left bst) :right (percolate (node-right bst)))) (defun lperc (bst) (make-node :value (node-value (node-left bst)) :left (percolate (node-left bst)) :right (node-right bst)))
2,737
Common Lisp
.lisp
77
22.272727
79
0.450773
andlys/ansi-common-lisp
0
1
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
6644f9cda10a4b504266a565dbefa753cdd51b52edd88b143dc00f62df1d7cc2
32,209
[ -1 ]
32,210
chapter-4.lisp
andlys_ansi-common-lisp/chapters/chapter-4.lisp
(defparameter arr (make-array '(2 3) :initial-element nil)) (aref arr 0 0) (setf (aref arr 0 0) 'b) (setf *print-array* t) (defparameter vec (make-array 4 :initial-element nil)) (vector "a" 'b 3) (svref vec 0) #| a multy- line comment |# ;;;; Utilities for operations on sorted vector ;;; finds an element in a sorted vector (defun bin-search (obj vec) (let ((len (length vec))) (if (zerop len) nil (finder obj vec 0 (- len 1))))) (defun finder (obj vec start end) (format t "~A~%" (subseq vec start (+ end 1))) (let ((range (- end start))) (if (zerop range) nil (let ((mid (+ start (round (/ end 2))))) (let ((obj2 (aref vec mid))) (if (> obj obj2) (finder obj vec (+ mid 1) end) (finder obj vec start (- mid 1)))))))) (bin-search 3 #(0 1 2 3 4 5 6 7 8 9)) (sort "elbow" #'char<) (sort (list "bbb" "aaa" "ccc") #'string<) (aref "abc" 1) (char "abc" 1) ;; the first argument of 'format' operator defines whether string will go ;; to the output stream or to a resulting string object (format nil "~A or ~A" "truth" "dare") (identity "a") (position #\a "fantasia") (position #\a "fantasia" :start 3 :end 5) (position #\a "fantasia" :from-end t) (position 'a '((c d) (a b))) (position 'a '((c d) (a b)) :key #'car) (position 3 '(4 3 2 1) :test #'>) (defun second-word (str) (let ((i (+ (position #\ str) 1))) (subseq str i (position #\ str :start i)))) (second-word "Form follows function") (defun nth-word (n str) (let ((i 0)) (loop (when (= n 1) (return-from nth-word (subseq str i (position #\ str :start i)))) (decf n) (setq i (+ 1 (position #\ str :start i)))))) (nth-word 1 "Form follows function") (position-if #'oddp '(2 3 4 5)) (defun fun (x) (setq x 42) (print x) ) (let ((a 1)) (fun a) (print a)) (find #\a "cat") (remove-duplicates "abracadabra") (reduce #'intersection '((b r a d 's ) (b a d) (c a t))) (defun tokens (str test start) (let ((p1 (position-if test str :start start))) (if p1 (let ((p2 (position-if #'(lambda (chr) (not (funcall test chr))) str :start p1))) (cons (subseq str p1 p2) (if p2 (tokens str test p2) nil))) nil))) (tokens "ab12 3cde.f" #'alpha-char-p 0) (defun constituent (chr) (and (graphic-char-p chr) (not (char= chr #\ )))) (tokens "ab12 3cde.f gh" #'constituent 0) (defun parse-date-my (date-str) (let ((lst (tokens date-str #'constituent 0))) (let ((mth (cadr lst))) (if (string-equal "Aug" mth) (setq mth 8)) (list (first lst) mth (last lst))))) (defun parse-date (str) (let ((toks (tokens str #'constituent 0))) (list (parse-integer (first toks)) (parse-month (second toks)) (parse-integer (third toks))))) (defconstant month-names #("jan" "feb" "mar" "apr" "may" "jun" "jul" "aug" "sep" "oct" "nov" "dec")) (defun parse-month (str) (let ((p (position str month-names :test #'string-equal))) (if p (+ p 1) nil))) (parse-date "16 Aug 1980") (parse-date-my "16 Aug 1980") (defun read-integer (str) (if (every #'digit-char-p str) (let ((accum 0)) (dotimes (pos (length str)) (setf accum (+ (* accum 10) (digit-char-p (char str pos))))) accum) nil)) (read-integer "42") ;;;; structures ;; note: every point structure is of type point, structure, atom, t (defstruct point x y) (defparameter p (make-point :x 0 :y 0)) (point-p p) (point-p 42) (point-x p) (point-y p) (copy-point p) (setf (point-y p) 2) p (typep p 'point) (defstruct polemic (type (progn (format t "What type of polemic was it? ") (read))) (effect nil)) (make-polemic) ;; input - scathing (defstruct (point (:conc-name p) (:print-function print-point)) (x 0) (y 0)) (defun print-point (p stream depth) (format stream "#<~A,~A>" (px p) (py p))) (make-point :x 42 :y -42) ;;;; BST (Binary Search Tree) is a tree in which, for some ordering function <, ;;;; the left child of each element is < the element, and the element is < its ;;;; right child. (defparameter node (cons 'a (cons '(b c) nil))) (car node) (cadr node) (defstruct (node (:print-function (lambda (node stream depth) (format stream "#<~A>" (node-value node))))) value (left nil) (right nil)) (defun bst-insert (obj bst less-cmp) (if (null bst) (make-node :value obj) (let ((val (node-value bst))) (if (eql obj val) bst (if (funcall less-cmp obj val) (make-node :value val :left (bst-insert obj (node-left bst) less-cmp) :right (node-right bst)) (make-node :value val :left (node-left bst) :right (bst-insert obj (node-right bst) less-cmp))))))) (defun bst-find (obj bst less-cmp) (if (null bst) nil (let ((val (node-value bst))) (if (eql obj val) bst (if (funcall less-cmp obj val) (bst-find obj (node-left bst) less-cmp) (bst-find obj (node-right bst) less-cmp)))))) (defun bst-find-min (bst) (if (null bst) nil (let ((left (node-left bst))) (if (null left) bst (bst-find-min left))))) (defun bst-find-max (bst) (if (null bst) nil (let ((right (node-right bst))) (if (null right) bst (bst-find-max right))))) (defun bst-remove (obj bst less-cmp) (if (null bst) nil (let ((val (node-value bst))) (if (eql obj val) (percolate bst) (if (funcall less-cmp obj val) (make-node :value val :left (bst-remove obj (node-left bst) less-cmp) :right (node-right bst)) (make-node :value val :left (node-left bst) :right (bst-remove obj (node-right bst) less-cmp))))))) (defun percolate (bst) (cond ((null (node-left bst)) (if (null (node-right bst)) nil (rpec bst))) ((null (node-right bst)) (lperc bst)) (t (if (zerop (random 2)) (lperc bst) (rperc bst))))) (defun rperc (bst) (make-node :value (node-value (node-right bst)) :left (node-left bst) :right (percolate (node-right bst)))) (defun lperc (bst) (make-node :value (node-value (node-left bst)) :left (percolate (node-left bst)) :right (node-right bst))) (defparameter tree nil) (dolist (n '(5 8 4 2 1 9 6 3)) (setf tree (bst-insert n tree #'<))) (bst-find 12 tree #'<) (bst-find 4 tree #'<) (bst-find-min tree) (bst-find-max tree) (setf tree (bst-remove 2 tree #'<)) (bst-find 2 tree #'<) (defun bst-traverse (fn bst) (when bst (bst-traverse fn (node-left bst)) (funcall fn (node-value bst)) (bst-traverse fn (node-right bst)))) (bst-traverse #'princ tree) (defparameter ht (make-hash-table)) (gethash 'color ht) (setf (gethash 'color ht) 'red) (gethash 'color ht) (defun our-member () ()) (defparameter bugs (make-hash-table)) (push "Doesn't take keyword arguments." (gethash #'our-member bugs)) (defparameter fruit (make-hash-table)) (setf (gethash 'apricot fruit) t) ; using hashtables as sets (gethash 'apricot fruit) (remhash 'apricot fruit) ; removes an entry from a hashtable (setf (gethash 'shape ht) 'spherical (gethash 'size ht) 'giant) (maphash #'(lambda (k v) (format t "~A -> ~A~%" k v)) ht) (make-hash-table :size 5) (defparameter ht2 (make-hash-table :size 1 :test #'equal)) (setf (gethash '(ralph waldo emerson) ht2) t)
8,583
Common Lisp
.lisp
258
24.813953
82
0.522507
andlys/ansi-common-lisp
0
1
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
52e2f32ece6a3f234b9909ec39949a6cf65df5954b6c0c8b0a96d2b607adb444
32,210
[ -1 ]
32,241
diff-sexp.lisp
nickziv_blip/diff-sexp.lisp
;;; diff-sexp.lisp -- diffs s-expressions based on Levenshtein-like edit distance. ;; Author: Michael Weber <[email protected]> ;; Date: 2005-09-03 ;; Modified: 2005-09-04 ;; Modified: 2005-09-07 ;; Modified: 2005-09-15 ;; ;; This code is in the Public Domain. ;;; Description: ;; DIFF-SEXP computes a diff between two s-expressions which minimizes ;; the number of atoms in the result tree, also counting edit ;; conditionals |#+new|, |#-new|. ;;; Examples: ;; DIFF-SEXP> (diff-sexp ;; '(DEFUN F (X) (+ (* X 2) 1)) ;; '(DEFUN F (X) (- (* X 2) 3 1))) ;; ((DEFUN F (X) (|#-new| + |#+new| - (* X 2) |#+new| 3 1))) ;; DIFF-SEXP> (diff-sexp ;; '(DEFUN F (X) (+ (* X 2) 4 1)) ;; '(DEFUN F (X) (- (* X 2) 5 3 1))) ;; ((DEFUN F (X) (|#-new| + |#+new| - (* X 2) |#-new| 4 |#+new| 5 |#+new| 3 1))) ;; DIFF-SEXP> (diff-sexp ;; '(DEFUN F (X) (+ (* X 2) 4 4 1)) ;; '(DEFUN F (X) (- (* X 2) 5 5 3 1))) ;; ((DEFUN F (X) |#-new| (+ (* X 2) 4 4 1) |#+new| (- (* X 2) 5 5 3 1))) ;; DIFF-SEXP> ;;; Todo: ;; * Support for moved subtrees ;; * The algorithm treats vectors, arrays, etc. as opaque objects ;; * Test harness ;; * Factor for better configurability ;; * This article might describe a better method (unchecked): ;; Hélène Touzet: "A linear tree edit distance algorithm for similar ordered trees" ;; LIFL - UMR CNRS 8022 - Université Lille 1 ;; 59 655 Villeneuve d'Ascq cedex, France ;; [email protected] ;;; Code: (defpackage #:mw-diff-sexp (:use #:cl) (:export #:diff-sexp)) (in-package #:mw-diff-sexp) (defun tree-size (tree) "Computes the number of atoms contained in TREE." (if (atom tree) 1 (reduce #'+ tree :key #'tree-size))) (defclass edit-record () ((edit-distance :reader edit-distance))) (defclass unchanged-record (edit-record) ((change :reader change :initarg :change))) (defclass deletion-record (edit-record) ((change :reader change :initarg :change))) (defclass insertion-record (edit-record) ((change :reader change :initarg :change))) (defclass update-record (edit-record) ((old :reader update-record-old :initarg :old) (new :reader update-record-new :initarg :new))) (defclass compound-record (edit-record) ((changes :reader changes :initarg :changes)) (:default-initargs :changes ())) (defmethod initialize-instance :after ((record deletion-record) &key) (setf (slot-value record 'edit-distance) (1+ (tree-size (slot-value record 'change))))) (defmethod initialize-instance :after ((record insertion-record) &key) (setf (slot-value record 'edit-distance) (1+ (tree-size (slot-value record 'change))))) (defmethod initialize-instance :after ((record update-record) &key) (setf (slot-value record 'edit-distance) (+ 1 (tree-size (update-record-old record)) 1 (tree-size (update-record-new record))))) (defmethod initialize-instance :after ((record unchanged-record) &key) (setf (slot-value record 'edit-distance) (tree-size (slot-value record 'change)))) (defmethod initialize-instance :after ((record compound-record) &key) (setf (slot-value record 'edit-distance) (reduce #'+ (slot-value record 'changes) :key #'edit-distance))) (defun insertion-record (change) (make-instance 'insertion-record :change change)) (defun deletion-record (change) (make-instance 'deletion-record :change change)) (defun update-record (old new) (make-instance 'update-record :old old :new new)) (defun unchanged-record (change) (make-instance 'unchanged-record :change change)) (defun empty-compound-record () (make-instance 'compound-record)) (defun extend-compound-record (r0 record) (make-instance 'compound-record :changes (list* record (changes r0)))) (defgeneric render-difference (record)) (defmethod render-difference ((record insertion-record)) (list :|#+new| (change record))) (defmethod render-difference ((record deletion-record)) (list :|#-new| (change record))) (defmethod render-difference ((record update-record)) (list :|#-new| (update-record-old record) :|#+new| (update-record-new record))) (defmethod render-difference ((record unchanged-record)) (list (change record))) (defmethod render-difference ((record compound-record)) (list (loop for r in (reverse (changes record)) append (render-difference r)))) (defun min/edit (record &rest records) "Returns record with minimum edit distance." (flet ((min/edit/2 (a b) (if (<= (edit-distance a) (edit-distance b)) a b))) (declare (dynamic-extent #'min/edit/2)) (reduce #'min/edit/2 records :initial-value record))) (defun initial-distance (function list) "Prepares initial data vectors for Levenshtein algorithm from LIST." (loop with seq = (make-sequence '(vector edit-record) (1+ (length list)) :initial-element (empty-compound-record)) for i from 0 for elt in list do (setf (elt seq (1+ i)) (extend-compound-record (elt seq i) (funcall function elt))) finally (return seq))) (defun levenshtein-tree-edit (old-tree new-tree) "Calculates the minimal edits needed to transform OLD-TREE into NEW-TREE. It minimizes the number of atoms in the result tree, also counting edit conditionals." (cond ((equal old-tree new-tree) (unchanged-record old-tree)) ((or (atom old-tree) (atom new-tree)) (update-record old-tree new-tree)) (t (min/edit (update-record old-tree new-tree) (loop with row = (initial-distance #'deletion-record old-tree) and col = (initial-distance #'insertion-record new-tree) and best-edit for new-part in new-tree for current across (subseq col 1) do (loop for old-part in old-tree for row-idx from 0 do (setq best-edit (min/edit (extend-compound-record (elt row (1+ row-idx)) (insertion-record new-part)) (extend-compound-record current (deletion-record old-part)) (extend-compound-record (elt row row-idx) (levenshtein-tree-edit old-part new-part)))) (shiftf (elt row row-idx) current best-edit)) (setf (elt row (1- (length row))) best-edit) finally (return best-edit)))))) (defun diff-sexp (old-tree new-tree) "Computes a diff between OLD-TREE and NEW-TREE which minimizes the number of atoms in the result tree, also counting inserted edit conditionals |#+new|, |#-new|." (render-difference (levenshtein-tree-edit old-tree new-tree))) ;;; Tests #|| (defun n-ary-tree (arity depth gen) (if (> depth 0) (loop repeat arity collect (n-ary-tree arity (1- depth) gen)) (funcall gen))) (defun time/diff-sexp (n &key (arity 2)) (let ((x 1)) (flet ((generator () (prog1 x (incf x)))) (let ((t1 (n-ary-tree arity n #'generator)) (t2 (n-ary-tree arity n #'generator))) (time (diff-sexp t1 t2)))))) ||#
6,815
Common Lisp
.lisp
167
37.359281
85
0.674549
nickziv/blip
0
0
0
MPL-2.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
83403ae918e8462e68e05abc253c03161121b7f5b656aab700c1310838820f00
32,241
[ -1 ]
32,242
envs.lisp
nickziv_blip/envs.lisp
;;; This Source Code Form is subject to the terms of the Mozilla Public ;;; License, v. 2.0. If a copy of the MPL was not distributed with this ;;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;;; Copyright 2017 Joyent, Inc. ;;; Copyright 2017 Nicholas Zivkovic (defvar env-stack nil) (defvar env-pool nil) ;(setf env-avail (file-to-form blip-env-avail)) (defvar env-avail nil) (defun all-files (repo commit suf pref antipref &optional depth) (let* ((fs (list-files-at-commit repo commit :suf suf :pref pref :antipref antipref))) (cond ((and depth) (map 'list #'(lambda (p) (apply #'str-cat p)) (map 'list #'(lambda (p) (intersperse p "/" t)) (remove-if #'(lambda (p) (> (length p) depth)) (map 'list #'(lambda (f) (str-split "/" f)) fs))))) ((not depth) fs)) )) (defun all-files-if (repo commit suf pref antipref test) (remove nil (map 'list #'(lambda (f) (if (funcall test f) f nil)) (all-files repo commit suf pref antipref)))) (defun set-env-all-files () (set-env-var 'files (all-files (get-env-var 'repo) (get-env-var 'commit) (get-env-var 'parser-suf) (get-env-var 'parser-pref) (gen-env-var 'parser-antipref)))) (defun set-env-file (&rest fs) (set-env-var 'files fs) ) (defun set-env-files (fs) (set-env-var 'files fs) ) (defun set-env-file-depth (max-depth) (let ((fs (all-files (get-env-var 'repo) (get-env-var 'commit) (get-env-var 'parser-suf) (get-env-var 'parser-pref) (get-env-var 'parser-antipref)))) (set-env-var 'files (map 'list #'(lambda (p) (apply #'str-cat p)) (map 'list #'(lambda (p) (intersperse p "/" t)) (remove-if #'(lambda (p) (> (length p) max-depth)) (map 'list #'(lambda (f) (str-split "/" f)) fs) )))) ) ) (defun get-env-npages () (ceiling (float (/ (length (get-env-var 'files)) (get-env-var 'pagesz))))) (defun test-fdepth () (map 'list #'(lambda (p) (intersperse p "/" t)) (set-env-file-depth 2))) (defclass env () ((repo :initarg :repo) (commit :initarg :commit) (name :initarg :name) (indexer :initarg :indexer) (idx-type :initarg :idx-type) (idx-type-conv :initarg :idx-type-conv) (files :initarg :files) (pagesz :initarg :pagesz) (ast-fmt :initarg :ast-fmt) (parser :initarg :parser) (parser-suf :initarg :parser-suf) (parser-pref :initarg :parser-pref) (parser-antipref :initarg :parser-antipref) (ast-ls-call :initarg :ast-ls-call) (ast-ls-def :initarg :ast-ls-def) (ast-ls-fbind :initarg :ast-ls-fbind) (ast-ls-word :initarg :ast-ls-word) (what-requires :initarg :what-requires) (requires-what :initarg :requires-what) (bottom-deps :initarg :bottom-deps) (top-deps :initarg :top-deps) (what-exports :initarg :what-exports) (exports-what :initarg :exports-what)) ) (defun env-ls () env-avail) (defun env-stack () (map 'list #'(lambda (e) (slot-value e 'name)) env-stack)) (defmacro! new-env%% (name repo commit indexer idx-type idx-type-conv files pagesz ast-fmt parser parser-suf parser-pref parser-antipref ast-ls-call ast-ls-def ast-ls-fbind ast-ls-word what-requires requires-what bottom-deps top-deps what-exports exports-what) `(let ((tmp (make-instance 'env :repo ,repo :name ',name :commit ,commit :indexer ,indexer :idx-type ,idx-type :idx-type-conv ,idx-type-conv :files ,files :pagesz ,pagesz :ast-fmt ,ast-fmt :parser ,parser :parser-suf ,parser-suf :parser-pref ,parser-pref :parser-antipref ,parser-antipref :ast-ls-call ,ast-ls-call :ast-ls-def ,ast-ls-def :ast-ls-fbind ,ast-ls-fbind :ast-ls-word ,ast-ls-word :what-requires ,what-requires :requires-what ,requires-what :bottom-deps ,bottom-deps :top-deps ,top-deps :what-exports ,what-exports :exports-what ,exports-what))) (pushr! env-avail ',name) (pushr! env-pool tmp) ;(setf ,name tmp) ;;; TODO: save this env to a file tmp ) ) (defmacro! new-env (name &body body) `(let* (,@body) ;(assert (and repo commit indexer idx-type idx-type-conv files parser ;parser-suf parser-pref ast-ls-call ast-ls-def)) (new-env%% ,name repo commit indexer idx-type idx-type-conv files pagesz ast-fmt parser parser-suf parser-pref parser-antipref ast-ls-call ast-ls-def ast-ls-fbind ast-ls-word what-requires requires-what bottom-deps top-deps what-exports exports-what) ) ) (defmacro! new-js-env (name repo-nm commit &optional pref antipref depth) `(new-env ,name ;(name ',name) (repo ,repo-nm) (commit (expand-commit ,repo-nm ,commit)) (indexer #'index-all-js-paths) (idx-type :funcs) (idx-type-conv #'js-idx-type-to-test) (files (all-files repo commit ".js" ,pref ,antipref ,depth)) (pagesz 70) (ast-fmt #'(lambda (a) (js-ast-fmt nil a :simtupid))) (parser #'js-to-ast) (parser-suf ".js") (parser-pref ,pref) (parser-antipref ,antipref) (ast-ls-call #'js-list-fcalls) (ast-ls-def #'js-list-fdefs) (ast-ls-fbind #'js-list-fbinds) (ast-ls-word #'js-list-words) (requires-what #'js-requires-what) (what-requires #'js-what-requires) (bottom-deps #'js-bottom-deps) (top-deps #'js-top-deps) (exports-what nil) (what-exports nil) ) ) (defmacro! new-c-env (name repo-nm commit &optional pref antipref depth) `(new-env ,name ;(name ',name) (repo ,repo-nm) (commit (expand-commit ,repo-nm ,commit)) (indexer #'index-all-c-paths) (idx-type :funcs) (idx-type-conv #'c-idx-type-to-test) (files (all-files repo commit ".c" ,pref ,antipref ,depth)) (pagesz 70) (ast-fmt #'(lambda (a) (c-ast-fmt nil a :simtupid))) (parser #'c-to-ast) (parser-suf ".c") (parser-pref ,pref) (parser-antipref ,antipref) (ast-ls-call #'c-list-fcalls) (ast-ls-def #'c-list-fdefs) (ast-ls-fbind nil) (ast-ls-word #'c-list-words) (requires-what nil) (what-requires nil) (bottom-deps nil) (top-deps nil) (exports-what nil) (what-exports nil) ) ) ;(form-to-file (env-ls) blip-env-avail) (defun pushenv (e) (pushr! env-stack e) ) (defun popenv () (popr! env-stack) ) (defun get-env-var (var) (let ((e (car (last env-stack)))) (slot-value e var))) (defun set-env-var (var val) (let ((e (car (last env-stack)))) (setf (slot-value e var) val) ) ) (defmacro! in-index-env (force page alt-idx-type &body body) `(let* ((repo (get-env-var 'repo)) (files (get-env-var 'files)) (cmt (get-env-var 'commit)) (pgsz (get-env-var 'pagesz)) (ast-fmt (get-env-var 'ast-fmt)) (idx-type (if (and ,alt-idx-type) ,alt-idx-type (get-env-var 'idx-type))) (indexer (get-env-var 'indexer)) (idx-type-conv (get-env-var 'idx-type-conv)) (indices (map 'list #'(lambda (f) (pipeline (load-ast repo f cmt) #'(lambda (ast) (path-index-setroot (funcall indexer repo f cmt idx-type ast :force ,force))) #'(lambda (ix) (list f ix))) ) (get-nth-page files ,page pgsz)))) ,@body ) ) (defmacro! in-ls-env (&body body) `(let* ((repo (get-env-var 'repo)) (files (get-env-var 'files)) (cmt (get-env-var 'commit)) (ast-ls-call (get-env-var 'ast-ls-call)) (ast-ls-def (get-env-var 'ast-ls-def)) (ast-ls-fbind (get-env-var 'ast-ls-fbind)) (ast-ls-word (get-env-var 'ast-ls-word)) ) ,@body)) (defmacro! in-req-env (&body body) `(let* ((repo (get-env-var 'repo)) (files (get-env-var 'files)) (cmt (get-env-var 'commit)) (requires-what (get-env-var 'requires-what)) (what-requires (get-env-var 'what-requires)) (top-deps (get-env-var 'top-deps)) (bottom-deps (get-env-var 'bottom-deps)) (what-exports (get-env-var 'what-exports)) (exports-what (get-env-var 'exports-what)) ) ,@body)) (defun index-print (&optional pov &key page force alt-idx-type) (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (ix) (print-js-paths ix pov)) indices))) (defun index-build (&key force alt-idx-type) (iter:iter (iter:for i from 0 to (- (get-env-npages) 1)) (index-print :down :force force :page i :alt-idx-type alt-idx-type) ) t) (defmacro! ast-ls (name lister) `(defun ,name (&optional count &key pref force) (in-ls-env (let ((full-list nil) (filt-list nil)) (setf full-list (map 'list #'(lambda (f) (list f (if ,lister (funcall ,lister repo f cmt count :force force) nil))) files)) (if (and pref) (setf filt-list (map 'list #'(lambda (pair) (cond ((and count) (if (not (member pref (cadr pair) :test #'is-str-prefix :key #'car)) nil pair)) ((not count) (if (not (member pref (cadr pair) :test #'is-str-prefix)) nil pair)))) full-list))) (if (not pref) (remove-if #'not full-list :key #'cadr) (remove nil filt-list)) ))) ) (ast-ls ast-ls-fdefs ast-ls-def) (ast-ls ast-ls-fbinds ast-ls-fbind) (ast-ls ast-ls-words ast-ls-word) (ast-ls ast-ls-fcalls ast-ls-call) (defun ast-ls-files () (in-ls-env files)) (defun env-file-to-path (f) (in-ls-env (str-cat blip-repos (get-env-var 'repo) "/" f))) (defun ast-extract-files (ast-ls-out) (map 'list #'car ast-ls-out)) (defun ast-extract-entities (ast-ls-out) (map 'list #'cadr ast-ls-out)) (defun defs-uncalled () (let ((defs (remove-duplicates (append (append-ls (ast-extract-entities (ast-ls-fbinds))) (append-ls (ast-extract-entities (ast-ls-fdefs)))) :test #'equal)) (calls (remove-duplicates (append-ls (ast-extract-entities (ast-ls-fcalls))) :test #'equal))) (set-difference defs calls :test #'equal) )) (defun calls-undefed () (let ((defs (remove-duplicates (append (append-ls (ast-extract-entities (ast-ls-fbinds))) (append-ls (ast-extract-entities (ast-ls-fdefs)))) :test #'equal)) (calls (remove-duplicates (append-ls (ast-extract-entities (ast-ls-fcalls))) :test #'equal))) (set-difference calls defs :test #'equal) )) (defun ast-parse (&optional force) (let* ((repo (get-env-var 'repo)) (cmt (get-env-var 'commit)) (suf (get-env-var 'parser-suf)) (pref (get-env-var 'parser-pref)) (antipref (get-env-var 'parser-antipref)) (parser (get-env-var 'parser)) ) (parse-x-files-at-commit repo cmt :force force :suf suf :pref pref :parser parser :whitelist (ast-ls-files)) ) ) (defun reconstruct-repo () (ast-parse t) (index-build :force t) (ast-ls-fcalls t :force t) (ast-ls-fdefs t :force t) (ast-ls-words t :force t) (ast-ls-fbinds t :force t) t ) (defun index-get-subtree-impl (index path &optional pov) ;(map 'list #'(lambda (e) (ast-to-str (cdr e))) (get-path-subtree path index pov))) (get-path-subtree path index pov)) (defun index-get-path-walk-impl (index path &optional pov) (get-path-walk path index pov)) (defun index-get-subtree-str (path &optional pov &key page force alt-idx-type) (pre-filter-files path (in-index-env force (if (and page) page 0) alt-idx-type (remove-if #'(lambda (x) (equal (cadr x) "")) (map 'list #'(lambda (ix) (list (car ix) (map 'list #'(lambda (ast) (ast-to-str (funcall ast-fmt ast))) (cadr ix)))) (map 'list #'(lambda (ix) (index-get-subtree-impl ix path pov)) indices)))))) (defun split-ix-path (path) (str-split "/|{|}|\\(|\\)|=|:" path)) (defun get-mod-exp-key (ls) (assert (listp ls)) (let ((key nil)) (cond ((and (string= "module" (car ls)) (string= "exports" (cadr ls))) (setf key (caddr ls))) ((and (string= "exports" (car ls))) (setf key (cadr ls))) ) ) ) (defun remove-empty-strs (ls) (remove-if #'(lambda (s) (string= s "")) ls)) (defun ix-get-mod-exp-key (ix) (map 'list #'(lambda (p) (list (car p) (remove nil (map 'list #'get-mod-exp-key (map 'list #'remove-empty-strs (map 'list #'split-ix-path (cadr p))))))) ix) ) (defmacro! pre-filter-files (pref &body body) `(let ((spref (if (listp ,pref) (map 'list #'split-ix-path ,pref) (split-ix-path ,pref))) (f1 '()) (f2 '()) (f3 '()) (f4 '()) (rpref ,pref) (orig-files (ast-ls-files)) (res nil)) (setf rpref (if (listp ,pref) (map 'list #'car spref) (car spref))) ;;; XXX Given that f4 is a superset of f1,2,3 we might want to get rid of ;;; those. ;(setf f1 (ast-extract-files (ast-ls-fcalls t :pref rpref))) ;(setf f2 (ast-extract-files (ast-ls-fdefs t :pref rpref))) ;(setf f3 (ast-extract-files (ast-ls-fbinds t :pref rpref))) (cond ((or (listp ,pref) (and (stringp ,pref) (not (string= ,pref "/")))) (setf f4 (ast-extract-files (ast-ls-words t :pref rpref))) (set-env-files (remove-duplicates (append f1 f2 f3 f4) :test #'equal)) (setf res ,@body) (set-env-files orig-files) res ) ((and t) (setf res ,@body) res ) ) )) (defun index-get-subtree (path &optional pov &key page force alt-idx-type) (pre-filter-files path (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (ix) (index-get-subtree-impl ix path pov)) indices)))) (defun index-get-subtree-walk (path &optional pov &key page force alt-idx-type) (pre-filter-files path (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (ix) ;(index-get-subtree-impl ix path pov)) (index-get-path-walk-impl ix path pov)) indices))) ) (defun index-prefix (pref &optional pov &key page force alt-idx-type) (pre-filter-files pref (in-index-env force (if (and page) page 0) alt-idx-type (remove nil (map 'list #'(lambda (i) (get-path-with-prefix pref i pov)) indices) :key #'cadr) )) ) ;;; TODO update this function to use pre-filtered files like index-prefix does. (defun index-suffix (suf &optional pov &key page force alt-idx-type) (in-index-env force (if (and page) page 0) alt-idx-type (remove nil (map 'list #'(lambda (i) (get-path-with-suffix suf i pov)) indices) :key #'cadr) )) (defun index-word-count (word &optional pov &key zero pre page force alt-idx-type) (pre-filter-files word (in-index-env force (if (and page) page 0) alt-idx-type (assert idx-type) (map 'list #'(lambda (i) (get-path-node-count #'(lambda (n) (and (is-word-group n) (match-str-list word n))) i (funcall idx-type-conv idx-type) pov :zero zero :pre pre)) indices)))) (defun index-line-count (&optional pov &key zero pre page force alt-idx-type) (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (i) (get-path-node-count #'(lambda (n) (and (is-white-space-group n) (member #\Newline n))) i (funcall idx-type-conv idx-type) pov :zero zero :pre pre)) indices))) (defun index-uniq (&optional pov &key page force alt-idx-type) (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (i) (uniq-path i :pov pov :fmt t :sort-path t :sort-count t)) indices))) (defun index-path-depth (&optional pov &key page force alt-idx-type) (in-index-env force (if (and page) page 0) alt-idx-type (map 'list #'(lambda (i) (paths-by-depth i :pov pov :fmt t)) indices))) (defun ast-file-deps (&key force) ) (defun ast-what-requires (dep &key force) (in-req-env (if (and what-requires) (funcall what-requires repo cmt dep files force) "what-requires not supported in this env")) ) (defun ast-requires-what (dep &key force) (in-req-env (if (and requires-what) (funcall requires-what repo cmt dep files force) "requires-what not supported in this env")) ) (defun ast-bottom-deps (&key force) (in-req-env (if (and bottom-deps) (funcall bottom-deps repo cmt files force) "bottom-deps not supported in this env")) ) (defun ast-top-deps (&key force) (in-req-env (if (and top-deps) (funcall top-deps repo cmt files force) "top-deps not supported in this env")) ) (defmacro! in-exp-env (&body body) `(let* ((pref '("module/exports/" "module/exports=" "exports/" "exports=/")) (ix (index-prefix pref :down :alt-idx-type :binds)) (keys (ix-get-mod-exp-key ix)) ) ,@body ) ) (defun ast-what-exports (func) (in-exp-env (map 'list #'car (remove-if #'(lambda (p) (not (member func (cadr p) :test #'equal))) keys)) ) ) (defun ast-exports-what (file) (in-exp-env (car (map 'list #'cadr (remove-if #'(lambda (p) (not (string= file (car p)))) keys)) )) ) (defun ifdef-metrics () (sort (remove-if #'not (map 'list #'(lambda (p) (list (car p) (find-if #'(lambda (pp) (string= "#ifdef" (car pp)) ) (cadr p) ) )) (ast-ls-words t :pref "#ifdef")) :key #'cadr) #'< :key #'cadadr) ) (defun ifndef-metrics () (sort (remove-if #'not (map 'list #'(lambda (p) (list (car p) (find-if #'(lambda (pp) (string= "#ifndef" (car pp)) ) (cadr p) ) )) (ast-ls-words t :pref "#ifndef")) :key #'cadr) #'< :key #'cadadr) ) (defun load-env (env) "Reads in the cfg file, walks each record until it finds the appropriate env-name and evals it. Saves us a lot of (git-related) IO." (let ((ls (file-to-forms blip-env-cfg)) (result nil)) (map 'nil #'(lambda (e) (if (equal (cadr e) env) (progn (setf result (eval e))))) ls) result )) (defun have-env (env) "Confirms that an env is present in the cfg file. Does not eval it." (let ((ls (file-to-forms blip-env-cfg)) (have nil)) (map 'nil #'(lambda (e) (if (equal (cadr e) env) (setf have t))) ls) have )) (defun find-env (name) (find-if #'(lambda (e) (equal (slot-value e 'name) name)) env-avail))
21,975
Common Lisp
.lisp
575
26.965217
87
0.509191
nickziv/blip
0
0
0
MPL-2.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
d915a2a75e70a5ba25302498a18443d9d49c47d612a102148506fcb6bf58aa2a
32,242
[ -1 ]
32,243
startup.lisp
nickziv_blip/startup.lisp
;;; When loading, we need 2 passes to accomodate definition-after-use ;;; Could be avoided with FASL format but why bother? (load "blip.lisp") (reload)
152
Common Lisp
.lisp
4
37
69
0.756757
nickziv/blip
0
0
0
MPL-2.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
c01251314c65c60317124ac09ebe0a90164d4b812350dc6f92d6d6f1830513b2
32,243
[ -1 ]
32,244
blip.lisp
nickziv_blip/blip.lisp
;;; This Source Code Form is subject to the terms of the Mozilla Public ;;; License, v. 2.0. If a copy of the MPL was not distributed with this ;;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;;; Copyright 2017 Joyent, Inc. ;;; Copyright 2017 Nicholas Zivkovic (load "/opt/quicklisp/setup.lisp") (ql:quickload "let-over-lambda") (ql:quickload "cl-quickcheck") (ql:quickload "drakma") (ql:quickload "cl-ppcre") (ql:quickload "trivial-ssh") (ql:quickload "inferior-shell") ; Convenient for synchronous command execution (ql:quickload "cl-async") ; Libuv wrapper, convenient for background commands (ql:quickload "blackbird") ;promises over cl-async (ql:quickload "cl-ncurses") (ql:quickload "series") (ql:quickload "iterate") (ql:quickload "uuid") (ql:quickload "ironclad") ;Works, but not too good at validation ;(ql:quickload "unix-options") (load "diff-sexp.lisp") (defmacro defmacro! (&body body) "Shorthand for lol:defmacro" `(lol:defmacro! ,@body)) (defun repeat (x n) (let ((ls '()) (i 0)) (tagbody again (pushr! ls x) (incf i) (if (< i n) (go again))) ls)) (defun pushr1 (ls elem) "Pushes a single elem to the rightmost side of the list" (assert (listp ls)) (append ls (list elem))) (defun pushl1 (ls elem) "Pushes a single elem to the leftmost side of the list" (assert (listp ls)) (append (list elem) ls)) (defun pushr (ls &rest elems) "Pushes a list of elems to the rightmost side of the list" (reduce #'pushr1 elems :initial-value ls)) (defmacro! pushr! (ls &rest elems) "Same as pushr, but overwrites the list" `(setf ,ls (pushr ,ls ,@elems))) (defun pushl (ls &rest elems) "Pushes a list of elems to the leftmost side of the list" (reduce #'pushl1 elems :initial-value ls)) (defun pushlr (ls &rest elems) (pushr (pushl ls elems) elems) ) (defun pushrl (ls &rest elems) "Same as above. But added for symmetry" (pushl (pushr ls elems) elems) ) (defmacro! pushl! (ls &rest elems) "Same as pushl, but overwrites the list" `(setf ,ls (pushl ,ls ,@elems))) (defun sha256-file (path) (let ((digester (ironclad:make-digest :sha256))) (ironclad:digest-file digester path) )) (defun quiet-load (path) ;;; TODO see if we can do this via a nil make-broadcast-stream... (with-open-file (*error-output* "/dev/null" :direction :output :if-exists :supersede) (load path)) ) (defmacro! uuid () (uuid:make-v4-uuid)) (defmacro! flatten (&body body) "Shorthand for lol:flatten" `(lol:flatten ,@body)) (defun timed-funcall (func arg) "Calls function taking 1 arg and returns the return value of func and the time-elapsed (in micro-seconds)" (let ((start (get-internal-real-time)) (end nil) (ret nil)) (setf ret (funcall func arg)) (setf end (get-internal-real-time)) (values ret (- end start)))) (defun mysleep (s) (sleep s) s) (defun pipeline (arg &rest fns) "Takes a list of 1 args funcs, and chains them in a pipeline, so that each function takes the return value of the previous function as its argument" (iter:iter (iter:for f in fns) (iter:for (values ret time) initially (values arg 0) then (timed-funcall f ret)) (iter:after-each (iter:collect (list f time) into timing)) (iter:finally (return (values ret timing))))) (defun pipeline-until-aux (arg fns) (if (and fns) (let ((ret nil)) (setf ret (funcall (car fns) arg)) (if (not ret) (progn (pipeline-until-aux arg (cdr fns))) (progn ret) )) (progn nil))) (defun pipeline-until (arg &rest fns) "Like pipeline, except that it stops calling functions after a function returns a non-nil value." (pipeline-until-aux arg fns)) (defun test-pipeline-until () (pipeline-until 42 #'(lambda (n) (= n 10)) #'(lambda (n) (= n 20)) #'(lambda (n) (= n 30)) ;#'(lambda (n) (= n 42)) #'(lambda (n) (= n 50)) )) (defun test-pl () (pipeline 1 #'mysleep #'mysleep #'mysleep)) (defun string-to-symbol (s) (intern (string-upcase s))) (defun symbol-to-string (s) (string-downcase (symbol-name s))) (defun string-to-keyword (s) (intern (string-upcase s) "KEYWORD")) (defun str-cat-2 (s1 s2) "Concatenates 2 strings" (concatenate 'string s1 s2)) (defun str-cat (&rest strings) "Concatenates 2 or more strings" (reduce #'str-cat-2 strings)) (defun str-last-char (s) "Gets the last character of a string" (char s (- (length s) 1))) (defun is-str-suffix-one (suf str) "Checks if the strings has the given suffix" (if (> (length suf) (length str)) nil (let* ((off (- (length str) (length suf))) (end (subseq str off (length str)))) (string= suf end) ))) (defun is-str-prefix-one (pre str) "Checks if the strings has the given prefix" (if (> (length pre) (length str)) nil (let* ((off (length pre)) (end (subseq str 0 off))) (string= pre end) ))) (defun fn-or (&rest args) "Apparently `or` is a macro, not a function, so we can't just pass it as such" (let ((cur args)) (tagbody again (cond ((not cur) (return-from fn-or nil)) ((not (car cur)) (setf cur (cdr cur)) (go again)) ((and t) (return-from fn-or t)) ) ) ) ) (defmacro! def-are-strs-*ix (ls-name str-name) `(defun ,ls-name (*s str) "Applies is-str-suffix-str over a list, returns true if any match" (apply #'fn-or (map 'list #'(lambda (s) (,str-name s str)) *s)) )) (def-are-strs-*ix are-strs-suffix is-str-suffix-one) (def-are-strs-*ix are-strs-prefix is-str-prefix-one) (defmacro! def-is-str-*ix (gen-name ls-name str-name) `(defun ,gen-name (*/s str) (if (listp */s) (,ls-name */s str) (,str-name */s str) ) )) (def-is-str-*ix is-str-suffix are-strs-suffix is-str-suffix-one) (def-is-str-*ix is-str-prefix are-strs-prefix is-str-prefix-one) (defun str-has (regex str) (cl-ppcre:all-matches regex str)) (defun is-npm-range-version (v) (or (str-has "\\^" v) (str-has "~" v) (str-has "\\*" v) (str-has "-" v) (str-has ">" v) (str-has "<" v) (str-has "=" v) (str-has "x" v) (str-has "X" v) (str-has "\\+" v) )) (defun str-split (regex str) "Splits the string at each place that the given pcre regex is matched" (cl-ppcre:split regex str)) (defun cwd () "Returns the current working directory" (sb-posix:getcwd)) (defun chdir (d) "Changes the current working directory" (sb-posix:chdir d)) (defun mkdir (d) (assert (> (length d) 0)) (if (CHAR= #\/ (str-last-char d)) (ensure-directories-exist d) (ensure-directories-exist (str-cat d "/")) )) (defvar dirhist '()) (defun pushdir (d) "Changes the current working directory and update the stack" (mkdir d) (setf dirhist (pushr dirhist (cwd))) (chdir d) ) (defun popdir () "Removes the current working directory from the stack, and sets it to the new top element of the stack. Essentially a back-button" (chdir (car (last dirhist))) (setf dirhist (popr dirhist)) ) (defvar blip-dirs '()) (defvar blip-files '()) (defun blip-dir (dir) ;(pushr! blip-dirs dir) (mkdir dir) dir) (defun blip-file (file) (pushr! blip-files file) file) ;;; All of these dirs get created at compile-time. This file must be in the ;;; `blip-self-repo` dir (see below). (defvar blip-root (blip-dir "/depot/synthesis/blip/")) (defvar blip-stor (blip-dir (str-cat blip-root "stor/"))) (defvar blip-tickets (blip-dir (str-cat blip-stor "tickets/"))) (defvar blip-meta (blip-dir (str-cat blip-root "meta/"))) (defvar blip-tmp (blip-dir (str-cat blip-meta "tmp/"))) (defvar blip-du (blip-dir (str-cat blip-meta "disk-usage/"))) (defvar blip-bin (blip-dir (str-cat blip-meta "bin/"))) (defvar blip-env (blip-dir (str-cat blip-meta "env/"))) (defvar blip-in-xform nil) (defvar blip-xform (blip-dir (str-cat blip-meta "xform/"))) (defvar blip-env-stack (blip-file (str-cat blip-env "stack"))) (defvar blip-env-avail (blip-file (str-cat blip-env "avail"))) (defvar blip-env-sha (blip-file (str-cat blip-env "sha"))) (defvar blip-core (str-cat blip-bin "blip")) (defvar blip-logs (blip-dir (str-cat blip-meta "logs/"))) (defvar blip-repos (blip-dir (str-cat blip-stor "repos/"))) (defvar blip-asts (blip-dir (str-cat blip-stor "repo-asts/"))) (defvar blip-repo-meta (blip-dir (str-cat blip-stor "repo-meta/"))) (defvar blip-repos-index (blip-dir (str-cat blip-stor "repos-index/"))) (defvar blip-self-repo (blip-dir (str-cat blip-repos "blip/"))) (defvar blip-code (str-cat blip-self-repo "blip.lisp")) (defvar blip-env-cfg (blip-file (str-cat blip-env "env-cfg.lisp"))) (defvar blip-latest-ix-ver 0) (defvar github-base-url "https://github.com/") (defvar npm-base-url "https://registry.npmjs.com/") (defvar gerrit-base-url "https://cr.joyent.us/p/") (defvar github-api-url "https://api.github.com/") (defvar blip-github-users (blip-file (str-cat blip-repos-index "github-users"))) (defun blip-env-cfg-currentp () (let* ((shanew (sha256-file blip-env-cfg)) (shaold (file-to-form blip-env-sha)) (current (equalp shaold shanew)) ) (if (not current) (form-to-file shanew blip-env-sha) ) current )) (defvar github-repo-blacklist '("natural-earth-vector")) (defmacro! enclose (&rest x) `(list ,@x)) (defun rdep (system) "Return list of Quicklisp packages that use SYSTEM" (let (rdeps) (dolist (s (ql-dist:provided-systems (ql-dist:find-dist "quicklisp")) rdeps) (if (member system (ql-dist:required-systems s) :test #'equal) (push (ql-dist:name s) rdeps))))) (defun github-user-repos-url (user) "Creates github URL that we can use to access a user's repos" (str-cat github-api-url "users/" user "/repos")) (defun repo-spec-to-github-url (spec) (str-cat github-base-url spec ".git")) (defun repo-specs-to-github-urls (specs) (map 'list #'repo-spec-to-github-url specs)) (defun repo-spec-to-gerrit-url (spec) (str-cat gerrit-base-url spec ".git")) (defun repo-specs-to-gerrit-urls (specs) (map 'list #'repo-spec-to-gerrit-url specs)) (defun reload () "Reloads this file" (load blip-code)) (defmacro! is-cmd-verb (s) `(string= verb ,s)) (defun str-to-pov (s) (cond ((string= s "up") :up) ((string= s "down") :down) ((and t) nil))) (defmacro! twice (&body body) `(progn ,@body ,@body)) (defmacro! thrice (&body body) `(progn ,@body ,@body ,@body)) (defmacro! in-index-path-cli (&body body) `(let* ((noun nouns) (path nil) (pov nil) (force nil) (page nil) (alt-idx-type nil)) (setf path (car noun)) (setf noun (cdr noun)) (setf pov (str-to-pov (car noun))) (if pov (setf noun (cdr noun))) (thrice (cond ((string= (car noun) "--page") (setf page (cadr noun)) (setf noun (cddr noun)) ) ((string= (car noun) "--force") (setf force t) (setf noun (cdr noun)) ) ((string= (car noun) "--type") (setf alt-idx-type (string-to-keyword (cadr noun))) (setf noun (cdr noun)) ) )) ,@body )) (defmacro! in-index-nopath-cli (&body body) `(let* ((noun nouns) (pov nil) (force nil) (page nil) (alt-idx-type nil)) (setf pov (str-to-pov (car noun))) (if pov (setf noun (cdr noun))) (thrice (cond ((string= (car noun) "--page") (setf page (cadr noun)) (setf noun (cddr noun)) ) ((string= (car noun) "--force") (setf force t) (setf noun (cdr noun)) ) ((string= (car noun) "--type") (setf alt-idx-type (string-to-keyword (cadr noun))) (setf noun (cdr noun)) ) )) ,@body )) (defun load-top-env () (pushenv (load-env (car (last (file-to-form blip-env-stack))))) ) (defun run-xform (&rest n) (cond ((= 1 (length n) (not (string= (car n) "-v"))) (setf blip-in-xform (car n)) (quiet-load (str-cat blip-xform (car n) ".lisp"))) ((and (= 2 (length n)) (string= (car n) "-v")) (setf blip-in-xform (cadr n)) (load (str-cat blip-xform (cadr n) ".lisp"))) ((and t) (print "Bad args")) ) ) (defmacro! in-ast-ls-cli (&body body) `(let* ((noun nouns) (pref nil) (force nil) (count nil)) (thrice (cond ((string= (car noun) "--count") (setf count t) (setf noun (cdr noun)) ) ((string= (car noun) "--pref") (setf pref (cadr noun)) (setf noun (cddr noun)) ) ((string= (car noun) "--force") (setf force t) (setf noun (cdr noun)) ) )) ,@body )) (defun file-size (path) (if (not path) (return-from file-size nil)) ;;; TODO need to use conditions to handle stat-failures. (let ((stat-obj (sb-posix:stat path))) (if (and stat-obj) (sb-posix:stat-size stat-obj) nil) ) ) (defun compute-disk-usage () "We compute disk usage, by walking our directories. We don't use `du`, because it it will error out if a file gets deleted while it tries to stat it. So, we instead walk the directory and attempt to get the stat-size, dropping any errors if they arise. We do this because other blips may be running and modifying the filesystem and we don't want to get in their way. If this is too slow, we can always run blip in a snapshot of the store (or something)." ;(let* (()) ;) ) (defun print-ln (form) (print form) (format t "~%")) (defun mk-blip-dirs () (map 'nil #'(lambda (d) (mkdir d)) blip-dirs) ) (defun main-impl (argv) (let* ((verb (cadr argv)) (nouns (cddr argv))) (cond ((is-cmd-verb "help") (format t "env-ls ~%") (format t "env-stack ~%") (format t "top-env ~%") (format t "pushenv $env-name ~%") (format t "popenv $env-name ~%") (format t "index-build [--force] [--type $type] ~%") (format t "index-prefix $path-prefix [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "index-suffix $path-suffix [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "index-get-subtree $path [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "index-get-subtree-str $path [up|down] [--fmt $formatter] ~ [--page $pg-num] [--force] [--type $type] ~%") (format t "index-word-count $word [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "index-uniq [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "index-path-depth [up|down] [--page $pg-num] [--force] ~ [--type $type] ~%") (format t "ast-ls-files ~%") (format t "ast-ls-words [--count] [--pref $prefix] [--force] ~%") (format t "ast-ls-fdefs [--count] [--pref $prefix] [--force] ~%") (format t "ast-ls-fbinds [--count] [--pref $prefix] [--force] ~%") (format t "ast-ls-fcalls [--count] [--pref $prefix] [--force] ~%") (format t "ast-parse [--force] ~%") (format t "ast-dump-file $file ~%") (format t "requires-what $filename [--force]") (format t "what-requires $filename [--force]") (format t "bottom-deps [--force]") (format t "top-deps [--force]") (format t "exports-what $filename") (format t "what-exports $funcname") (format t "reconstruct-repo ~%") (format t "github-users ~%") (format t "github-user-add $username ~%") (format t "github-user-rem $username ~%") (format t "github-user-clone $username ~%") (format t "github-user-pull $username ~%") (format t "pull-env ~%") (format t "strap-repo ~%") (format t "eval $lisp-code ~%") ) ((is-cmd-verb "compute-disk-usage") (let ((date (get-universal-time))) ; Exec du on dirs of interest, crunch/agg output into a table ; Save tuple with date and table. ) ) ((is-cmd-verb "show-disk-usage") ) ((is-cmd-verb "env-ls") (cond ((not (blip-env-cfg-currentp)) (quiet-load blip-env-cfg) ) ) (format t "~A~%" (file-to-form blip-env-avail)) ) ((is-cmd-verb "env-stack") (format t "~A~%" (file-to-form blip-env-stack)) ) ((is-cmd-verb "top-env") (load-top-env) (format t "~A~%" (get-env-var 'name)) ) ((is-cmd-verb "pushenv") (let* ((env-name (string-to-symbol (car nouns))) (env nil) ) (if (have-env env-name) (form-to-file (pushr (file-to-form blip-env-stack) env-name) blip-env-stack)) )) ((is-cmd-verb "popenv") (form-to-file (popr (file-to-form blip-env-stack)) blip-env-stack) ) ((is-cmd-verb "index-prefix") (load-top-env) (in-index-path-cli (print-ln (index-prefix path pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-suffix") (load-top-env) (in-index-path-cli (print-ln (index-suffix path pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-word-count") (load-top-env) (in-index-path-cli (print-ln (index-word-count path pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-uniq") (load-top-env) (in-index-nopath-cli (print-ln (index-uniq pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-path-depth") (load-top-env) (in-index-nopath-cli (print-ln (index-path-depth pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-print") (load-top-env) (in-index-nopath-cli (print-ln (index-print pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-build") (load-top-env) (in-index-nopath-cli (index-build :force force :alt-idx-type alt-idx-type)) ) ((is-cmd-verb "index-get-subtree") (load-top-env) (in-index-path-cli (print-ln (index-get-subtree path pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "index-get-subtree-str") (load-top-env) (in-index-path-cli (print-ln (index-get-subtree-str path pov :page page :force force :alt-idx-type alt-idx-type))) ) ((is-cmd-verb "ast-ls-files") (load-top-env) (let ((files (ast-ls-files))) (print-ln (if (car nouns) (length files) files)) ) ) ((is-cmd-verb "ast-ls-fcalls") (load-top-env) (in-ast-ls-cli (print-ln (ast-ls-fcalls count :pref pref :force force))) ) ((is-cmd-verb "ast-ls-fdefs") (load-top-env) (in-ast-ls-cli (print-ln (ast-ls-fdefs count :pref pref :force force))) ) ((is-cmd-verb "ast-ls-words") (load-top-env) (in-ast-ls-cli (print-ln (ast-ls-words count :pref pref :force force))) ) ((is-cmd-verb "ast-ls-fbinds") (load-top-env) (in-ast-ls-cli (print-ln (ast-ls-fbinds count :pref pref :force force))) ) ((is-cmd-verb "ast-parse") (load-top-env) (ast-parse (and (car nouns))) ) ((is-cmd-verb "ast-dump-file") (load-top-env) (print-ln (char-ls-to-str (flatten (load-ast (get-env-var 'repo) (car nouns) (get-env-var 'commit))))) ) ((is-cmd-verb "what-requires") (load-top-env) (print-ln (ast-what-requires (car nouns) :force (cadr nouns))) ) ((is-cmd-verb "requires-what") (load-top-env) (print-ln (ast-requires-what (car nouns) :force (cadr nouns))) ) ((is-cmd-verb "bottom-deps") (load-top-env) (print-ln (ast-bottom-deps :force (car nouns))) ) ((is-cmd-verb "top-deps") (load-top-env) (print-ln (ast-top-deps :force (car nouns))) ) ((is-cmd-verb "requires-what") (load-top-env) (print-ln (ast-requires-what (car nouns) :force (cadr nouns))) ) ((is-cmd-verb "what-exports") (load-top-env) (print-ln (ast-what-exports (car nouns))) ) ((is-cmd-verb "exports-what") (load-top-env) (print-ln (ast-exports-what (car nouns))) ) ((is-cmd-verb "reconstruct-repo") (load-top-env) (reconstruct-repo) ) ((is-cmd-verb "outputs") ) ((is-cmd-verb "jobs") ) ((is-cmd-verb "xform") (run-xform nouns)) ((is-cmd-verb "github-users") (print-ln (file-to-form blip-github-users)) ) ((is-cmd-verb "github-user-add") (let ((users (file-to-form blip-github-users))) (cond ((and (car nouns) (not (member (car nouns) users :test #'equal))) (pushr! users (car nouns)) (form-to-file users blip-github-users) ) ) ) ) ((is-cmd-verb "github-user-rem") (let ((users (file-to-form blip-github-users))) (cond ((and (car nouns) (member (car nouns) users :test #'equal)) (setf users (remove-if #'(lambda (u) (string= u (car nouns))) users)) (form-to-file users blip-github-users) ) ) ) ) ((is-cmd-verb "github-user-clone") (cond ((car nouns) (cache-svc-user-repo-list "github" (car nouns)) (github-clone-user-all-bg (car nouns)) )) ) ((is-cmd-verb "github-user-pull") (cond ((car nouns) (cache-svc-user-repo-list "github" (car nouns)) (github-pull-user-all-bg (car nouns)) )) ) ((is-cmd-verb "pull-env") (load-top-env) (pushdir (str-cat blip-repos (get-env-var 'repo))) (inferior-shell:run/ss (list "git" "pull")) (popdir) ) ((is-cmd-verb "strap-repo") (load-top-env) (strap-git-repo (get-env-var 'repo)) ) ((is-cmd-verb "eval") (if (cadr nouns) (form-to-file (eval (read-from-string (car nouns))) (str-car blip-root (car nouns))) (print (eval (read-from-string (car nouns)))) ) ) ((is-cmd-verb "sleep") (sleep (parse-integer (car nouns))) ) ((and t) (format t "Bad verb!~%") (sb-ext:exit :code -1)) ) )) (defun main () "The main entry point for this program." (let* ((argv sb-ext:*posix-argv*)) (main-impl argv)) ) (defun exec-self () "This function executes this file as a child process" (inferior-shell:run/ss (list blip-core "hi"))) (defun save-core (path) "Saves an executable core to the given path" (progn #+sbcl (let ((fork-result (sb-posix:fork))) (case fork-result (-1 (error "fork failed")) (0 (sb-ext:save-lisp-and-die path :toplevel #'main :executable t)) (otherwise (sb-posix:wait))) (format t "stand-alone core ~a saved~%" path)) #-sbcl (error "not available on this lisp~%") (values))) (defun install () "This saves an executable core to the proper location" (save-core blip-core)) (defun append-ls (ls) (apply #'append ls)) (defclass stack () ((list :initarg :list :initform '()) (last :initarg :last :initform nil) )) (defun stack-list (s) (slot-value s 'list)) (defun stack-pushr (s e) (if (slot-value s 'list) (progn (setf (cdr (slot-value s 'last)) (cons e nil)) (setf (slot-value s 'last) (cdr (slot-value s 'last)))) (progn (setf (slot-value s 'list) (list e)) (setf (slot-value s 'last) (slot-value s 'list))))) (defun stack-last-until (s test) (let ((last (stack-last s)) (list (stack-list s))) (if (funcall test last) (return-from stack-last-until last) ) (tagbody again (setf list (popr list)) (setf last (car (last list))) (if (or (not last) (funcall test last)) (return-from stack-last-until last) ) (go again) ) ) ) (defun stack-last (s) (car (slot-value s 'last))) (defun stack-set-last (s e) (setf (car (slot-value s 'last)) e)) (defun map-if (ls test function) "Maps over a list, ignoring elems that fail a condition" (loop for e in ls when (funcall test e) collect (funcall function e))) (defun head-n (list n) "Get the first n elems of a list" (iter:iter (iter:for x from 1 to n) (iter:for y in list) (iter:collect y))) (defun popl-n (ls n) "Pops the leftmost n elems of a list" (if (< n (length ls)) (progn (iter:iter (iter:for x from 1 to n) (setq ls (cdr ls))) ls) nil)) (defun get-nth-page (ls n pagesz) (head-n (popl-n ls (* n pagesz)) pagesz)) (defmacro! popl-n! (ls n) "Same as popl-n but overwrites the list" `(setf ,ls (popl-n ,ls ,n))) (defun popr-n (ls n) "Pops the rightmost n elems of a list" (if (< n (length ls)) (head-n ls (- (length ls) n)) nil)) (defmacro! popr-n! (ls n) "Same as popr-n but overwrites the list" `(setf ,ls (popr-n ,ls ,n))) (defun popl (ls) "Pops the leftmost elem from the list" (popl-n ls 1)) (defmacro! popl! (ls) "Same as popl but overwrite the list" `(setf ,ls (popl ,ls))) (defun popr (ls) "Pops the rightmost elem from the list" (popr-n ls 1)) (defmacro! popr! (ls) "Same as popr but overwrite the list" `(setf ,ls (popr ,ls))) (defun num-ngrams (n list) "Number of possible ngrams of size `n` for the list" (floor (/ (length list) n))) (defun ngrams-aux (acc n list) (cond ((< (length list) n) (append acc '())) ((>= (length list) n) (ngrams-aux (pushr acc (head-n list n)) n (cdr list))))) (defun ngrams (n list) "Computes all ngrams of a list" (ngrams-aux '() n list)) ;;; Some basic string/char-list conversion funcs. (defun str-to-char-ls (str) "Convert string to character list" (coerce str 'list)) (defun char-ls-to-str (cls) "Convert character list to string" (coerce cls 'string)) ;;; White-space grouping and related boolean tests. (defun is-white-space (c) "Test if a character is white space" (and c (characterp c) (or (CHAR= c #\Space) (CHAR= c #\Tab) (CHAR= c #\Newline)))) (defun white-space-list (acc head tail) "Collect consecutive white-space into a list" (tagbody again (if (is-white-space head) (progn (pushr! acc head) (setf head (car tail)) (setf tail (cdr tail)) (go again)))) (list acc (cons head tail))) (defun test-new-ws () (white-space-list% '() #\Space (str-to-char-ls " abcde "))) (defmacro! advance-scanner-impl () `(progn (setf head (car tail)) (setf tail (cdr tail)))) (defmacro! advance-scanner (&optional times) `(if (not ,times) (advance-scanner-impl) (let ((c 0)) (tagbody again (cond ((< c ,times) (incf c) (advance-scanner-impl) (go again))))))) (defun white-space-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and (listp head) tail) (progn (stack-pushr stack head) (advance-scanner) (go again))) ((and (listp head) (not tail)) (stack-pushr stack head)) ((is-white-space head) (let ((wsls '())) (tagbody wsagain (if (is-white-space head) (progn (pushr! wsls head) (advance-scanner) (go wsagain)) (progn (stack-pushr stack wsls) (go again)) )))) ((and t) (progn (stack-pushr stack head) (advance-scanner) (go again))) )) (stack-list stack)) (defun white-space (ls) "Returns a list that is just like the input, except that all sequences of whitespace are grouped in their own sublists" (white-space-aux (make-instance 'stack) (car ls) (cdr ls))) (defun test-ws () (white-space (str-to-char-ls "123 123 123 123 "))) (defun is-blank (c) "Test if a node is a blank. This equates to being either white-space or a comment" (and (listp c) (or (is-white-space-group c) (is-comment c)))) (defun is-cl-blank (c) "Test if a node is a blank. This equates to being either white-space or a comment" (and (listp c) (or (is-white-space-group c) (is-cl-comment c)))) (defmacro! def-blanks-aux (name test) `(defun ,name (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and (listp head) (not (,test head)) tail) (stack-pushr stack head) (advance-scanner) (go again)) ((and (listp head) (not (,test head)) (not tail)) (stack-pushr stack head) (advance-scanner)) ((,test head) (let ((ls '())) (tagbody blsagain (cond ((,test head) (pushr! ls head) (advance-scanner) (go blsagain))) (stack-pushr stack ls))) (go again)) ((and t) (stack-pushr stack head) (advance-scanner) (go again)) )) (stack-list stack))) (def-blanks-aux blanks-aux is-blank) (def-blanks-aux cl-blanks-aux is-cl-blank) (defun blanks (ls) "Returns the input list, with all blanks in sublists" (blanks-aux (make-instance 'stack) (car ls) (cdr ls))) (defun cl-blanks (ls) "Same as above, but for common lisp blanks" (cl-blanks-aux (make-instance 'stack) (car ls) (cdr ls))) (defun test-blanks () (pipeline (str-to-char-ls "123 /* */ 123 123 123 ") #'cmt-str #'white-space #'blanks)) (defun test-cl-blanks () (pipeline (str-to-char-ls "123 ;my comment ") #'cl-cmt-str #'white-space #'cl-blanks)) ;;; Word grouping and related boolean tests (also used in punctuation) (defun is-punctuation (c) (and c (characterp c) (or (CHAR= c #\() (CHAR= c #\)) (CHAR= c #\{) (CHAR= c #\}) (CHAR= c #\[) (CHAR= c #\]) (CHAR= c #\;) (CHAR= c #\,) (CHAR= c #\.) (CHAR= c #\:) (CHAR= c #\?) (CHAR= c #\<) (CHAR= c #\>) (CHAR= c #\=) (CHAR= c #\+) (CHAR= c #\-) (CHAR= c #\*) (CHAR= c #\/) (CHAR= c #\!) (CHAR= c #\~) (CHAR= c #\%) (CHAR= c #\|) (CHAR= c #\&) (CHAR= c #\^)))) (defun is-non-nestable-punctuation (c) (and (is-punctuation c) (CHAR/= c #\{) (CHAR/= c #\}) (CHAR/= c #\() (CHAR/= c #\)) (CHAR/= c #\[) (CHAR/= c #\]))) (defun is-word-char (c) (and c (characterp c) (not (is-white-space c)) (not (is-punctuation c)))) (defun words-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and (listp head) tail) (stack-pushr stack head) (advance-scanner) (go again)) ((and (listp head) (not tail)) (stack-pushr stack head) (advance-scanner) (go again)) ((characterp head) (cond ((is-word-char head) (let ((ls '())) (tagbody lsagain (cond ((is-word-char head) (pushr! ls head) (advance-scanner) (go lsagain)) ((and t) (stack-pushr stack ls) (go again)))))) ((and t) (stack-pushr stack head) (advance-scanner) (go again)))) ((and t) (stack-pushr stack head) (advance-scanner) (go again) ))) (stack-list stack)) (defun words (ls) (words-aux (make-instance 'stack) (car ls) (cdr ls))) (defun test-words () (pipeline (str-to-char-ls "123 /* */ 123 123 123 ") #'cmt-str #'white-space #'blanks #'words)) ;;; Punctuation grouping and related boolean tests (also used in punctuation) (defun punctuations-list (acc head tail) (if (is-non-nestable-punctuation head) (punctuations-list (pushr acc head) (car tail) (cdr tail)) (list acc (cons head tail)))) (defun punctuations-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and (listp head) tail) (stack-pushr stack head) (advance-scanner) (go again)) ((and (listp head) (not tail)) (stack-pushr stack head) (advance-scanner) (go again)) ((characterp head) (cond ((is-non-nestable-punctuation head) (let ((ls '())) (tagbody lsagain (cond ((is-non-nestable-punctuation head) (pushr! ls head) (advance-scanner) (go lsagain)) ((and t) (stack-pushr stack ls) (go again)))))) ((and t) (stack-pushr stack head) (advance-scanner) (go again)))))) (stack-list stack) ) (defun punctuations (ls) (punctuations-aux (make-instance 'stack) (car ls) (cdr ls))) (defun test-puncts () (pipeline (str-to-char-ls "123 (1 2 3); 1,2,3 /* */ 123 123 123 ") #'cmt-str #'white-space #'blanks #'words #'punctuations)) (defun nestables-aux (acc head tail fin) (cond ((and head (listp head)) (nestables-aux (pushr acc head) (car tail) (cdr tail) fin)) ((and (not head) (not tail)) (values acc tail)) ((or (and fin head (CHAR= head fin)) (and head (not tail))) (values (pushr acc head) tail)) ((characterp head) (cond ((and acc (CHAR= head #\()) (multiple-value-bind (nacc ntail) (nestables-aux '() head tail #\)) (nestables-aux (pushr acc nacc) (car ntail) (cdr ntail) fin) ) ) ((and acc (CHAR= head #\{)) (multiple-value-bind (nacc ntail) (nestables-aux '() head tail #\}) (nestables-aux (pushr acc nacc) (car ntail) (cdr ntail) fin) ) ) ((and acc (CHAR= head #\[)) (multiple-value-bind (nacc ntail) (nestables-aux '() head tail #\]) (nestables-aux (pushr acc nacc) (car ntail) (cdr ntail) fin) ) ) ((and t) (nestables-aux (pushr acc head) (car tail) (cdr tail) fin) ))))) (defun nestables (ls) (nestables-aux '() (car ls) (cdr ls) nil)) (defun test-nestables () (nestables (str-to-char-ls "fn (a, b, c) { a e; a e; a e = c; a e = c && b || {}; cb();} more() { stuff }; foo(); foo(); foo();"))) (defun nestable-assert (char head) (cond ((CHAR= char #\() (assert (and head (CHAR/= #\} head) (CHAR/= #\] head)))) ((CHAR= char #\{) (assert (and head (CHAR/= #\) head) (CHAR/= #\] head)))) ((CHAR= char #\[) (assert (and head (CHAR/= #\) head) (CHAR/= #\} head)))))) (defun is-empty-nestable (ls) (let ((f (car ls)) (l (cadr ls))) (and (= 2 (length ls)) (and (characterp f) (characterp l) (or (and (CHAR= f #\() (CHAR= l #\))) (and (CHAR= f #\{) (CHAR= l #\})) (and (CHAR= f #\[) (CHAR= l #\]))))))) (defun is-empty-str (ls) (let ((f (car ls)) (l (cadr ls))) (and (= 2 (length ls)) (and (characterp f) (character l) (or (and (CHAR= f #\') (CHAR= l #\')) (and (CHAR= f #\") (CHAR= l #\"))))))) ; TODO: return a pair of consumed and tail (defmacro! is-bcmt-end () `(and (CHAR= head #\*) (CHAR= (car tail) #\/))) (defmacro! is-lcmt-end () `(CHAR= head #\Newline)) (defmacro! str-tagbody (quote tag) `(let ((ls '()) (nq 0)) (tagbody ,tag (cond ((and (CHAR/= head ,quote) (not tail)) (pushr! ls head)) ((CHAR= head ,quote) (incf nq) (pushr! ls head) (advance-scanner) (if (< nq 2) (go ,tag))) ((CHAR= head #\\) (pushr! ls head (car tail)) (advance-scanner 2) (go ,tag) ) ((not (CHAR= head #\\)) (pushr! ls head) (advance-scanner) (go ,tag)))) (stack-pushr stack ls) (go again))) (defun char-eq-any (char charls) (apply #'fn-or (map 'list #'(lambda (e) (CHAR= char e)) charls)) ) (defun is-regex (stack) "We need to check the preceding character to determine if we are (likely) looking at a regex literal or instead of a division. If we are preceded by any of the following, we assume we are looking at the start of a regex: (,=:[!&|?{}; Clearly we can't handle regexes that are expressed as `if (cond) return /rgx/g;`" (let ((last-glyph (stack-last-until stack #'(lambda (e) (not (is-white-space e)))))) (char-eq-any last-glyph (str-to-char-ls "(,=:[!&|?{};")) ) ) (defun cmt-str-regex-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and head (not tail)) (stack-pushr stack head)) ((and (CHAR= head #\/) (CHAR= (car tail) #\*)) (let ((bcls '())) (tagbody bcmtagain (cond ((and (not (is-bcmt-end)) (not tail)) (pushr! bcls head) (advance-scanner)) ((and (is-bcmt-end)) (pushr! bcls #\* #\/) (advance-scanner 2)) ((not (is-bcmt-end)) (pushr! bcls head) (advance-scanner) (go bcmtagain)) ) (stack-pushr stack bcls) (go again) ) )) ((and (CHAR= head #\/) (CHAR= (car tail) #\/)) (let ((lcls '())) (tagbody lcmtagain (cond ((and (not (is-lcmt-end)) (not tail)) (pushr! lcls head) (advance-scanner)) ((and (is-lcmt-end)) (pushr! lcls #\Newline) (advance-scanner)) ((not (is-lcmt-end)) (pushr! lcls head) (advance-scanner) (go lcmtagain)) ) (stack-pushr stack lcls) (go again) ) )) ((CHAR= head #\") (str-tagbody #\" dqagain) ) ((CHAR= head #\') (str-tagbody #\' sqagain) ) ((and (CHAR= head #\/) (is-regex stack)) (str-tagbody #\/ rgxagain) ) ((and t) (stack-pushr stack head) (advance-scanner) (go again) ) ) ) (stack-list stack) ) (defun cmt-str-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and head (not tail)) (stack-pushr stack head)) ((and (CHAR= head #\/) (CHAR= (car tail) #\*)) (let ((bcls '())) (tagbody bcmtagain (cond ((and (not (is-bcmt-end)) (not tail)) (pushr! bcls head) (advance-scanner)) ((and (is-bcmt-end)) (pushr! bcls #\* #\/) (advance-scanner 2)) ((not (is-bcmt-end)) (pushr! bcls head) (advance-scanner) (go bcmtagain)) ) (stack-pushr stack bcls) (go again) ) )) ((and (CHAR= head #\/) (CHAR= (car tail) #\/)) (let ((lcls '())) (tagbody lcmtagain (cond ((and (not (is-lcmt-end)) (not tail)) (pushr! lcls head) (advance-scanner)) ((and (is-lcmt-end)) (pushr! lcls #\Newline) (advance-scanner)) ((not (is-lcmt-end)) (pushr! lcls head) (advance-scanner) (go lcmtagain)) ) (stack-pushr stack lcls) (go again) ) )) ((CHAR= head #\") (str-tagbody #\" dqagain) ) ((CHAR= head #\') (str-tagbody #\' sqagain) ) ((and t) (stack-pushr stack head) (advance-scanner) (go again) ) ) ) (stack-list stack) ) (defun cl-cmt-str-aux (stack head tail) (tagbody again (cond ((and (not head) (not tail)) ) ((and head (not tail)) (stack-pushr stack head)) ((CHAR= head #\;) (let ((lcls '())) (tagbody lcmtagain (cond ((and (not (is-lcmt-end)) (not tail)) (pushr! lcls head) (advance-scanner)) ((and (is-lcmt-end)) (pushr! lcls #\Newline) (advance-scanner)) ((not (is-lcmt-end)) (pushr! lcls head) (advance-scanner) (go lcmtagain)) ) (stack-pushr stack lcls) (go again) ) )) ((CHAR= head #\") (str-tagbody #\" dqagain) ) ((and t) (stack-pushr stack head) (advance-scanner) (go again) ) ) ) (stack-list stack) ) (defun cmt-str (char-ls) (cmt-str-aux (make-instance 'stack) (car char-ls) (cdr char-ls))) (defun cmt-str-regex (char-ls) (cmt-str-regex-aux (make-instance 'stack) (car char-ls) (cdr char-ls))) (defun cl-cmt-str (char-ls) (cl-cmt-str-aux (make-instance 'stack) (car char-ls) (cdr char-ls))) ; When called this returns a list containing all chars from /* to */ and a new ; tail. (defun bcmt-list (acc head tail) (let ((is-end (and (CHAR= head #\*) (CHAR= (car tail) #\/)))) (cond ((and (not is-end) (not tail)) (progn (list (pushr acc head) tail))) ((and is-end) (progn (list (pushr acc #\* #\/) (cdr tail)))) ((not is-end) (progn (bcmt-list (pushr acc head) (car tail) (cdr tail))))))) (defun lcmt-list (acc head tail) (let ((is-end (or (CHAR= head #\Newline)))) (cond ((and (not is-end) (not tail)) (progn (list (pushr acc head) tail))) ((and is-end) (progn (list (pushr acc #\Newline) (cdr tail)))) ((not is-end) (progn (lcmt-list (pushr acc head) (car tail) (cdr tail))))))) ; Just like bcmt-list above, we return a pair. The string in list form and the ; new tail. We leave the escape-sequences intact. (defmacro! str-list-body (quote fname) `(cond ((is-empty-str acc) (progn (list acc (cons head tail)))) ((and (CHAR/= head ,quote) (not tail)) (progn (list (pushr acc head tail)))) ((CHAR= head ,quote) (progn (list (pushr acc head) tail))) ((CHAR= head #\\) ; Add the escape to list, call self on thing after (let ((nacc (pushr acc head (car tail)))) (progn (,fname nacc (cadr tail) (cddr tail))))) ((not (CHAR= head #\\)) (progn (,fname (pushr acc head) (car tail) (cdr tail)))))) (defun dquote-str-list (acc head tail) (str-list-body #\" dquote-str-list)) (defun squote-str-list (acc head tail) (str-list-body #\' squote-str-list)) (defun is-comment (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (characterp (cadr ls)) (or (and (CHAR= #\/ (car ls)) (CHAR= #\* (cadr ls))) (and (CHAR= #\/ (car ls)) (CHAR= #\/ (cadr ls))))) t) )) (defun is-cl-comment (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (CHAR= #\; (car ls))) t) )) (defun is-str (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (or (CHAR= #\" (car ls)) (CHAR= #\' (car ls)))) t) )) (defun drop-str-quotes (ls) (progn (assert (is-str ls)) (head-n (cdr ls) (- (length ls) 2)))) (defun undrop-str-quotes (ls) (pushr (pushl ls #\") #\")) (defun is-paren-group (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (CHAR= #\( (car ls))) t) )) (defun is-curly-group (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (CHAR= #\{ (car ls))) t) )) (defun is-bracket-group (ls) (cond ((not (listp ls)) nil) ((< (length ls) 2) nil) ((and (characterp (car ls)) (CHAR= #\[ (car ls))) t) )) (defun is-nestable (ls) (and (listp ls) (or (is-paren-group ls) (is-curly-group ls) (is-bracket-group ls)))) (defun match-lists (l1 l2) (equal l1 l2)) (defun match-str-list (s ls) (equal (str-to-char-ls s) ls)) (defun is-ctl-struct (ls) (or (match-str-list "if" ls) (match-str-list "for" ls) (match-str-list "while" ls) (match-str-list "return" ls))) (defun is-js-ctl-struct (ls) (or (is-ctl-struct ls) (match-str-list "try" ls) (match-str-list "catch" ls))) (defun is-word-group (ls) (and (listp ls) (is-word-char (car ls)) (not (is-str ls)))) (defmacro! validate-x (name test) `(defun ,name (ls) (and (listp ls) (= 1 (length (remove-duplicates (map 'list #',test ls)))))) ) (validate-x validate-word is-word-char) (defun is-c-func-name (ls) (and (is-word-group ls) (not (is-ctl-struct ls)))) (defun is-js-func-name (ls) (and (is-word-group ls) (not (is-js-ctl-struct ls)))) (defun is-white-space-group (ls) (and (listp ls) ls (is-white-space (car ls)))) (validate-x validate-ws is-white-space) (defun validate-ws (ls) (and (listp ls) (= 1 (length (remove-duplicates (map 'list #'is-white-space ls)))))) (defun is-blank-group (ls) (and (listp ls) ls (or (is-white-space-group (car ls)) (is-comment (car ls))))) (validate-x validate-blank (lambda (e) (or (is-white-space-group e) (is-comment e)))) (defun is-punctuation-group (ls) (and (listp ls) ls (not (is-nestable ls)) (is-punctuation (car ls)))) ;;; TODO need to identify nestables from inner context (validate-x validate-punc (lambda (e) (and ;(not (is-nestable e)) (is-punctuation e)))) (defun match-punc-ls (s ls) (and (is-punctuation-group ls) (equal (str-to-char-ls s) ls))) (defun match-any-puncs-ls (ss ls) (let ((c ss)) (tagbody again (cond ((not c) (return-from match-any-puncs-ls nil)) ((match-punc-ls (car c) ls) (return-from match-any-puncs-ls t)) ((and t) (setf c (cdr c)) (go again)) ) ) ) ) (defun is-stmt-aux (ls count) (cond ((match-punc-ls ";" (car ls)) count) ((and ls) (is-stmt-aux (cdr ls) (+ count 1))) ((and t) nil) )) (defun is-stmt (ls) (is-stmt-aux ls 0)) (defun is-obj-lit-rval-aux (ls count) (cond ((or (and (characterp (car ls)) (CHAR= #\} (car ls))) (match-punc-ls "," (car ls))) count) ((and ls) (is-obj-lit-rval-aux (cdr ls) (+ count 1))) ((and t) nil) )) (defun is-obj-lit-rval (ls) (is-obj-lit-rval-aux ls 0)) (defun is-stmt-group (ls) (match-punc-ls ";" (last ls))) (defun is-colon-group (ls) (and (is-punctuation-group ls) (= 1 (length ls)) (CHAR= #\: (car ls)))) (defun is-eq-group (ls) (and (is-punctuation-group ls) (= 1 (length ls)) (CHAR= #\= (car ls)))) (defun is-binding (ls) (or (is-colon-group ls) (is-eq-group ls))) (defun is-nestable-end (c) (and (characterp c) (or (CHAR= c #\)) (CHAR= c #\}) (CHAR= c #\])))) ;; So the function call is over if we are the end of a list, at a punctuation ;; group, at a closing )}], or at a paren/bracket group. It is possible to do: ;; foo()() and foo()[0] ;; ;; If foo returns a function or an array. (defun is-fcall-end (ls) (or (not ls) (is-punctuation-group ls) (is-nestable-end ls) (or (is-paren-group ls) (is-bracket-group ls)) )) (defun is-js-fcall-end (ls) (if (or (not ls) (is-punctuation-group ls) (is-nestable-end ls) (or (is-paren-group ls) (is-bracket-group ls))) 0 nil )) ;; Same conditions for jsarr as for fcall. (defun is-jsarr-end (ls) (is-fcall-end ls)) (defun is-json-value (ls) (or (is-word-group ls) (is-str ls) (is-nestable ls))) (defun is-kvp-end (ls) (is-json-value ls)) (defun is-c-fdef-end (ls) (is-curly-group ls)) (defun is-fcall (ls) (and (listp ls) (cond ((= (length ls) 2) (and (is-c-func-name (car ls)) (is-paren-group (cadr ls)))) ((= (length ls) 3) (and (is-c-func-name (car ls)) (is-blank-group (cadr ls)) (is-paren-group (caddr ls)))) ((and t) nil)))) (defun is-js-word-or-fcall-or-arr (ls) (or (is-js-fcall ls) (is-js-arr ls) (is-word-group ls)) ) (defun is-js-word-or-arr (ls) (or (is-js-arr ls) (is-word-group ls)) ) (defun is-js-word-or-str (ls) (or (is-str ls) (is-word-group ls)) ) (defun is-dot (ls) (and (is-punctuation-group ls) (= 1 (length ls)) (CHAR= #\. (car ls))) ) (defun is-word-arr-fcall-vbind-fbind (ls) (or (is-js-fcall ls) (is-word-group ls) (is-js-arr ls) (is-js-var-binding ls) (is-js-fdef-binding ls)) ) (defun is-jsarr (ls) (and (listp ls) (cond ((= (length ls) 2) (and (is-c-func-name (car ls)) (is-bracket-group (cadr ls)))) ((= (length ls) 3) (and (is-c-func-name (car ls)) (is-blank-group (cadr ls)) (is-bracket-group (caddr ls)))) ((and t) nil)))) (defun is-op (ls) ; Use CHAR= instead of match-str to deal with empty statements `;;...` (and (is-punctuation-group ls) (and (not (CHAR= (car ls) #\;)) (not (CHAR= (car ls) #\,))))) (defun c-what-is (ls) (cond ((is-op ls) 'operator) ((is-c-fdef ls) 'function-definition) ((is-fcall ls) 'function-call) ((is-jsarr ls) 'js-array) ((is-word-group ls) 'word) ((is-comment ls) 'comment) ((is-str ls) 'string) ((is-punctuation-group ls) 'punctuation) ((is-blank-group ls) 'blank) ((is-white-space-group ls) 'whitespace) ((characterp ls) 'character) ((is-bracket-group ls) 'brackets) ((is-paren-group ls) 'parens) ((is-curly-group ls) 'curlies) ((and t) 'other) )) (defun js-what-is (ls) (cond ((is-op ls) 'operator) ((is-js-fdef ls) 'function-definition) ((is-js-fcall ls) 'function-call) ((is-jsarr ls) 'js-array) ((is-word-group ls) 'word) ((is-comment ls) 'comment) ((is-str ls) 'string) ((is-punctuation-group ls) 'punctuation) ((is-blank-group ls) 'blank) ((is-white-space-group ls) 'whitespace) ((characterp ls) 'character) ((is-bracket-group ls) 'brackets) ((is-paren-group ls) 'parens) ((is-curly-group ls) 'curlies) ((and t) 'other) )) (defun js-fcall-name-eq (fcall name) (and (is-js-fcall fcall) (match-str-list name (get-fcall-name fcall)))) (defun js-vbind-name-eq (vbind name) (and (is-js-var-binding vbind) (match-str-list name (get-js-vbind-name vbind)))) (defun js-obj-key-eq (obj-lit-rec name) (and (is-js-obj-lit-rec obj-lit-rec) (match-str-list name (get-js-obj-key obj-lit-rec))) ) (defun is-c-fdef (ls) (and (listp ls) (cond ((= (length ls) 3) (and (is-c-func-name (car ls)) (is-paren-group (cadr ls)) (is-curly-group (caddr ls)))) ((= (length ls) 4) (and (is-c-func-name (car ls)) (or (and (is-paren-group (cadr ls)) (is-blank-group (caddr ls)) (is-curly-group (cadddr ls))) (and (is-blank-group (cadr ls)) (is-paren-group (caddr ls)) (is-curly-group (cadddr ls)))))) ((= (length ls) 5) (and (is-c-func-name (car ls)) (is-blank-group (cadr ls)) (is-paren-group (caddr ls)) (is-blank-group (cadddr ls)) (is-curly-group (car (cddddr ls))))) ((and t) nil)))) (defun is-js-fdef (ls) (and ls (listp ls) (js-fdefp (car ls) (cdr ls)))) (defun is-js-curly-ctl-stmt (ls) (and ls (listp ls) (js-curly-ctl-stmtp (car ls) (cdr ls)))) (defun is-js-do-while-stmt (ls) (and ls (listp ls) (js-do-while-stmtp (car ls) (cdr ls)))) (defun is-ctl-word (ls) (or (match-str-list "if" ls) (match-str-list "while" ls) (match-str-list "for" ls) (match-str-list "switch" ls))) (defun is-js-flat-ctl-stmt (ls) (and ls (listp ls) (not (is-js-curly-ctl-stmt ls)) (is-ctl-word (car ls)))) (defun is-js-any-ctl-stmt (ls) (or (is-js-curly-ctl-stmt ls) (is-js-flat-ctl-stmt ls))) (defun is-js-fdef-binding (ls) (and ls (listp ls) (js-fdef-bindingp (car ls) (cdr ls)))) (defun is-js-var-binding (ls) (and ls (listp ls) (not (is-js-fdef-binding ls)) (or (is-word-group (car ls)) (is-js-arr (car ls))) (or (is-eq-group (cadr ls)) (is-eq-group (caddr ls))))) (defun is-js-binding (ls) (and ls (listp ls) (or (is-js-fdef-binding ls) (is-js-var-binding ls)))) (defun is-js-obj-lit-rec (ls) (and ls (listp ls) (or (is-word-group (car ls)) (is-str (car ls))) (or (is-colon-group (cadr ls)) (is-eq-group (caddr ls))) )) (defun is-js-fcall (ls) (and (listp ls) (not (is-js-fdef ls)) (js-fcallp (car ls) (cdr ls)))) (defun is-js-arr (ls) (and (listp ls) (js-arrp (car ls) (cdr ls)))) (defun is-c-fcall (ls) (and (listp ls) (is-c-func-name (car ls)) (is-fcall ls))) (defun is-c-fdef-or-fcall (ls) (or (is-c-fdef ls) (is-c-fcall ls))) (defun is-js-fdef-or-fcall (ls) (or (is-js-fdef ls) (is-js-fcall ls))) (defun is-js-indexable-funcs (ls) (or (is-js-fdef ls) (is-js-fcall ls) (is-js-fdef-binding ls))) (defun is-js-indexable-conds (ls) (or (is-js-indexable-funcs ls) (is-js-any-ctl-stmt ls) (is-js-do-while-stmt ls))) (defun is-js-indexable-binds (ls) (or (is-js-fdef-binding ls) (is-js-var-binding ls) (is-js-obj-lit-rec ls) (is-js-mbr-chain-word-bind ls) (is-js-fdef ls) ) ) (defmacro! def-5-state-match (fname test-slot-1 test-slot-2-opt test-slot-2 test-slot-3-opt test-slot-3) `(defun ,fname (head tail s) (case s (0 (if (,test-slot-1 head) (,fname (car tail) (cdr tail) 1) nil)) (1 (cond ((,test-slot-2-opt head) (,fname (car tail) (cdr tail) 2)) ((,test-slot-2 head) (,fname (car tail) (cdr tail) 3)) ((and t) nil))) (2 (cond ((,test-slot-2 head) (,fname (car tail) (cdr tail) 3)) ((and t) nil))) (3 (cond ((,test-slot-3-opt head) (,fname (car tail) (cdr tail) 4)) ((,test-slot-3 head) (,fname (car tail) (cdr tail) 5)) ((and t) nil))) (4 (cond ((,test-slot-3 head) (and t)) ((and t) nil))) (5 (and t))))) (def-5-state-match fcallp is-js-func-name is-blank-group is-paren-group is-blank-group is-fcall-end) (def-5-state-match fdefp is-js-func-name is-blank-group is-paren-group is-blank-group is-c-fdef-end) ;(def-5-state-match js-fdefp is-js-func-name is-blank-group is-paren-group ; is-blank-group is-c-fdef-end) (def-5-state-match jsarrp is-js-func-name is-blank-group is-bracket-group is-blank-group is-jsarr-end) (def-5-state-match json-kv-pair-p is-str is-blank-group is-colon-group is-blank-group is-kvp-end) (defun count-n-wsgroup (n ls) (let ((nls (head-n ls n))) (count-if #'is-white-space-group nls))) (defun count-n-blankgroup (n ls) (let ((nls (head-n ls n))) (count-if #'is-blank-group nls))) ;;; Function-defining macro. The macro does following: ;;; Groups something like an fcall, jsarr, or kvp starting at head. Returns a tuple of: ;;; (grouped-$thing, new-head, new-tail) (defmacro! group-2-to-3 (name fletnm fletif fletcall) `(defun ,name (head tail agg) (let ((ws2 (count-n-blankgroup 2 (pushl tail head))) (ws3 (count-n-blankgroup 3 (pushl tail head)))) (flet ((,fletnm (x) (if (,fletif x) (,fletcall x) x))) (cond ((= ws2 0) (list (map 'list #',fletnm (head-n (pushl tail head) 2)) (car (popl-n tail 1)) (popl-n tail 2))) ((= ws3 1) (list (map 'list #',fletnm (head-n (pushl tail head) 3)) (car (popl-n tail 2)) (popl-n tail 3))) ((and t) (assert (and nil))) ))))) (group-2-to-3 group-fcall fcalls-if-group is-paren-group fcalls) (group-2-to-3 group-jsarr jsarrs-if-group is-bracket-group jsarrs) (defmacro! group-3-to-5 (name fletnm fletif fletcall) `(defun ,name (head tail agg) (let ((ws3 (count-n-blankgroup 3 (pushl tail head))) (ws4 (count-n-blankgroup 4 (pushl tail head))) (ws5 (count-n-blankgroup 5 (pushl tail head))) ) (flet ((,fletnm (x) (if (,fletif x) (,fletcall x) x))) (cond ((= ws3 0) (list (map 'list #',fletnm (head-n (pushl tail head) 3)) (car (popl-n tail 2)) (popl-n tail 3))) ((= ws4 1) (list (map 'list #',fletnm (head-n (pushl tail head) 4)) (car (popl-n tail 3)) (popl-n tail 4))) ((= ws5 2) (list (map 'list #',fletnm (head-n (pushl tail head) 5)) (car (popl-n tail 4)) (popl-n tail 5))) ((and t) ;Never get here (assert (and nil))) ))))) (group-3-to-5 group-fdef fdefs-if-group is-nestable c-fdefs) (group-3-to-5 group-json-kvp kvp-if-group is-nestable json-kvp) (defun get-c-fdef-triple (head tail agg) (group-fdef head tail agg)) ; Walk the list. Call itself on every is-nestable list along the way. (defun fcalls-aux (acc head tail) (cond ((fcallp head tail 0) (let* ((agg (group-fcall head tail '())) (nacc (pushr acc (car agg))) (nhead (cadr agg)) (ntail (caddr agg))) (progn (fcalls-aux nacc nhead ntail)))) ((and (listp head) (is-nestable head)) (progn (let ((nacc (pushr acc (fcalls head))) (nhead (car tail)) (ntail (cdr tail))) (fcalls-aux nacc nhead ntail)))) ((and (characterp head) tail) (progn (fcalls-aux (pushr acc head) (car tail) (cdr tail)))) ((and tail) (progn (fcalls-aux (pushr acc head) (car tail) (cdr tail)))) ((and head (not tail)) (progn (pushr acc head))) ((and (not head)) (progn acc)) )) ; Function call: name pgroup [ws] [semi | comma | end-group | operator] (defun fcalls (ls) (fcalls-aux '() (car ls) (cdr ls))) (defun xform-fcall-pgroup (fc cb) (if (= (length fc) 2) (list (car fc) (funcall cb (cadr fc))) (list (car fc) (cadr fc) (funcall cb (caddr fc))) )) (defun xform-js-arr-bgroup (fc cb) (if (= (length fc) 2) (list (car fc) (funcall cb (cadr fc))) (list (car fc) (cadr fc) (funcall cb (caddr fc))) )) (defun xform-c-fdef-pgroup (fd cb) (cond ((= (length fd) 3) (list (car fd) (funcall cb (cadr fd)) (caddr fd))) ((and (= (length fd) 4) (is-blank-group (cadr fd))) (list (car fd) (cadr fd) (funcall cb (caddr fd)) (funcall cb (cadddr fd)))) ((and (= (length fd) 4) (is-blank-group (caddr fd))) (list (car fd) (funcall cb (cadr fd)) (caddr fd) (funcall cb (cadddr fd)))) ((= (length fd) 5) (list (car fd) (cadr fd) (funcall cb (caddr fd)) (cadddr fd) (car (cddddr fd)))))) (defun xform-c-fdef-cgroup (fd cb) (cond ((= (length fd) 3) (list (car fd) (cadr fd) (funcall cb (caddr fd)))) ((= (length fd) 4) (list (car fd) (cadr fd) (caddr fd) (funcall cb (cadddr fd)))) ((= (length fd) 5) (list (car fd) (cadr fd) (caddr fd) (cadddr fd) (funcall cb (car (cddddr fd))))))) (defun xform-js-fdef-cgroup-aux (acc head tail cb) (cond ((not head) acc) ((is-curly-group head) (xform-js-fdef-cgroup-aux (pushr acc (funcall cb head)) (car tail) (cdr tail) cb)) ((not (is-curly-group head)) (xform-js-fdef-cgroup-aux (pushr acc head) (car tail) (cdr tail) cb)) )) (defun xform-js-vbind-rval-aux (acc head tail cb) (cond ((not head) acc) ((is-eq-group head) (xform-js-vbind-rval-aux (pushr acc head (funcall cb tail)) (cadr tail) (cddr tail) cb)) ((not (is-eq-group head)) (xform-js-vbind-rval-aux (pushr acc head) (car tail) (cdr tail) cb)) )) (defun xform-js-curly-ctl-stmt-cgroup-aux (acc head tail cb) (cond ((not head) acc) ((is-curly-group head) (xform-js-curly-ctl-stmt-cgroup-aux (pushr acc (funcall cb head)) (car tail) (cdr tail) cb)) ((not (is-curly-group head)) (xform-js-curly-ctl-stmt-cgroup-aux (pushr acc head) (car tail) (cdr tail) cb)) )) (defun xform-js-do-while-cgroup-aux (acc head tail cb) (cond ((not head) acc) ((is-curly-group head) (xform-js-do-while-cgroup-aux (pushr acc (funcall cb head)) (car tail) (cdr tail) cb)) ((not (is-curly-group head)) (xform-js-do-while-cgroup-aux (pushr acc head) (car tail) (cdr tail) cb)) )) (defun xform-js-fdef-pgroup-aux (acc head tail cb) (cond ((not head) acc) ((is-paren-group head) (xform-js-fdef-pgroup-aux (pushr acc (funcall cb head)) (car tail) (cdr tail) cb)) ((not (is-curly-group head)) (xform-js-fdef-pgroup-aux (pushr acc head) (car tail) (cdr tail) cb)) )) (defun xform-js-fdef-cgroup (fd cb) (xform-js-fdef-cgroup-aux '() (car fd) (cdr fd) cb)) (defun xform-js-vbind-rval (fd cb) (xform-js-vbind-rval-aux '() (car fd) (cdr fd) cb)) (defun xform-js-fdef-pgroup (fd cb) (xform-js-fdef-pgroup-aux '() (car fd) (cdr fd) cb)) (defun xform-js-curly-ctl-stmt-cgroup (cstmt cb) (xform-js-curly-ctl-stmt-cgroup-aux '() (car cstmt) (cdr cstmt) cb)) (defun xform-js-do-while-cgroup (cstmt cb) (xform-js-do-while-cgroup-aux '() (car cstmt) (cdr cstmt) cb)) (defun c-fdefs-aux (acc head tail) (cond ((fdefp head tail 0) (let* ((agg (get-c-fdef-triple head tail '())) (nacc (pushr acc (car agg))) (nhead (cadr agg)) (ntail (caddr agg))) (progn (c-fdefs-aux nacc nhead ntail)))) ((is-fcall head) (let* ((nacc (pushr acc (xform-fcall-pgroup head #'c-fdefs)))) (c-fdefs-aux nacc (car tail) (cdr tail)))) ((and (listp head) (is-nestable head)) (let ((nacc (pushr acc (c-fdefs head)))) (progn (c-fdefs-aux nacc (car tail) (cdr tail))))) ((or (and (characterp head) tail) tail) (progn (c-fdefs-aux (pushr acc head) (car tail) (cdr tail)))) ((and head (not tail)) (progn (pushr acc head))) ((and (not head)) (progn acc)) )) ; Function def: name pgroup cgroup [name != if | for | while] (defun c-fdefs (ls) (c-fdefs-aux '() (car ls) (cdr ls))) (defun finite-match-aux (head tail match-fns count) (let* ((pair (car match-fns)) (type (car pair)) (func (cadr pair)) (match (if (and func) (funcall func head) nil)) (cmatch (if (and func) (funcall func (cons head tail)) nil)) (cdroff cmatch) (caroff cdroff) ) (cond ((not match-fns) count) ((and (equal type :m) (not match)) nil) ((and (equal type :mc) (not cmatch)) nil) ((and (equal type :m) match) (finite-match-aux (car tail) (cdr tail) (cdr match-fns) (+ count 1))) ((and (equal type :mc) cmatch) (finite-match-aux (nth caroff tail) (nthcdr cdroff tail) (cdr match-fns) (+ count cmatch))) ((and (equal type :o) match) (finite-match-aux (car tail) (cdr tail) (cdr match-fns) (+ count 1))) ((and (equal type :oc) cmatch) (finite-match-aux (nth caroff tail) (nthcdr cdroff tail) (cdr match-fns) (+ count cmatch))) ((and (equal type :o) (not match)) (finite-match-aux head tail (cdr match-fns) count)) ((and (equal type :oc) (not cmatch)) (finite-match-aux head tail (cdr match-fns) count)) ((and t) ;should never get here (assert nil)) ))) (defun finite-match (ls match-fns) (finite-match-aux (car ls) (cdr ls) match-fns 0)) (defun finite-repeating-match (ls rmatch-fns ematch-fns &optional zero_plus) "Just like finite-match, except we match rmatch-fns in a loop, until it returns nil. We then run ematch-fns on the part that rmatch failed to match. If rmatch succeeds, this function returns t, otherwise nil" (let ((curls ls) (total_size 0) (current_rsize 0) (current_esize 0) (rmatched 0)) (tagbody again (setf current_rsize (finite-match curls rmatch-fns)) (cond ((and current_rsize) (incf total_size current_rsize) (setf curls (nthcdr current_rsize curls)) (incf rmatched) (go again)) ((not current_rsize) (setf current_esize (finite-match curls ematch-fns)) (if (or (not current_esize) (and (= rmatched 0) (not zero_plus))) (setf total_size nil) (incf total_size current_esize) ))) ) total_size ) ) (defun js-else-if-stmtp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (match-str-list "else" x))) (list :o #'is-blank-group) (list :m #'is-js-any-ctl-stmt) ))) (defun js-curly-else-stmtp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (match-str-list "else" x))) (list :o #'is-blank-group) (list :m #'is-js-any-ctl-stmt) (list :o #'is-blank-group) (list :m #'is-curly-group) ))) (defun js-curly-ctl-stmtp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (or (match-str-list "if" x) (match-str-list "while" x) (match-str-list "for" x) (match-str-list "switch" x)))) (list :o #'is-blank-group) (list :m #'is-paren-group) (list :o #'is-blank-group) (list :m #'is-curly-group)))) (defun js-flat-ctl-stmtp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (or (match-str-list "if" x) (match-str-list "while" x) (match-str-list "for" x) (match-str-list "switch" x)))) (list :o #'is-blank-group) (list :m #'is-paren-group) (list :o #'is-blank-group) (list :mc #'is-stmt)))) (defun js-do-while-stmtp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (match-str-list "do" x))) (list :o #'is-blank-group) (list :m #'is-curly-group) (list :o #'is-blank-group) (list :m #'(lambda (x) (match-str-list "while" x))) (list :o #'is-blank-group) (list :m #'is-paren-group) (list :o #'is-blank-group) ))) (defun js-fdefp (head tail) (finite-match (cons head tail) (list (list :m #'(lambda (x) (match-str-list "function" x))) (list :o #'is-blank-group) (list :o #'is-js-func-name) (list :o #'is-blank-group) (list :m #'is-paren-group) (list :o #'is-blank-group) (list :m #'is-c-fdef-end) ) ) ) (defun js-fcallp (head tail) (finite-match (cons head tail) (list (list :m #'is-js-func-name) (list :o #'is-blank-group) (list :m #'is-paren-group) ) ) ) (defun js-arrp (head tail) (finite-match (cons head tail) (list (list :m #'is-js-func-name) (list :o #'is-blank-group) (list :m #'is-bracket-group) ) ) ) (defun group-js-fdef (head tail size) (list (map 'list #'(lambda (x) (if (is-nestable x) (js-fdefs x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size) )) (defun group-js-fcall (head tail size) (list (map 'list #'(lambda (x) (if (is-nestable x) (js-fcalls x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size) )) (defun group-js-arr (head tail size) (list (map 'list #'(lambda (x) (if (is-nestable x) (js-arrs x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size) )) (defun group-js-do-while-stmt (head tail size) (list (map 'list #'(lambda (x) (if (is-nestable x) (js-do-while-stmts x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun first-pgroup-pos-aux (head tail count) (cond ((is-paren-group head) count) ((not (is-paren-group head)) (first-pgroup-pos-aux (car tail) (cdr tail) (+ count 1))) ((not head) nil))) (defun first-pgroup-pos (ls) (first-pgroup-pos-aux (car ls) (cdr ls) 0)) (defun group-js-flat-ctl-stmt (head tail size) (let* ((ls (head-n (cons head tail) size)) (pos (first-pgroup-pos ls)) (blank-after (is-blank-group (nth (+ pos 1) ls))) (n-cdr (if (and blank-after) (+ pos 2) (+ pos 1))) (tail-ls (nthcdr n-cdr ls)) (tail-group (js-flat-ctl-stmts tail-ls)) ) (list (append (head-n ls n-cdr) tail-group) (car (popl-n tail (- size 1))) (popl-n tail size)))) (defmacro! group-and-continue (parent grpr grp-sz) `(let* ((agg (,grpr head tail ,grp-sz)) (nacc (pushr acc (car agg))) (nhead (cadr agg)) (ntail (caddr agg))) (,parent nacc nhead ntail))) (defmacro! xform-and-continue (parent xformer cb) `(let* ((nacc (pushr acc (,xformer head #',cb)))) (,parent nacc (car tail) (cdr tail)))) (defmacro! descend-and-continue (grand-parent parent) `(let ((nacc (pushr acc (,grand-parent head)))) (,parent nacc (car tail) (cdr tail)))) (defmacro! pipeline-until-lambda (test body) `(function (lambda (q) (if ,test ,body nil))) ) (defmacro! js-uber-aux-impl (self-parent self matcher grouper &key fcall fdef fdef-bind curly-ctl do-while flat-ctl arr nestable var-bind obj-lit-rec mbr-chain) `(defun ,self (acc head tail) (let ((sz (,matcher head tail))) (pipeline-until nil (pipeline-until-lambda (and sz) (group-and-continue ,self ,grouper sz)) (pipeline-until-lambda (is-js-fcall head) ,fcall) (pipeline-until-lambda (is-js-arr head) ,arr) (pipeline-until-lambda (is-js-fdef head) ,fdef) (pipeline-until-lambda (is-js-fdef-binding head) ,fdef-bind) (pipeline-until-lambda (is-js-var-binding head) ,var-bind) (pipeline-until-lambda (is-js-curly-ctl-stmt head) ,curly-ctl) (pipeline-until-lambda (is-js-do-while-stmt head) ,do-while) (pipeline-until-lambda (is-js-flat-ctl-stmt head) ,flat-ctl) (pipeline-until-lambda (is-js-mbr-chain head) ,mbr-chain) (pipeline-until-lambda (is-js-obj-lit-rec head) ,obj-lit-rec) (pipeline-until-lambda (is-nestable head) ,nestable) (pipeline-until-lambda (or (and (characterp head) tail) tail) (,self (pushr acc head) (car tail) (cdr tail))) (pipeline-until-lambda (and head (not tail)) (pushr acc head)) (pipeline-until-lambda (and (not tail)) acc)) ) ) ) (js-uber-aux-impl js-fdefs js-fdefs-aux js-fdefp group-js-fdef ;:fcall (xform-and-continue js-fdefs-aux xform-fcall-pgroup js-fdefs) :nestable (descend-and-continue js-fdefs js-fdefs-aux)) (js-uber-aux-impl js-fcalls js-fcalls-aux js-fcallp group-js-fcall :fdef (xform-and-continue js-fcalls-aux xform-js-fdef-cgroup js-fcalls) :nestable (descend-and-continue js-fcalls js-fcalls-aux)) (js-uber-aux-impl js-arrs js-arrs-aux js-arrp group-js-arr :fdef (xform-and-continue js-arrs-aux xform-js-fdef-cgroup js-arrs) :fcall (xform-and-continue js-arrs-aux xform-fcall-pgroup js-arrs) :nestable (descend-and-continue js-arrs js-arrs-aux)) (js-uber-aux-impl js-var-bindings js-var-bindings-aux js-var-bindingp group-js-var-binding :fdef (xform-and-continue js-var-bindings-aux xform-js-fdef-cgroup js-var-bindings) :nestable (descend-and-continue js-var-bindings js-var-bindings-aux)) (js-uber-aux-impl js-mbr-chain js-mbr-chain-aux js-mbr-chainp group-js-mbr-chain :fcall (xform-and-continue js-mbr-chain-aux xform-fcall-pgroup js-mbr-chain) :arr (xform-and-continue js-mbr-chain-aux xform-js-arr-bgroup js-mbr-chain) :fdef (xform-and-continue js-mbr-chain-aux xform-js-fdef-cgroup js-mbr-chain) ;XXX descend or xform??? ;:var-bind (xform-and-continue js-mbr-chain-aux xform-js-vbind-rval js-mbr-chain) :var-bind (descend-and-continue js-mbr-chain js-mbr-chain-aux) :fdef-bind (descend-and-continue js-mbr-chain js-mbr-chain-aux) :nestable (descend-and-continue js-mbr-chain js-mbr-chain-aux)) (js-uber-aux-impl js-obj-lit-recs js-obj-lit-recs-aux js-obj-lit-recp group-js-obj-lit-rec :fdef-bind (descend-and-continue js-obj-lit-recs js-obj-lit-recs-aux) :var-bind (descend-and-continue js-obj-lit-recs js-obj-lit-recs-aux) :mbr-chain (descend-and-continue js-obj-lit-recs js-obj-lit-recs-aux) :fdef (xform-and-continue js-obj-lit-recs-aux xform-js-fdef-cgroup js-obj-lit-recs) :fcall (xform-and-continue js-obj-lit-recs-aux xform-fcall-pgroup js-obj-lit-recs) :nestable (descend-and-continue js-obj-lit-recs js-obj-lit-recs-aux)) (js-uber-aux-impl js-curly-ctl-stmts js-curly-ctl-stmts-aux js-curly-ctl-stmtp group-js-curly-ctl-stmt :fdef (xform-and-continue js-curly-ctl-stmts-aux xform-js-fdef-cgroup js-curly-ctl-stmts) :fcall (xform-and-continue js-curly-ctl-stmts-aux xform-fcall-pgroup js-curly-ctl-stmts) :mbr-chain (descend-and-continue js-curly-ctl-stmts js-curly-ctl-stmts-aux) :var-bind (descend-and-continue js-curly-ctl-stmts js-curly-ctl-stmts-aux) :obj-lit-rec (descend-and-continue js-curly-ctl-stmts js-curly-ctl-stmts-aux) ;:nestable (js-curly-ctl-stmts-aux (pushr acc head) (car tail) (cdr tail)) :nestable (descend-and-continue js-curly-ctl-stmts js-curly-ctl-stmts-aux) ) (js-uber-aux-impl js-do-while-stmts js-do-while-stmts-aux js-do-while-stmtp group-js-do-while-stmt :fdef (xform-and-continue js-do-while-stmts-aux xform-js-fdef-cgroup js-do-while-stmts) :fcall (xform-and-continue js-do-while-stmts-aux xform-fcall-pgroup js-do-while-stmts) :obj-lit-rec (descend-and-continue js-do-while-stmts js-do-while-stmts-aux) :curly-ctl (xform-and-continue js-do-while-stmts-aux xform-js-curly-ctl-stmt-cgroup js-do-while-stmts) ;:nestable (js-do-while-stmts-aux (pushr acc head) (car tail) (cdr tail)) :nestable (descend-and-continue js-do-while-stmts js-do-while-stmts-aux) ) (js-uber-aux-impl js-flat-ctl-stmts js-flat-ctl-stmts-aux js-flat-ctl-stmtp group-js-flat-ctl-stmt :fdef (xform-and-continue js-flat-ctl-stmts-aux xform-js-fdef-cgroup js-flat-ctl-stmts) :fcall (xform-and-continue js-flat-ctl-stmts-aux xform-fcall-pgroup js-flat-ctl-stmts) :obj-lit-rec (descend-and-continue js-flat-ctl-stmts js-flat-ctl-stmts-aux) :curly-ctl (xform-and-continue js-flat-ctl-stmts-aux xform-js-curly-ctl-stmt-cgroup js-flat-ctl-stmts) :do-while (xform-and-continue js-flat-ctl-stmts-aux xform-js-do-while-cgroup js-flat-ctl-stmts) ) ; Function def: 'function' name pgroup cgroup [name != if | for | while] (defun js-fdefs (ls) (js-fdefs-aux '() (car ls) (cdr ls))) (defun js-fcalls (ls) (js-fcalls-aux '() (car ls) (cdr ls))) (defun js-arrs (ls) (js-arrs-aux '() (car ls) (cdr ls))) (defun js-fdef-bindingp (head tail) (finite-match (cons head tail) (list (list :m #'is-word-group) (list :o #'is-blank-group) (list :m #'is-eq-group) (list :o #'is-blank-group) (list :m #'is-js-fdef) ) )) (defun js-var-bindingp (head tail) (finite-match (cons head tail) (list (list :m #'is-js-word-or-arr) (list :o #'is-blank-group) (list :m #'is-eq-group) (list :o #'is-blank-group) (list :mc #'is-stmt) ) )) (defun js-mbr-chainp (head tail) (finite-repeating-match (cons head tail) (list (list :m #'is-js-word-or-fcall-or-arr) (list :o #'is-blank-group) (list :m #'is-dot) (list :o #'is-blank-group)) (list (list :m #'is-word-arr-fcall-vbind-fbind)))) (defun is-js-mbr-chain (ls) (and ls (listp ls) (js-mbr-chainp (car ls) (cdr ls)))) (defun is-js-mbr-chain-word-bind (ls) "Detects mbr-chains that contain words and end in a binding" (let ((fail nil)) (if (and (is-js-mbr-chain ls) (is-js-binding (car (last ls)))) (map 'nil #'(lambda (e) (if (not (or (is-blank-group e) (is-punctuation-group e) (is-word-group e) (is-js-binding e)) ) (setf fail t)) (if (and (is-js-binding e) (is-js-arr (car e))) (setf fail t)) ) ls) (setf fail t) ) (not fail) ) ) ;;; Basically anything until '}' or ',' (defun js-obj-lit-recp (head tail) (finite-match (cons head tail) (list (list :m #'is-js-word-or-str) (list :o #'is-blank-group) (list :m #'is-colon-group) (list :o #'is-blank-group) (list :mc #'is-obj-lit-rval) ) ) ) (defun js-var-bindings (ls) (js-var-bindings-aux '() (car ls) (cdr ls))) (defun js-mbr-chain (ls) (js-mbr-chain-aux '() (car ls) (cdr ls))) (defun js-obj-lit-recs (ls) (js-obj-lit-recs-aux '() (car ls) (cdr ls))) (defun group-js-curly-ctl-stmt (head tail size) (list (map 'list #'(lambda (x) (if (is-nestable x) (js-curly-ctl-stmts x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun group-js-var-binding (head tail size) (list (map 'list #'(lambda (x) (if (is-js-fdef x) (js-var-bindings x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun group-js-mbr-chain (head tail size) (list (map 'list #'(lambda (x) (if (or (is-js-fdef-binding x) (is-js-fcall x) (is-js-var-binding x) (is-js-arr x) ) (js-mbr-chain x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun group-js-obj-lit-rec (head tail size) (list (map 'list #'(lambda (x) (if (or (is-js-fdef-binding x) (is-js-fcall x) (is-js-var-binding x) (is-js-arr x) (is-js-mbr-chain x) ) (js-obj-lit-recs x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun group-js-mbr-chain2 (head tail size) (list (map 'list #'(lambda (x) (if (or (is-js-fdef-binding x) (is-js-fcall x)) (js-mbr-chain x) x)) (head-n (cons head tail) size)) (car (popl-n tail (- size 1))) (popl-n tail size))) (defun js-curly-ctl-stmts (ls) (js-curly-ctl-stmts-aux '() (car ls) (cdr ls))) (defun js-do-while-stmts-aux (acc head tail) (let ((sz (js-do-while-stmtp head tail))) (cond ((and sz) (group-and-continue js-do-while-stmts-aux group-js-do-while-stmt sz)) ((is-js-fdef head) (xform-and-continue js-do-while-stmts-aux xform-js-fdef-cgroup js-do-while-stmts)) ((is-js-fcall head) (xform-and-continue js-do-while-stmts-aux xform-fcall-pgroup js-do-while-stmts)) ((is-js-curly-ctl-stmt head) (xform-and-continue js-do-while-stmts-aux xform-js-curly-ctl-stmt-cgroup js-do-while-stmts)) ((and (listp head) (is-nestable head)) (descend-and-continue js-do-while-stmts js-do-while-stmts-aux)) ((or (and (characterp head) tail) tail) (js-do-while-stmts-aux (pushr acc head) (car tail) (cdr tail))) ((and head (not tail)) (pushr acc head)) ((and (not head)) acc)))) (defun js-do-while-stmts (ls) (js-do-while-stmts-aux '() (car ls) (cdr ls))) (defun js-flat-ctl-stmts (ls) (js-flat-ctl-stmts-aux '() (car ls) (cdr ls))) (defun jsarrs-aux (acc head tail) (cond ((jsarrp head tail 0) (let* ((agg (group-jsarr head tail '())) (nacc (pushr acc (car agg))) (nhead (cadr agg)) (ntail (caddr agg))) (progn (jsarrs-aux nacc nhead ntail)))) ((is-c-fdef head) (let* ((nacc (pushr acc (xform-js-fdef-cgroup (xform-js-fdef-pgroup head #'jsarrs) #'jsarrs)))) (progn (jsarrs-aux nacc (car tail) (cdr tail))))) ((is-fcall head) (let* ((nacc (pushr acc (xform-fcall-pgroup head #'jsarrs)))) (progn (jsarrs-aux nacc (car tail) (cdr tail))))) ((and (listp head) (is-nestable head)) (let ((nacc (pushr acc (jsarrs head)))) (progn (jsarrs-aux nacc (car tail) (cdr tail))))) ((or (and (characterp head) tail) tail) (progn (jsarrs-aux (pushr acc head) (car tail) (cdr tail)))) ((and head (not tail)) (progn (pushr acc head))) ((and (not head)) (progn acc)) )) ;;; Match array-accesses. Should be similar to fcalls. (defun jsarrs (ls) (jsarrs-aux '() (car ls) (cdr ls))) (defun js-vars (ast) ast) ;;; Match object-literal bindingr (assignments using `:`) ;;; Note that we don't want to accidentally match the `:` of the ternary ;;; `?:` operator. ;;; Obviously, if the l-val is not a word (and is not true or false) we can ;;; ignore it. If it is a word, (defun obj-bindings (ls) ) ;;; Match json K-V pairs. ;;; ;;; word [ws] colon [ws] word | string | group ;;; XXX this looks like a 5-state match ;;; Yes. But extraction does not look like fcall or jsarr. But more like fdef ;;; (we keep the last elem) (defun json-kvp-aux (acc head tail) (cond ((json-kv-pair-p head tail 0) (let* ((agg (group-json-kvp head tail '())) (nacc (pushr acc (car agg))) (nhead (cadr agg)) (ntail (caddr agg))) (progn (json-kvp-aux nacc nhead ntail)))) ((is-nestable head) (let ((nacc (pushr acc (json-kvp head)))) (progn (json-kvp-aux nacc (car tail) (cdr tail))))) ((and (not head)) (progn acc)) ((and head (not tail)) (progn (pushr acc head))) ((and head tail) (progn (json-kvp-aux (pushr acc head) (car tail) (cdr tail)))) )) (defun json-kvp (ls) (json-kvp-aux '() (car ls) (cdr ls))) (defun jsontest () (let ((input (str-to-char-ls "\"A\" : \"B\", \"C\" : \"D\""))) (json-to-ast input))) (defun walk-tree-until (ls test work until path) (if (funcall test (car ls)) (funcall work (car ls) path)) (if (funcall until (car ls)) (return-from walk-tree-until)) (if (and (car ls) (listp (car ls))) (walk-tree-until (car ls) test work until (pushr path (car ls)))) (if (and (cdr ls)) (walk-tree-until (cdr ls) test work until path))) (defun walk-tree (ls test work path walk) (if (funcall test (car ls)) (funcall work (car ls) path walk)) (if (and (car ls) (listp (car ls))) (walk-tree (car ls) test work (pushr path (car ls)) (pushr walk 'd))) (if (and (cdr ls)) (walk-tree (cdr ls) test work path (pushr walk 'r)))) ; Walk over the top level of ls and calls func on any fdefs it finds on that ; level. (defmacro! def-apply (name test) `(defun ,name (ls func) (cond ((,test (car ls)) (progn (funcall func (car ls)) (,name (cdr ls) func))) ((and ls (not (,test (car ls)))) (progn (,name (cdr ls) func)))))) (def-apply fdefs-apply is-c-fdef) (def-apply fcalls-apply is-fcall) (def-apply nestable-apply is-nestable) (def-apply paren-group-apply is-paren-group) (def-apply bracket-group-apply is-bracket-group) (def-apply curly-group-apply is-curly-group) (def-apply word-apply is-word-group) (def-apply space-apply is-white-space-group) (def-apply pnctn-apply is-punctuation-group) (defun get-first-of-type (ls test) (cond ((not ls) nil) ((funcall test (car ls)) (car ls)) ((and t) (get-first-of-type (cdr ls) test)) ) ) (defun get-c-fdef-params (ls) (progn (assert (is-c-fdef ls)) (get-first-of-type ls #'is-paren-group))) (defun get-c-fdef-body (ls) (progn (assert (is-c-fdef ls)) (get-first-of-type ls #'is-curly-group))) (defun get-c-fdef-name (ls) (progn (assert (is-c-fdef ls)) (car ls))) (defun get-js-fdef-params (ls) (get-c-fdef-params ls)) (defun get-js-fdef-body (ls) (get-c-fdef-body ls)) (defun get-js-fdef-name-aux (prev-word ls) (cond ((is-paren-group (car ls)) prev-word) ((and (not (is-paren-group (car ls))) (not (is-word-group (car ls)))) (get-js-fdef-name-aux prev-word (cdr ls))) ((is-word-group (car ls)) (get-js-fdef-name-aux (car ls) (cdr ls))) )) (defun get-js-fdef-name (ls) (assert (is-js-fdef ls)) (get-js-fdef-name-aux nil ls)) (defun get-js-ctl-name (ls) (assert (is-js-any-ctl-stmt ls)) (car ls)) (defun get-js-fbind-name (ls) (assert (is-js-fdef-binding ls)) (car ls)) (defun get-js-vbind-name (ls) (assert (is-js-var-binding ls)) (car ls)) (defun get-js-obj-key (ls) (assert (is-js-obj-lit-rec ls)) (car ls)) (defun set-js-obj-key (ls key) (assert (is-js-obj-lit-rec ls)) (assert (or (stringp key) (listp key))) (if (stringp str) (setf (car ls) (str-to-char-ls key))) (if (listp str) (setf (car ls) key)) ) (defun set-js-fdef-name (ls name) (assert (is-js-fdef ls)) (tagbody again (cond ((and (is-paren-group (cadr ls)) (not (match-str-list "function" (car ls)))) (setf ls name) ) ((and (is-paren-group (cadr ls)) (match-str-list "function" (car ls))) (setf (cdr ls) (cons name (cdr ls))) ) ((and t) (setf ls (cdr ls)) (go again) ) ) ) ) (defun set-js-fcall-name (ls name) (assert (is-js-fcall ls)) (setf (car ls) name) ) (defun get-fcall-params (ls) (progn (assert (is-js-fcall ls)) (get-first-of-type ls #'is-paren-group))) (defun get-fcall-param-aux (ls r) (cond ((or (and (listp ls) (listp (car ls)) (characterp (caar ls)) (CHAR= (caar ls) #\,)) (and (characterp (car ls)) (CHAR= (car ls) #\)))) r) ((and t) (get-fcall-param-aux (cdr ls) (pushr r (car ls)))) )) (defun get-param-start-aux (ls n c) (assert (and (listp ls) (listp (car ls)))) (cond ((= c n) ls) ((CHAR= (caar ls) #\,) (get-param-start-aux (cdr ls) n (+ c 1))) ((or (CHAR/= (caar ls) #\,) (and (characterp (car ls)) (CHAR= (car ls) #\())) (get-param-start-aux (cdr ls) n c)))) (defun get-param-start (ls n) (if (= n 0) (cdr ls) (get-param-start-aux ls n 0))) (defun get-fcall-param (ls n) (let ((params (get-fcall-params ls))) (cond ((< n 0) nil) ((>= n (get-fcall-n-args params)) nil) ((and t) (get-fcall-param-aux (get-param-start params n) '())) ) ) ) (defun get-fcall-name (ls) (progn (assert (is-js-fcall ls)) (car ls))) ;;; File IO. ;;; Copied from Practical Common Lisp (because wildcards (why?!)) (defun component-present-p (value) (and value (not (eql value :unspecific)))) (defun directory-pathname-p (p) (and (not (component-present-p (pathname-name p))) (not (component-present-p (pathname-type p))) p)) (defun pathname-as-directory (name) (let ((pathname (pathname name))) (when (wild-pathname-p pathname) (error "Can't reliably convert wild pathnames.")) (if (not (directory-pathname-p name)) (make-pathname :directory (append (or (pathname-directory pathname) (list :relative)) (list (file-namestring pathname))) :name nil :type nil :defaults pathname) pathname))) (defun directory-wildcard (dirname) (make-pathname :name :wild :type #-clisp :wild #+clisp nil :defaults (pathname-as-directory dirname))) (defun list-directory (dirname) (when (wild-pathname-p dirname) (error "Can only list concrete directory names.")) (directory (directory-wildcard dirname))) (defun list-directory (dirname) (when (wild-pathname-p dirname) (error "Can only list concrete directory names.")) (let ((wildcard (directory-wildcard dirname))) #+(or sbcl cmu lispworks) (directory wildcard) #+openmcl (directory wildcard :directories t) #+allegro (directory wildcard :directories-are-files nil) #+clisp (nconc (directory wildcard) (directory (clisp-subdirectories-wildcard wildcard))) #-(or sbcl cmu lispworks openmcl allegro clisp) (error "list-directory not implemented"))) #+clisp (defun clisp-subdirectories-wildcard (wildcard) (make-pathname :directory (append (pathname-directory wildcard) (list :wild)) :name nil :type nil :defaults wildcard)) (defun file-exists-p (pathname) #+(or sbcl lispworks openmcl) (probe-file pathname) #+(or allegro cmu) (or (probe-file (pathname-as-directory pathname)) (probe-file pathname)) #+clisp (or (ignore-errors (probe-file (pathname-as-file pathname))) (ignore-errors (let ((directory-form (pathname-as-directory pathname))) (when (ext:probe-directory directory-form) directory-form)))) #-(or sbcl cmu lispworks openmcl allegro clisp) (error "list-directory not implemented")) (defun is-file-p (pathname) (let ((p (file-exists-p pathname))) (if (and p) (pathname-name p)) )) (defun pathname-as-file (name) (let ((pathname (pathname name))) (when (wild-pathname-p pathname) (error "Can't reliably convert wild pathnames.")) (if (directory-pathname-p name) (let* ((directory (pathname-directory pathname)) (name-and-type (pathname (first (last directory))))) (make-pathname :directory (butlast directory) :name (pathname-name name-and-type) :type (pathname-type name-and-type) :defaults pathname)) pathname))) (defun walk-directory (dirname fn &key directories (test (constantly t))) (labels ((walk (name) (cond ((directory-pathname-p name) (when (and directories (funcall test name)) (funcall fn name)) (dolist (x (list-directory name)) (walk x))) ((funcall test name) (funcall fn name))))) (walk (pathname-as-directory dirname)))) (defun file-to-char-ls-impl (input) (let ((str-ls '()) (in (open input :if-does-not-exist nil))) (when in (setf str-ls (loop for char = (read-char in nil) while char collect char)) (close in) str-ls))) (defun file-to-form-impl (input) (let* ((in (open input :if-does-not-exist nil)) (form nil) (empty nil)) (cond ((and in) (setf form (read in)) (close in) (if (not form) (setf empty t))) ) (values form empty))) (defun file-to-forms-impl (input) (let* ((in (open input :if-does-not-exist nil)) (form nil) (forms '()) (empty nil)) (cond ((and in) (tagbody again (setf form (read in nil 'eof)) (cond ((not (equal form 'eof)) (pushr! forms form) (go again)) ) ) (close in) (if (not forms) (setf empty t))) ) (values forms empty))) (defun file-to-forms (input) (file-to-forms-impl input)) (defun form-to-file-impl (form output) (let ((out nil) (pathls (str-split "/" output))) (if (> (length pathls) 1) (mkdir (apply #'str-cat (intersperse (popr pathls) "/"))) ) (setf out (open output :direction :output :if-exists :supersede :if-does-not-exist :create)) (prin1 form out) (finish-output out) (close out) )) (defun str-to-file (str output) (let ((out (open output :direction :output :if-exists :supersede :if-does-not-exist :create))) (write-string str out) (finish-output out) (close out) ) ) (defun char-ls-to-file (cls output) (str-to-file (char-ls-to-str cls) output) ) (defun file-to-char-ls (input) (file-to-char-ls-impl input)) (defun file-to-form (input) (file-to-form-impl input)) (defun form-to-file (form output) (form-to-file-impl form output)) (defun test-cmt-str () (let ((in "abc/* \"xyz\" */||\"abc/* xyz */\"//abc\"a") (in2 "abc/*xyz*/\"some str in here\"") (in3 "abc/*xyz*/")) (cmt-str (str-to-char-ls in3)))) ;(nestables (str-to-char-ls "abc(123[xyz]789)pqr")) ;(white-space (str-to-char-ls "abc 123 \t xyz ")) (defun c-name-to-pathname (ls) (cond ((is-c-fcall ls) (concatenate 'list (get-fcall-name ls) "()")) ((is-c-fdef ls) (concatenate 'list (get-c-fdef-name ls) "{}")) )) (defun get-js-mbr-nested-words (ls) (let ((words '())) (map 'nil #'(lambda (e) (cond ((is-word-group e) ;(if (> 0 (length words)) ;(pushr! words '(#\.)) ;) (pushr! words e) ) ) ) ls ) (flatten (intersperse words '(#\/) t)) ) ) (defun js-name-to-pathname (ls) (cond ((is-js-flat-ctl-stmt ls) (concatenate 'list (get-js-ctl-name ls) ";")) ((is-js-curly-ctl-stmt ls) (get-js-ctl-name ls)) ((is-js-do-while-stmt ls) (str-to-char-ls "do")) ((is-js-fcall ls) (concatenate 'list (get-fcall-name ls) "()")) ((is-js-fdef ls) (concatenate 'list (get-js-fdef-name ls) "{}")) ((is-js-fdef-binding ls) (concatenate 'list (get-js-fbind-name ls) "=")) ((is-js-var-binding ls) (concatenate 'list (get-js-vbind-name ls) "=")) ((is-js-obj-lit-rec ls) (concatenate 'list (get-js-obj-key ls) ":")) ((is-js-mbr-chain-word-bind ls) (get-js-mbr-nested-words ls)) ((and t) (assert nil)))) (defun js-refine-path (path idx-bool) (map 'list #'js-name-to-pathname (remove-if-not idx-bool path))) (defun c-refine-path (path idx-bool) (map 'list #'c-name-to-pathname (remove-if-not idx-bool path))) (defun fold-list (ls) (if (= (length ls) 0) (return-from fold-list nil)) (if (= (length ls) 1) (return-from fold-list (list (list 1 (car ls))))) (let* ((prev (car ls)) (count 1) (acc '())) (map 'nil #'(lambda (e) (cond ((equal e prev) (incf count)) ((not (equal e prev)) (pushr! acc (list count prev)) (setf prev e) (setf count 1)) )) (cdr ls)) (pushr! acc (list count prev)) )) (defun unfold-list (ls) (if (= (length ls) 0) (return-from unfold-list nil)) (let* ((unfls '())) (map 'nil #'(lambda (p) (dotimes (z (car p)) (pushr! unfls (cadr p)))) ls ) unfls )) (defun mk-js-path-index (ast idx-bool) ;; We keep the non-str lists around for backwards compatibility. ;; Removed the code that populates these lists because these lists were ;; unused, but consumed tons of space. ;; Same holds for all non-JS variants of this code. (let ((str-stkls '()) (rev-str-stkls '()) ) (values (lambda (x y z) (pushr! str-stkls (list (js-refine-path (pushr y x) idx-bool) (fold-list z))) (pushr! rev-str-stkls (list (js-refine-path (reverse (pushr y x)) idx-bool) (fold-list z))) ) (lambda () (list str-stkls rev-str-stkls ast blip-latest-ix-ver)) ))) (defun mk-c-path-index (ast idx-bool) (let ((str-stkls '()) (rev-str-stkls '()) ) (values (lambda (x y z) (pushr! str-stkls (list (c-refine-path (pushr y x) idx-bool) (fold-list z))) (pushr! rev-str-stkls (list (c-refine-path (reverse (pushr y x)) idx-bool) (fold-list z))) ) (lambda () (list str-stkls rev-str-stkls ast blip-latest-ix-ver)) ))) (defun path-index-file (ls) (car ls)) (defun path-index-str (ls) (car (cadr ls))) (defun path-index-revstr (ls) (cadr (cadr ls))) (defun path-index-ast (ls) (caddr (cadr ls))) (defun path-index-ver (ls) (cadddr (cadr ls))) (defun path-index-setroot (ls) (pushl! (car ls) (list '((#\/)) nil)) (pushl! (cadr ls) (list '((#\/)) nil)) ls ) (defun js-idx-type-to-test (type) (let ((idx-bool nil)) (cond ((or (equal type :funcs) (equal type nil)) (setf idx-bool #'is-js-indexable-funcs)) ((equal type :funcs-conds) (setf idx-bool #'is-js-indexable-conds)) ((equal type :binds) (setf idx-bool #'is-js-indexable-binds)) ) idx-bool ) ) (defun js-idx-type-to-name (type) (if (equal type nil) (symbol-name :funcs) (symbol-name type))) (defun c-idx-type-to-test (type) (let ((idx-bool nil)) (cond ((or (equal type :funcs) (equal type nil)) (setf idx-bool #'is-c-fdef-or-fcall)) ((equal type :funcs-conds) (setf idx-bool #'is-c-fdef-or-fcall)) ) idx-bool ) ) (defun c-idx-type-to-name (type) (js-idx-type-to-name type)) (defmacro! index-all-x-paths-impl (name type-to-test mk-x-path-index) `(defun ,name (ast &optional type) (let ((idx-bool (,type-to-test type))) (assert idx-bool) (multiple-value-bind (update-indices get-indices) (,mk-x-path-index ast idx-bool) (walk-tree ast idx-bool update-indices '() '()) (funcall get-indices) )) ) ) (index-all-x-paths-impl index-all-js-paths-impl js-idx-type-to-test mk-js-path-index) (index-all-x-paths-impl index-all-c-paths-impl c-idx-type-to-test mk-c-path-index) (defmacro! cache-x-path-index (name indexer type-namer) `(defun ,name (repo file commit &optional type ast) (if (not ast) (setf ast (load-ast repo file commit))) (let* ((type-nm (,type-namer type)) (fcommit (git-file-latest-commit-until repo file commit)) (outdir (str-cat blip-repo-meta repo "/root/" file "/" fcommit "/path-index/")) (out (str-cat outdir type-nm))) (mkdir outdir) (form-to-file (,indexer ast type) out)))) (cache-x-path-index cache-js-path-index index-all-js-paths-impl js-idx-type-to-name) (cache-x-path-index cache-c-path-index index-all-c-paths-impl c-idx-type-to-name) (defmacro! load-x-path-index (name type-namer) `(defun ,name (repo file commit &optional type ast) (let* ((type-nm (,type-namer type)) (fcommit (git-file-latest-commit-until repo file commit)) (in (str-cat blip-repo-meta repo "/root/" file "/" fcommit "/path-index/" type-nm)) (ix (file-to-form in))) ix ))) (load-x-path-index load-js-path-index js-idx-type-to-name) (load-x-path-index load-c-path-index c-idx-type-to-name) (defun is-latest-ix (ix) (and (numberp (cadddr ix)) (= (cadddr ix) blip-latest-ix-ver))) (defmacro! index-all-x-paths (name cacher loader) `(defun ,name (repo file commit &optional type ast &key force) (expand-commit! repo commit) (let* ((ix (if (not force) (,loader repo file commit type ast) nil))) (cond ((or (not ix) (not (is-latest-ix ix))) (,cacher repo file commit type ast) (setf ix (,loader repo file commit type ast))) ) ix )) ) (index-all-x-paths index-all-js-paths cache-js-path-index load-js-path-index) (index-all-x-paths index-all-c-paths cache-c-path-index load-c-path-index) (defun test-index-js (&optional force) (index-all-js-paths "github/davepacheco/node-vasync" "examples/barrier-basic.js" :head :funcs nil :force force)) (defun count-node-in-ast (test idx-bool ast &key deep) (let ((count 0)) (walk-tree ast test #'(lambda (n stack walk) (let ((depth (length (remove-if-not idx-bool stack)))) (if (or (and (> depth 0) deep) (and (= depth 0))) (if (funcall test n) (incf count))))) '() '()) count )) (defun list-node-in-ast (test fmt dedup ast &optional count) (let ((list '()) (ddl '()) (cl '())) (walk-tree ast test #'(lambda (n stack walk) (if (funcall test n) (pushr! list (funcall fmt n)))) '() '() ) (setf ddl (remove-duplicates list :test dedup)) (if (and count) (progn (map 'list #'(lambda (e) (pushr! cl (list e (count e list :test dedup)))) ddl) (setf cl (stable-sort cl #'< :key #'cadr)) )) (if (and cl) cl ddl) )) (defmacro! load-list-nodes (name suf) `(defun ,name (repo file commit) (let* ((fcommit (git-file-latest-commit-until repo file commit)) (in (str-cat blip-repo-meta repo "/root/" file "/" fcommit ,suf))) (file-to-form in) ) ) ) (defmacro! x-list-node-impl (name test getter) `(defun ,name (ast &optional count) (list-node-in-ast #',test #'(lambda (n) (char-ls-to-str (,getter n))) #'string= ast count))) (defmacro! cache-x-list-node (name list-impl suf) `(defun ,name (repo file commit) (let* ((ast (load-ast repo file commit)) (fcommit (git-file-latest-commit-until repo file commit)) (outdir (str-cat blip-repo-meta repo "/root/" file "/" fcommit)) (out (str-cat outdir ,suf)) ) ;TODO implement a cache-ast function that will cache ASTs on a per-file basis ;TODO cleanup parse-x-files-at-commit (if (not ast) (assert ast)) (mkdir outdir) (form-to-file (,list-impl ast t) out) ) ) ) (defmacro! x-list-node (name cacher loader) `(defun ,name (repo file commit &optional count &key force) (expand-commit! repo commit) (multiple-value-bind (ls empty) (if (not force) (,loader repo file commit) (values nil nil)) (cond ((and (not ls) (not empty)) (,cacher repo file commit) (setf ls (,loader repo file commit))) ) (cond ((not count) (setf ls (map 'list #'car ls))) ) ls ) )) (load-list-nodes load-list-words "/ls-words") (load-list-nodes load-list-fcalls "/ls-fcalls") (load-list-nodes load-list-fdefs "/ls-fdefs") (load-list-nodes load-list-fbinds "/ls-fbinds") (x-list-node-impl js-list-fcalls-impl is-js-fcall get-fcall-name) (cache-x-list-node cache-js-list-fcalls js-list-fcalls-impl "/ls-fcalls") (x-list-node-impl js-list-fdefs-impl is-js-fdef get-js-fdef-name) (cache-x-list-node cache-js-list-fdefs js-list-fdefs-impl "/ls-fdefs") (x-list-node-impl js-list-fbinds-impl is-js-fdef-binding get-js-fbind-name) (cache-x-list-node cache-js-list-fbinds js-list-fbinds-impl "/ls-fbinds") (x-list-node-impl js-list-words-impl is-word-group identity) (cache-x-list-node cache-js-list-words js-list-words-impl "/ls-words") (x-list-node-impl c-list-fcalls-impl is-fcall get-fcall-name) (cache-x-list-node cache-c-list-fcalls c-list-fcalls-impl "/ls-fcalls") (x-list-node-impl c-list-fdefs-impl is-c-fdef get-c-fdef-name) (cache-x-list-node cache-c-list-fdefs c-list-fdefs-impl "/ls-fdefs") (x-list-node-impl c-list-words-impl is-word-group identity) (cache-x-list-node cache-c-list-words c-list-words-impl "/ls-words") (x-list-node js-list-fcalls cache-js-list-fcalls load-list-fcalls) (x-list-node c-list-fcalls cache-c-list-fcalls load-list-fcalls) (x-list-node js-list-fdefs cache-js-list-fdefs load-list-fdefs) (x-list-node js-list-fbinds cache-js-list-fbinds load-list-fbinds) (x-list-node c-list-fdefs cache-c-list-fdefs load-list-fdefs) (x-list-node js-list-words cache-js-list-words load-list-words) (x-list-node c-list-words cache-c-list-words load-list-words) (defun test-ls-js (&optional count force) (js-list-fcalls "github/davepacheco/node-vasync" "examples/barrier-basic.js" :head count :force force)) (defun hash-table-to-alist (table) (let ((alist nil)) (maphash #'(lambda (k v) (push (cons k v) alist)) table) alist )) (defmacro! agg-ast (ast test work sort key) `(let ((counts (make-hash-table :test #'equal))) (walk-tree ,ast ,test ,work '() '()) (sort (hash-table-to-alist counts) ,sort :key ,key) )) (defun file-commit-count (ast) (agg-ast ast #'is-file-mod #'(lambda (n s w) (incf (gethash (file-mod-stringify-path n) counts 0))) #'< #'cdr )) (defun js-word-count (ast) (agg-ast ast #'is-word-group #'(lambda (n s w) (incf (gethash (char-ls-to-str (flatten n)) counts 0))) #'< #'cdr )) (defun js-fcall-count (ast) (agg-ast ast #'is-js-fcall #'(lambda (n s w) (incf (gethash (char-ls-to-str (get-fcall-name n)) counts 0))) #'< #'cdr )) (defun js-fcall-params-count (ast) (agg-ast ast #'is-js-fcall #'(lambda (n s w) (incf (gethash (char-ls-to-str (flatten (get-fcall-params n))) counts 0))) #'< #'cdr )) (defun js-fdef-count (ast) (agg-ast ast #'is-js-fdef #'(lambda (n s w) (incf (gethash (char-ls-to-str (get-js-fdef-name n)) counts 0))) #'< #'cdr )) (defun js-word-count-old (ast) (let ((counts (make-hash-table :test #'equal))) (walk-tree ast #'is-word-group #'(lambda (n s w) (incf (gethash (char-ls-to-str n) counts 0))) '() '() ) (sort (hash-table-to-alist counts) #'< :key #'cdr) )) (defun is-require (f) (js-fcall-name-eq f "require")) (defun walk-print-fcall-args (f s w) (print-fcall-args f)) (defun print-all-requires (ast) (walk-tree ast #'is-require #'walk-print-fcall-args '() '()) ) (defun print-var-names (ast) (let ((counts (make-hash-table :test #'equal)) (count 0)) (walk-tree ast #'is-js-var-binding #'(lambda (v s w) (incf (gethash (char-ls-to-str (car v)) counts 0)) ;(pushr! names (char-ls-to-str (car v))) (incf count) ) '() '()) (sort (hash-table-to-alist counts) #'< :key #'cdr) ;count )) (defun print-all-arrays (ast) (walk-tree ast #'is-jsarr #'(lambda (e s w) (print (flatten e))) '() '())) (defun test-arr-pr () (print-all-arrays (load-ast "github/joyent/sdc-docker" "lib/moray.js" :head))) (defun get-require-arg0 (ast) (let ((args '())) (walk-tree ast #'is-require #'(lambda (f s w) (let ((param (flatten (get-fcall-param f 0)))) (if (is-str param) (pushr! args (char-ls-to-str (drop-str-quotes param)))))) '() '()) (map 'list #'(lambda (e) (str-split "/" e)) args))) (defun pathname-to-string (p) "Note that the 'flatten' is in there because some bindings, (such as binding to an array) contain lists at the toplevel instead of characters" (char-ls-to-str (flatten p))) (defun inter-aux (c ls e nl) (cond ((or (and ls (not nl)) (and ls nl (cdr ls))) (inter-aux (pushr c (car ls) e) (cdr ls) e nl)) ((and ls nl (not (cdr ls))) (inter-aux (pushr c (car ls)) (cdr ls) e nl)) ((not ls) c))) (defun intersperse (ls e &optional not-last) (inter-aux '() ls e not-last)) (defun fmt-path (path) (reduce #'str-cat (intersperse (map 'list #'pathname-to-string path) "/"))) (defun fmt-paths (pathls) (map 'list #'fmt-path pathls)) (defun print-js-path-tree-pair (pair) (print (fmt-path (car pair))) (print (cadr pair)) ) (defun print-js-path (pair) (fmt-path (car pair))) (defun print-js-path-raw (pair) (car pair)) (defun print-js-path-tree-pairs (pairs) (map 'list #'print-js-path-tree-pair pairs)) (defun print-js-paths (index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (map 'list #'print-js-path pairs)))) (defun match-path (p1 p2) (equal p1 p2)) (defun uniq-path-aux (stack pairs fmt) (let ((prev (stack-last stack))) (cond ((not pairs) (stack-list stack)) ((and fmt prev (equal (car prev) (fmt-path (caar pairs)))) (stack-set-last stack (list (fmt-path (caar pairs)) (incf (cadr prev)))) (uniq-path-aux stack (cdr pairs) fmt)) ((and prev (equal (car prev) (caar pairs))) (stack-set-last stack (list (caar pairs) (incf (cadr prev)))) (uniq-path-aux stack (cdr pairs) fmt)) ((and fmt) (stack-pushr stack (list (fmt-path (caar pairs)) 1)) (uniq-path-aux stack (cdr pairs) fmt)) ((and t) (stack-pushr stack (list (caar pairs) 1)) (uniq-path-aux stack (cdr pairs) fmt)) ))) (defun sort-by-path (p1 p2) (string< (fmt-path p1) (fmt-path p2))) (defun uniq-path (index &key pov fmt sort-path sort-count) (let* ((pairs nil) (ret nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (if (and sort-path) (setf pairs (stable-sort pairs #'sort-by-path :key #'car))) (setf ret (list (path-index-file index) (uniq-path-aux (make-instance 'stack) pairs fmt))) (if (and sort-count) (stable-sort (cadr ret) #'< :key #'cadr)) ret )) (defun paths-by-depth (index &key pov fmt) (let ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) ;(print (fmt-path (caar pairs))) (stable-sort pairs #'(lambda (x y) (< (length x) (length y))) :key #'car) (list (path-index-file index) (if (and fmt) (map 'list #'(lambda (p) (fmt-path (car p))) pairs) (map 'list #'car pairs)) ))) (defun test-pbd () (paths-by-depth (test-docker-create-index) :pov nil :fmt t)) (defun auto-walk-tree-aux (tree walk) (cond ((not walk) (car tree)) ((eql 'd (car walk)) (auto-walk-tree-aux (car tree) (cdr walk))) ((eql 'r (car walk)) (auto-walk-tree-aux (cdr tree) (cdr walk))) ((and t) (assert nil)) )) (defun auto-walk-tree (tree walk) (auto-walk-tree-aux tree walk) ) (defun splice-subtree-aux (tree walk subtree) (cond ((not walk) (setf (car tree) subtree)) ((eql 'd (car walk)) (splice-subtree-aux (car tree) (cdr walk) subtree)) ((eql 'r (car walk)) (splice-subtree-aux (cdr tree) (cdr walk) subtree)) ((and t) (assert nil)) )) (defun splice-subtree (tree walk subtree) (splice-subtree-aux tree walk subtree) tree ;;; XXX VERIFY that this contains a spliced-in subtree ) (defun get-path-subtree (path index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (remove nil (map 'list #'(lambda (p) (cond ((string= path "/") (path-index-ast index)) ((match-path path (fmt-path (car p))) (auto-walk-tree (path-index-ast index) (unfold-list (cadr p)))))) pairs)))) ) (defun get-path-walk (path index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (remove nil (map 'list #'(lambda (p) (cond ((string= path "/") (list (path-index-ast index) '())) ((match-path path (fmt-path (car p))) (list (path-index-ast index) (unfold-list (cadr p)))))) pairs)))) ) (defun get-path-subtree-str (path index &optional pov) (map 'list #'ast-to-str (get-path-subtree path pov))) (defun get-path-node-count (test index idx-bool &optional pov &key zero pre) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (remove nil (map 'list ;;; TODO use get-subtree here #'(lambda (p) (let ((count (count-node-in-ast test idx-bool (get-path-subtree (fmt-path (car p)) index pov) :deep t))) (if (and (or (and zero (= 0 count)) (> count 0)) (or (not pre) (is-str-prefix pre (fmt-path (car p))))) (list (fmt-path (car p)) count)))) pairs))))) (defun get-path-with-prefix (prefix index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (remove nil (map 'list #'(lambda (p) (cond ((is-str-prefix prefix (fmt-path (car p))) (fmt-path (car p))) ) ) pairs)))) ) (defun get-path-with-suffix (suffix index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (list (path-index-file index) (remove nil (map 'list #'(lambda (p) (if (is-str-suffix suffix (fmt-path (car p))) (fmt-path (car p)))) pairs)))) ) (defun get-index-length (index) (map 'list #'(lambda (pair) (list (car pair) (length (cadr pair)))) index)) (defun print-js-paths-raw (index &optional pov) (let* ((pairs nil)) (if (or (not pov) (equal pov :down)) (setf pairs (path-index-str index)) (setf pairs (path-index-revstr index))) (map 'list #'print-js-path-raw pairs))) (defun print-fcall-name (fls path) (print (js-refine-path path)) (format t "~%name: ~a~%" (char-ls-to-str (get-fcall-name fls))) ) (defun print-fcall-args(fls) (format t "name: ~a args: ~a~%" (char-ls-to-str (get-fcall-name fls)) (get-fcall-params fls))) (defun get-c-fdef-n-args (p) (let ((count 0)) (labels ((counter (pg) (if (and (= 1 (length pg)) (CHAR= #\, (car pg))) (incf count 1)))) (pnctn-apply p #'counter) (+ count 1)))) (defun get-fcall-n-args (p) (get-c-fdef-n-args p)) (defun strtest () (cmt-str (str-to-char-ls "word''drow"))) (defun nestest() (nestables (str-to-char-ls "word()drow"))) (defun ast-to-str (ast) (pipeline (flatten ast) #'char-ls-to-str)) (defun mapahead-aux (res func ls prev) (cond ((not ls) res) ((and ls) (mapahead-aux (pushr res (funcall func prev (car ls) (cdr ls))) func (cdr ls) (car ls))))) (defun mapahead (func ls) (mapahead-aux '() func ls nil)) (defun xform-ast (ast test xform stack &key on-test-fail) (if (not on-test-fail) (setf on-test-fail 'drop)) (if (not (listp ast)) (return-from xform-ast ast)) (let* ((ret nil)) (setf ret (remove nil (reduce #'append (mapahead #'(lambda (prev n rest) (cond ((or (and test (funcall test n)) (not test)) (multiple-value-list (funcall xform prev n rest stack))) ((and test (not (funcall test n)) (equal on-test-fail 'keep)) (multiple-value-list n) ) ) ) ast)))) (setf ret (map 'list #'(lambda (n) (xform-ast n test xform (pushr stack n))) ret)) ret ) ) (defun copy-ast (ast test) (xform-ast ast test #'(lambda (p n r s) n) '())) (defun gen-ws-aux (acc n) (cond ((> n 0) (gen-ws-aux (pushr acc #\Space) (- n 1)) ) ((= n 0) acc) ) ) (defun gen-ws (ns) (gen-ws-aux '() ns)) (defun gen-nl-ws-aux (acc n) (cond ((> n 0) (gen-nl-ws-aux (pushr acc #\Space) (- n 1)) ) ((= n 0) acc) ) ) (defun gen-nl-ws (ns) (gen-nl-ws-aux '(#\Newline) ns)) (defun is-js-hyperlink (n) (and (listp n) (> (length n) 4) (and (characterp (car n)) (CHAR= (car n) #\<)) (and (characterp (cadr n)) (CHAR= (cadr n) #\<)) (and (characterp (caddr n)) (CHAR= (caddr n) #\<)) (and (characterp (cadddr n)) (CHAR= (cadddr n) #\Space)) )) ;;; We want to not indent `};` ;;; Also, we may want to count depty by {} and not fdefs (defun js-simtupid-fmt-cb (prev n rest s) (let* ((depth 0)) (incf depth (count-if #'is-curly-group s)) (cond ((is-js-hyperlink (car (last s))) (values n)) ((and (is-punctuation-group n) (CHAR= #\; (car n)) (or (and (characterp (car rest)) (CHAR/= #\} (car rest))) (not (characterp (car rest))))) (values n (gen-nl-ws (* 4 depth)))) ((and (characterp n) (CHAR= #\{ n) (or (and (characterp (car rest)) (CHAR/= #\} (car rest))) (not (characterp (car rest))))) (values (gen-ws 1) n (gen-nl-ws (* 4 depth)))) ((and (characterp n) (CHAR= #\{ n) (and (characterp (car rest)) (CHAR= #\}))) ;(print (last s)) (values (gen-ws 1) n (gen-nl-ws (* 4 (- depth 1))))) ((and (characterp n) (CHAR= #\} n)) (values (gen-nl-ws (* 4 (- depth 1))) n (gen-nl-ws (* 4 (- depth 1))))) ((and (is-js-var-binding n) (is-word-group prev)) (values (gen-ws 1) n)) ((is-js-ctl-struct n) (values n (gen-ws 1))) ((and (is-str n) (is-word-group prev)) (values (gen-ws 1) n)) ((and (is-str n) (is-str prev)) (values (gen-nl-ws (* 4 depth)) n)) ((and (or (is-word-group n) (is-jsarr n)) ;(is-punctuation-group (car rest)) (or (match-punc-ls "," prev) (is-word-group prev))) (values (gen-ws 1) n)) ((match-punc-ls "," n) (values n (gen-ws 1))) ((or (match-any-puncs-ls '("+" "-" "*" "/" "||" "<<" ">>" ">" "<" ">=" "<=" "==" "===" "!=" "!==" "&&" "=") n)) (values (gen-ws 1) n (gen-ws 1))) ((and (> depth 0) (is-js-fdef n)) (values (gen-nl-ws (* 4 depth)) (append (str-to-char-ls "<<< ") (get-js-fdef-name n) (str-to-char-ls "{}/ >>>") (gen-nl-ws (* 4 depth))))) ((and (> depth 0) (is-js-fdef-binding n)) (values (gen-nl-ws (* 4 depth)) (str-to-char-ls "<<< ") (get-js-fbind-name n) (str-to-char-ls "=/ >>>"))) ((and t) (values n)) ) ) ) (defun js-ast-fmt-simtupid (out ast) (let* ((ret nil) (idx-bool (js-idx-type-to-test :funcs))) (setf ret (copy-ast ast #'(lambda (n) (not (is-blank-group n))))) (setf ret (xform-ast ret #'identity #'js-simtupid-fmt-cb '())) ret ) ) (defun c-simtupid-fmt-cb (prev n rest s) (let* ((depth 0)) (incf depth (count-if #'is-curly-group s)) (cond ((and (is-punctuation-group n) (CHAR= #\; (car n)) (or (and (characterp (car rest)) (CHAR/= #\} (car rest))) (not (characterp (car rest))))) (values n (gen-nl-ws (* 4 depth)))) ((and (characterp n) (CHAR= #\{ n) (or (and (characterp (car rest)) (CHAR/= #\} (car rest))) (not (characterp (car rest))))) (values (gen-ws 1) n (gen-nl-ws (* 4 depth)))) ((and (characterp n) (CHAR= #\{ n) (and (characterp (car rest)) (CHAR= #\}))) ;(print (last s)) (values (gen-ws 1) n (gen-nl-ws (* 4 (- depth 1))))) ((and (characterp n) (CHAR= #\} n)) (values (gen-nl-ws (* 4 (- depth 1))) n (gen-nl-ws (* 4 (- depth 1))))) ((is-ctl-struct n) (values n (gen-ws 1))) ((and (is-str n) (is-word-group prev)) (values (gen-ws 1) n)) ((and (is-str n) (is-str prev)) (values (gen-nl-ws (* 4 depth)) n)) ((and (or (is-word-group n) (is-c-fdef n) (is-jsarr n)) ;(is-punctuation-group (car rest)) (or (match-punc-ls "," prev) (is-word-group prev))) (values (gen-ws 1) n)) ((match-punc-ls "=" n) (values (gen-ws 1) n (gen-ws 1))) ((and (is-punctuation-group n) (CHAR= (car n) #\*)) (values (gen-ws 1) n)) ((and t) (values n)) ) ) ) (defun c-ast-fmt-simtupid (out ast) (let* ((ret nil) (idx-bool (js-idx-type-to-test :funcs))) (setf ret (copy-ast ast #'(lambda (n) (not (is-blank-group n))))) (setf ret (xform-ast ret #'identity #'c-simtupid-fmt-cb '())) ret ) ) (defun test-js-fmt () (let* ((in (str-to-char-ls "function foo (a b c) { function bar (x y z) { hello.world(); } bar();}")) (ast (js-to-ast in))) (js-ast-fmt-simtupid nil ast) ) ) (defun test-js-fmt-2 () (let* ((in (str-to-char-ls "function foo (a b {d:function c (a b c) { stuff }}) { function bar (x y z) { hello.world(); } bar();}")) (ast (js-to-ast in))) (js-ast-fmt t ast :simtupid) ) ) (defun js-ast-fmt (out ast style) (if (equal out t) (setf out *standard-output*)) (cond ((equal style :simtupid) (js-ast-fmt-simtupid nil ast)) ((and t) (assert nil)) )) (defun c-ast-fmt (out ast style) (if (equal out t) (setf out *standard-output*)) (cond ((equal style :simtupid) (c-ast-fmt-simtupid nil ast)) ((and t) (assert nil)) )) (defun gen-chars (&rest cs) (let* ((res '())) (map 'nil #'(lambda (c) (cond ((characterp c) (pushr! res c)) ((stringp c) (setf res (append res (str-to-char-ls c)))) ((and t) (assert nil)) ) ) cs) res ) ) (defun valve (test val) (if (funcall test val) val (assert nil))) (defmacro! gen-word (&rest cs) `(valve #'validate-word (gen-chars ,@cs))) (defmacro! gen-blank () `(valve #'validate-blank (enclose (gen-ws 1)))) (defun js-to-ast (input) (pipeline input #'cmt-str-regex #'white-space #'blanks #'words #'punctuations #'nestables #'js-fdefs #'js-fcalls #'js-arrs #'js-var-bindings #'js-mbr-chain #'js-obj-lit-recs #'js-vars #'js-curly-ctl-stmts #'js-do-while-stmts #'js-flat-ctl-stmts )) (defun cl-to-ast (input) (pipeline input #'cl-cmt-str #'white-space #'cl-blanks #'words #'punctuations #'nestables )) (defun test-if-parse () (let ((in1 "call(\"arg\", function (a, b) { if (true) if (true) { if (true) { return 1 }};});") (in2 " if (x) if (y) {(10 * 10)};") (in3 "if (x) if (y) (10 * 10);") (in4 "if (x) { (10 * 10); }") (in5 "if (z) {do { if (a) do { (10 * 10) } while (y); } while (x);}") (in6 "if (x) { if (z) while (y) { (10 * 10); };}") (in7 "function (a) { return {a: function () { if (a) { return a.b.c } } }}") (in8 "a.b.c = {a: function () { if (a) { return a.b.c } } };") (in9 "{a: b, c: d}") ) (js-to-ast (str-to-char-ls in9)))) (defun test-varbind-parse () (let ((in1 "if (x) { function foo (a, b) {var mvar = 2 + 2 + call(); for (mvar = 0; true; mvar++) { print('heeeeeeey'); }}; bar(); foo(); x = 4.2; }") (in2 "if (a, b) {call(); var func = function foo (a, b) {hello = function (a) {b};};}") (in3 "function a (1, 2) {foo = function (1, 2) {4};}")) (js-to-ast (str-to-char-ls in2)))) (defun test-mbrchain-parse () (let ((in2 "if (a, b) {call().a.b.c; var func = function foo (a, b) {hello.fn = function (a) {b.mycall().mymbr = {a: b, b: c, c: d.e, e: f};};};}") (in3 "function (a) {a.b[10].c[10] = function (a) {myCall(); function () {a.b.c}; return a = a.b.call(function () {a.b.c});};}") (in4 "a. b .c = q.w.e;")) (js-to-ast (str-to-char-ls in4)))) ;;; TODO implement this (defun c-pre-proc (ls) ;;;(c-pre-proc-aux '() (car ls) (cdr ls) ) (defun c-to-ast (input) (pipeline input #'cmt-str #'white-space #'blanks #'words #'punctuations #'nestables #'fcalls #'c-fdefs #'jsarrs)) (defun test-ast () (js-to-ast (str-to-char-ls "var foo = require /*cmt*/ ('module'); var bar = require('module');var myfunc = function foo (a, b, c) { var func2 = function (abc) { return x } };"))) (defun test-fcop () (js-to-ast (str-to-char-ls "var myfunc = function foo (a, b, c) { var func2 = function (abc) { return x } };"))) (defun test-fcall-cb-old () (let ((in "'operations': funcs.map(function (func) { return ({ }); }),")) (js-to-ast (str-to-char-ls in)) ) ) (defun test-fcall-cb() (let ((in "funcs.map(function (func) {\n return ({\n 'func': func,\n 'funcname': func.name || '(anon)',\n 'status': 'waiting'\n });\n })")) (js-to-ast (str-to-char-ls in)) )) (defun test-docker-ast () (multiple-value-bind (ast time) (js-to-ast (file-to-char-ls (str-cat blip-repos "github/joyent/sdc-docker/lib/backends/sdc/containers.js"))) time)) (defun test-js-ast () (let ((in "function addPublishFirewallRules(opts, container, img, payload, callback) { var e; var exposed; var hostConf = container.HostConfig; var imageExposedPorts = img.config && img.config.ExposedPorts || {}; callback(); }") (in2 "if { if { }")) (js-to-ast (str-to-char-ls in2)) ) ) ;;; TODO group bindings `$STRING : $STUFF` ;;; A JSON binding is a string, a colon, and a value followed by a comma or nil. ;;; A value is either a string, word, or group. ;;; TODO allow walking of JSON and 1-level listing of keys (defun json-to-ast (input) (pipeline input #'cmt-str #'white-space #'blanks #'words #'punctuations #'nestables #'json-kvp)) (defun is-json-kvp (ls) (and (listp ls) (cond ((= (length ls) 3) (and (is-str (car ls)) (is-colon-group (cadr ls)) (is-json-value (caddr ls)))) ((= (length ls) 4) (and (is-str (car ls)) (or (and (is-colon-group (cadr ls)) (is-blank-group (caddr ls)) (is-json-value (cadddr ls))) (and (is-blank-group (cadr ls)) (is-colon-group (caddr ls)) (is-json-value (cadddr ls)))))) ((= (length ls) 5) (and (is-str (car ls)) (is-blank-group (cadr ls)) (is-colon-group (caddr ls)) (is-blank-group (cadddr ls)) (is-json-value (car (cddddr ls))))) ((and t) nil)))) (defun get-json-kvp-value (ls) (progn (assert (is-json-kvp ls)) (cond ((is-json-value (caddr ls)) (caddr ls)) ((is-json-value (cadddr ls)) (cadddr ls)) ((is-json-value (car (cddddr ls))) (car (cddddr ls)))))) (defun get-json-kvp-key (ls) (progn (assert (is-json-kvp ls)) (car ls))) ;;; The quotes around `str` are implied (defun json-key-eq (ls str) (match-str-list str (drop-str-quotes (get-json-kvp-key ls)))) (defun test-docker-json () (multiple-value-bind (ast time) (json-to-ast (file-to-char-ls (str-cat blip-repos "gerrit/joyent/sdc-docker/package.json"))) ast)) (defun json-get-kvp (ast &optional key) (let ((kvps '())) (walk-tree ast #'is-json-kvp #'(lambda (n ignore w) (if (or (and key (json-key-eq n key)) (not key)) (pushr! kvps (list (get-json-kvp-key n) (get-json-kvp-value n))))) '() '()) kvps ) ) (defun pkg-deps-json (ast) (let ((deps '()) (dep-tree '())) (setf dep-tree (cadar (json-get-kvp ast "dependencies"))) (setf deps (map 'list #'(lambda (x) (list (char-ls-to-str (drop-str-quotes (car x))) (char-ls-to-str (drop-str-quotes (cadr x))))) (json-get-kvp dep-tree))) deps)) (defun test-docker-deps () (pkg-deps-json (test-docker-json))) (defun pkg-type (pkg) ;TODO validate the semver (let ((v (cadr pkg))) (cond ((is-str-prefix "https" v) 'http-commit) ((is-str-prefix "git+https" v) 'git+https-commit) ((is-str-prefix "git" v) 'git-commit) ((is-npm-range-version v) 'semver-range) ((and t) 'semver)))) (defun git-commit-split (pkg) (str-split "\\+|#" (cadr pkg))) (defun get-repo-url-from-pkg-ver (pkg) (if (eq (pkg-type pkg) 'git+https-commit) (let ((vparts (git-commit-split pkg))) (if (> (length vparts) 1) (if (string= "git" (car vparts)) (cadr vparts) (car vparts)))))) (defun test-docker-git-urls () (remove nil (map 'list #'get-repo-url-from-pkg-ver (test-docker-deps)))) (defun test-docker-pkg-json () (map 'list #'(lambda (tup) (npm-get-pkg (car tup) (cadr tup))) (remove nil (map 'list #'(lambda (p) (if (eq (pkg-type p) 'semver) p)) (test-docker-deps)))) ) (defun test-docker-dep-vers () (pipeline (car (test-docker-pkg-json)) #'json-to-ast #'(lambda (x) (json-get-kvp x "dependencies")) ;TODO tell above func to return value from above kvp ;(map 'list #'json-to-ast (test-docker-pkg-json) )) (defun test-docker-dep-types () (map 'list #'pkg-type (test-docker-deps))) (defun npm-pkg-url (p v) (str-cat npm-base-url p "/" v)) (defun npm-get-pkg (pkg version) (pushnew '("application" . "json") drakma:*text-content-types*) (drakma:http-request (npm-pkg-url pkg version) :method :get)) (defun npm-parse-ver-str (v) (pipeline v #'white-space #'blanks #'words #'punctuation)) (defun mk-str-index () (let ((strs '())) (values (lambda (x y z) (if (json-key-eq x "full_name") (setf strs (pushr strs (char-ls-to-str (drop-str-quotes (get-json-kvp-value x))))))) (lambda () (list strs)) ))) (defun index-repo-names (ast) (multiple-value-bind (update-str-index get-index) (mk-str-index) (walk-tree ast #'is-json-kvp update-str-index '() '()) (funcall get-index) ) ) (defun list-user-repos-http (user page) (let ((url (github-user-repos-url user)) (pg (write-to-string page))) (pushnew '("application" . "json") drakma:*text-content-types*) (drakma:http-request url :method :get :parameters (pairlis '("page" "per_page") (list pg "100"))))) (defun user-repos-json (user page) (json-to-ast (str-to-char-ls (list-user-repos-http user page)))) (defun user-repo-list-aux (user pg rl) (let* ((repo-list (car (index-repo-names (user-repos-json user pg)))) (all (append rl repo-list))) (if (and repo-list) (user-repo-list-aux user (+ pg 1) all) all))) (defun fetch-user-repo-list (user) (user-repo-list-aux user 1 '())) (defun load-svc-user-repo-list (svc user) (file-to-form (str-cat blip-repos-index svc "/" user))) (defun cache-svc-user-repo-list (svc user) (form-to-file (fetch-user-repo-list user) (str-cat blip-repos-index svc "/" user))) (setf git-jobs 0) (defun update-git-cmd-status (proc stat sig) (print "stat") (print stat) (decf git-jobs) (if (= git-jobs 0) (cl-async:exit-event-loop))) (defun git-cmd (cmd dir &optional remote) (pushdir dir) (cl-async:spawn "git" (if (and remote) (list cmd remote) (list cmd)) :exit-cb #'update-git-cmd-status) (incf git-jobs) (popdir) ) (defun git-cmd-svc-user (cmd svc user &optional remote) (git-cmd cmd (str-cat blip-repos svc "/" user "/") remote)) (defun github-pull-joyent (user-repo) ) (defun localhost-clone (path) ;(git-clone path (str-cat blip-repos "localhost/" (car (last (str-split "/" path)))));) (defun github-clone-user-all (user) (map 'list #'(lambda (remote) (git-cmd-svc-user "clone" "github" user remote)) (repo-specs-to-github-urls (load-svc-user-repo-list "github" user)))) (defun github-clone-user-all-bg (user) (cl-async:start-event-loop #'(lambda () (github-clone-user-all user)))) (defun github-clone-joyent-all () (github-clone-user-all-bg "joyent")) (defun github-pull-user-all (user) (map 'list #'(lambda (user-repo) (git-cmd-svc-user "pull" "github" user-repo)) (load-svc-user-repo-list "github" user))) (defun github-pull-user-all-bg (user) (cl-async:start-event-loop #'(lambda () (github-pull-user-all user)))) (defun github-pull-joyent-all () (github-pull-user-all-bg "joyent")) (defun github-clone-daly (remote) (git-cmd-svc-user "clone" "github" "daly" remote)) (defun github-pull-daly (user-repo) (git-cmd-svc-user "pull" "github" user-repo)) (defun github-clone-daly-all% () (map 'list #'github-clone-daly (repo-specs-to-github-urls (load-svc-user-repo-list "github" "daly")))) (defun github-clone-daly-all () (cl-async:start-event-loop #'github-clone-daly-all%)) (defun github-pull-daly-all% () (map 'list #'github-pull-daly (load-svc-user-repo-list "github" "daly"))) (defun github-pull-daly-all () (cl-async:start-event-loop #'github-pull-daly-all%)) (defun gerrit-clone-joyent (remote) (git-cmd-svc-user "clone" "gerrit" "joyent" remote)) (defun gerrit-pull-joyent (user-repo) (if (file-exists-p (str-cat blip-repos "gerrit" "/" user-repo "/")) (git-cmd-svc-user "pull" "gerrit" user-repo))) (defun gerrit-clone-joyent-all% () (map 'list #'gerrit-clone-joyent (repo-specs-to-gerrit-urls (load-svc-user-repo-list "github" "joyent")))) (defun gerrit-clone-joyent-all () (cl-async:start-event-loop #'gerrit-clone-joyent-all%)) (defun gerrit-fetch-joyent-all-patches () (cl-async:start-event-loop #'gerrit-clone-joyent-all%)) (defun gerrit-pull-joyent-all% () (map 'list #'gerrit-pull-joyent (load-svc-user-repo-list "github" "joyent"))) (defun gerrit-pull-joyent-all () (cl-async:start-event-loop #'gerrit-pull-joyent-all%)) (defun git-switch-branch (branch) (assert (and branch)) (inferior-shell:run/ss (list "git" "checkout" branch))) (defun git-clone (path dest) (assert (and path dest)) (inferior-shell:run/ss (list "git" "clone" path dest))) (defun git-log-repo (repo &optional branch) (let ((curbr (git-current-branch repo))) (pushdir (str-cat blip-repos repo "/")) (if (and branch) (git-switch-branch branch)) (let ((log (inferior-shell:run/ss (list "git" "--no-pager" "log" "--name-status")))) (if (and branch) (git-switch-branch curbr)) (popdir) log) ) ) (defun git-ls-remote (repo) (pushdir (str-cat blip-repos repo "/")) (let ((remotes (inferior-shell:run/ss (list "git" "ls-remote" "origin")))) (popdir) remotes) ) (defun git-ls-branches (repo) (pushdir (str-cat blip-repos repo "/")) (let ((branches (inferior-shell:run/ss (list "git" "branch")))) (popdir) (let ((bs (str-split "[\\n\\r\\s]+" branches))) (iter:iter (iter:for b in bs) (if (and (not (equal "*" b)) ( not(equal "" b))) (iter:collect b)))) )) (defun git-fetch-remote (repo targ) (let ((branches (git-ls-branches repo)) (branch (cadr (str-split ":" targ)))) (if (not (member branch branches :test #'equal)) (progn (pushdir (str-cat blip-repos repo "/")) (let ((out (inferior-shell:run/ss (list "git" "fetch" "origin" targ)))) (popdir))) ))) (defun git-log-urepo (svc user repo) (git-log-repo (str-cat svc "/" user "/" repo "/")) ) (defun git-current-branch (repo) (pushdir (str-cat blip-repos repo "/")) (let ((cb (inferior-shell:run/ss (list "git" "rev-parse" "--abbrev-ref" "HEAD")))) (popdir) cb ) ) (defun git-branch-commit (commit) (assert (and commit)) (inferior-shell:run/ss (list "git" "checkout" "-B" "blip_tmp_branch" commit)) ) (defun git-unbranch (curbr) (inferior-shell:run/ss (list "git" "checkout" curbr)) (inferior-shell:run/ss (list "git" "branch" "-d" "blip_tmp_branch")) ) (defun starts-w-newline (ls) (and ls (listp ls) (characterp (car ls)) (CHAR= #\Newline (car ls)))) (defun is-just-newline (ls) (and (starts-w-newline ls) (< (length ls) 3))) (defun commits-aux (stack head tail) (tagbody again (cond ((and (is-just-newline head) (match-str-list "commit" (car tail))) (stack-pushr stack head) (stack-pushr stack (head-n tail 3)) (advance-scanner 4) (go again)) ((and tail) (stack-pushr stack head) (advance-scanner) (go again)) )) (stack-list stack) ) (defun commits (ls) (pushr (commits-aux (make-instance 'stack) '(#\Newline) ls) '(#\Newline))) (defun is-author-or-date (ls) (or (match-str-list "Author" ls) (match-str-list "Date" ls))) (defun author-date-aux (stack head tail) (tagbody again (cond ((and (is-just-newline (stack-last stack)) (is-author-or-date head)) (let ((ls '())) (tagbody lsagain (cond ((not (starts-w-newline head)) (pushr! ls head) (advance-scanner) (go lsagain)) ((and t) (stack-pushr stack ls) (go again)) )))) ((and tail) (stack-pushr stack head) (advance-scanner) (go again)) ((and t) (stack-pushr stack head) ) ) ) (stack-list stack) ) (defun author-date (ls) (author-date-aux (make-instance 'stack) '(#\Newline) ls)) (defun file-mod-list (acc head tail) (if (not (starts-w-newline head)) (file-mod-list (pushr acc head) (car tail) (cdr tail)) (list acc (cons head tail)))) (defun is-file-mod-char (ls) (and (is-word-group ls) (= (length ls) 1))) (defun file-mods-aux (stack head tail) (tagbody again (cond ((and (is-just-newline (stack-last stack)) (is-file-mod-char head)) (let ((ls '())) (tagbody lsagain (cond ((not (starts-w-newline head)) (pushr! ls head) (advance-scanner) (go lsagain)) ((and t) (stack-pushr stack ls) (go again)) )))) ((and tail) (stack-pushr stack head) (advance-scanner) (go again)) ((and t) (stack-pushr stack head)) )) (stack-list stack)) (defun file-mods (ls) (file-mods-aux (make-instance 'stack) '(#\Newline) ls)) (defun git-strip-commit-msgs (ast) (let ((acc nil)) (walk-tree ast #'is-commit-or-file-mod #'(lambda (n s w) (pushr! acc n)) '() '()) acc ) ) (defun cache-git-log (repo &optional branch) (let* ((branchname (if (and branch) branch (git-current-branch repo))) (dir (str-cat blip-repo-meta repo "/br/" branchname "/")) (status (mkdir dir)) (log-file (str-cat dir "git.log")) (full-ast nil)) (mkdir dir) (setf full-ast (pipeline repo #'(lambda (r) (git-log-repo r branch)) #'str-to-char-ls #'white-space #'words #'punctuations #'commits #'author-date #'file-mods)) (form-to-file (git-strip-commit-msgs full-ast) log-file) ) ) (defun cache-git-log-breakdown (repo &optional branch) (let* ((branchname (if (and branch) branch (git-current-branch repo))) (dir (str-cat blip-repo-meta repo "/br/" branchname "/")) (status (mkdir dir)) (log-file (str-cat dir "git.log"))) (multiple-value-bind (form timing) (pipeline repo #'(lambda (r) (git-log-repo r branch)) #'str-to-char-ls #'white-space #'words #'punctuations #'commits #'author-date #'file-mods) (print timing)) )) (defun test-cache-git-log () (cache-git-log "gerrit/joyent/sdc-docker" "CH-145-1")) (defun test-cache-git-log-breakdown () (cache-git-log-breakdown "gerrit/joyent/sdc-docker" "CH-145-1")) (defun cache-git-log-all-branches (repo) (let ((branches (git-ls-branches repo))) (map 'nil #'(lambda (b) (cache-git-log repo b)) branches))) (defun git-refs-aux (stack head tail) (tagbody again (cond ((and (is-blank-group (stack-last stack)) (CHAR= #\Tab (caar (stack-last stack)))) (let ((ls '())) (tagbody lsagain (cond ((or (is-blank-group head) (not head)) (stack-pushr stack ls) (go again)) ((and t) (pushr! ls head) (advance-scanner) (go lsagain)) ) ) )) ((and head) (stack-pushr stack head) (advance-scanner) (go again)) ) ) (stack-list stack) ) (defun git-refs (ls) (git-refs-aux (make-instance 'stack) (car ls) (cdr ls))) (defun is-git-ref (ls) (and ls (listp ls) (= (length ls) 9) (match-str-list "refs" (car ls)) (match-str-list "/" (cadr ls)) (match-str-list "changes" (caddr ls)) (match-str-list "/" (cadddr ls)))) (defun change-patch-triple (ls) (list (nth 4 ls) (nth 6 ls) (nth 8 ls))) (defun refs-to-triples (ls) (map 'list #'change-patch-triple ls)) (defun triple-to-branch (ls) (let ((changelet (char-ls-to-str (car ls))) (change (char-ls-to-str (cadr ls))) (patch (char-ls-to-str (caddr ls)))) (str-cat "CH-" change "-" patch))) (defun triple-to-ref (ls) (let ((changelet (char-ls-to-str (car ls))) (change (char-ls-to-str (cadr ls))) (patch (char-ls-to-str (caddr ls)))) (str-cat "refs/changes/" changelet "/" change "/" patch))) (defun triple-to-target-str (ls) (str-cat (triple-to-ref ls) ":" (triple-to-branch ls))) (defun triples-to-targs (ls) (map 'list #'triple-to-target-str ls)) (defun cache-git-remotes (repo &optional branch) (let* ((branchname (if (and branch) branch (git-current-branch repo))) (dir (str-cat blip-repo-meta repo "/br/" branchname "/")) (status (mkdir dir)) (remote-file (str-cat dir "git.remotes"))) (form-to-file (pipeline repo #'git-ls-remote #'str-to-char-ls #'white-space #'blanks #'words #'punctuations #'git-refs) remote-file ))) (defun load-git-remotes (repo &optional branch) (let* ((branchname (if (and branch) branch (git-current-branch repo))) (dir (str-cat blip-repo-meta repo "/br/" branchname "/")) (remote-file (str-cat dir "git.remotes"))) (file-to-form remote-file))) (defun extract-git-refs (ast) (let ((ref-ls '())) (walk-tree ast #'is-git-ref #'(lambda (x p w) (if (is-git-ref x) (pushr! ref-ls x))) '() '()) ref-ls)) (defun fetchable-remote-targs (repo) (triples-to-targs (refs-to-triples (extract-git-refs (load-git-remotes repo))))) (defun fetch-git-remotes (repo) (map 'nil #'(lambda (targ) (git-fetch-remote repo targ)) (fetchable-remote-targs repo))) (defun load-git-log (repo &optional branch) (let ((branchname (if (and branch) branch (git-current-branch repo)))) (file-to-form (str-cat blip-repo-meta repo "/br/" branchname "/" "git.log")))) (defun cache-git-log-urepo (svc user repo) (cache-git-log (str-cat svc "/" user "/" repo)) ) (defun load-git-log-urepo (svc user repo) (load-git-log (str-cat svc "/" user "/" repo)) ) (defun is-commit (ls) (and (listp ls) (match-str-list "commit" (car ls)))) (defun is-file-mod (ls) (and (listp ls) (is-word-group (car ls)) (= 1 (length (car ls))))) (defun is-commit-or-file-mod (ls) (or (is-commit ls) (is-file-mod ls))) (defun file-mod-stringify-path (ls) (if (is-file-mod ls) (char-ls-to-str (cddr (reduce #'append ls))))) (defun print-form (n s w) (if (is-commit n) (print (caddr n)) (print (file-mod-stringify-path n)) )) (defun build-ast-dir (repo) (pushdir (str-cat blip-asts repo)) (map 'nil #'(lambda (f) (mkdir (str-cat (cwd) "/" f))) (git-show-ftree-all-time repo)) (popdir) ) (defun build-meta-dir (repo) (let* ((dir (str-cat blip-repo-meta repo "/root"))) (mkdir dir) (pushdir dir) (map 'nil #'(lambda (f) (mkdir (str-cat (cwd) "/" f))) (git-show-ftree-all-time repo)) (popdir) ) ) (defun strap-git-repo (repo) (build-meta-dir repo) (build-ast-dir repo)) (defun git-show-ftree (repo commit) (assert (and repo commit)) (let ((tree nil)) (pushdir (str-cat blip-repos repo "/")) (setf tree (inferior-shell:run/ss (list "git" "ls-tree" "-r" "--name-only" "--full-tree" commit))) (popdir) (str-split "\\n" tree) )) (defun files-present-at-commit (repo commit) (git-show-ftree repo commit)) (defun git-show-ftree-all-time (repo) (let ((tree nil)) (pushdir (str-cat blip-repos repo "/")) (setf tree (inferior-shell:run/ss (list "git" "log" "--pretty=format:" "--name-only" "--diff-filter=A"))) (popdir) (sort (remove-duplicates (remove-if #'(lambda (e) (equal e "")) (str-split "\\n" tree)) :test #'equal) #'string<) ) ) (defun git-head-commit (repo) (let ((hc nil)) (pushdir (str-cat blip-repos repo "/")) (setf hc (inferior-shell:run/ss (list "git" "rev-parse" "HEAD"))) (popdir) hc )) (defun git-root-commits (repo) "Used to get root commits (like the first commit, and merges)" (let ((rc nil)) (pushdir (str-cat blip-repos repo "/")) (setf rc (inferior-shell:run/ss (list "git" "rev-list" "--max-parents=0" "HEAD"))) (popdir) (str-split "\\n" rc) )) (defun git-file-latest-commit (repo path) "Only works for files that are present in current branch" (let ((lc nil)) (pushdir (str-cat blip-repos repo "/")) (setf lc (inferior-shell:run/ss (list "git" "rev-list" "-1" "HEAD" "--" path))) (popdir) lc ;(str-split "\\n" lc) )) (defun git-file-latest-commit-until (repo path commit) "Only works for files that are present in current branch" (let ((lc nil)) (pushdir (str-cat blip-repos repo "/")) (setf lc (inferior-shell:run/ss (list "git" "rev-list" "-1" commit "--" path))) (popdir) lc ;(str-split "\\n" lc) )) (defun git-file-all-commits (repo path) "Only works for files that are present in current branch" (let ((lc nil)) (pushdir (str-cat blip-repos repo "/")) (setf lc (inferior-shell:run/ss (list "git" "rev-list" "HEAD" path))) (popdir) (str-split "\\n" lc) )) (defun git-amend-log-misdeletion (repo file commit) (let* ((outdir (str-cat blip-repo-meta repo "/amends/")) (out (str-cat outdir commit)) (append-to nil)) (mkdir outdir) (setf append-to (file-to-form out)) (form-to-file (remove-duplicates (pushr append-to (list 'misdeletion file))) out) ) ) (defun load-git-log-amendments (repo commit) (let* ((file (str-cat blip-repo-meta repo "/amends/" commit))) (file-to-form file) ) ) (defun is-misdeleted (amends file) (let ((ret nil)) (map 'nil #'(lambda (a) (if (and (equal (car a) 'misdeletion) (equal (cadr a) file)) (setf ret t))) amends) ret ) ) (defun apply-git-log-amends (repo commit file-list) (let* ((amends (load-git-log-amendments repo commit))) (remove nil (map 'list #'(lambda (f) (if (is-misdeleted amends f) nil f)) file-list)) ) ) (defun parse-x-files-at-commit (repo commit &key force suf pref parser whitelist antipref) (expand-commit! repo commit) (let ((files (files-present-at-commit repo commit)) (curbr (git-current-branch repo))) (pushdir (str-cat blip-repos repo)) (git-branch-commit commit) (map 'nil #'(lambda (file) (if (and (if (and suf) (is-str-suffix suf file) t) (if (and pref) (is-str-prefix pref file) t) (if (and antipref) (not (is-str-prefix antipref file)) t) ) (let* ((slot (str-cat blip-asts repo "/" file)) (revid (git-file-latest-commit repo file)) (fullpath (str-cat slot "/" revid)) (full-src-path (str-cat (cwd) "/" file))) (cond ((and (is-file-p full-src-path) (or (and force (file-exists-p fullpath)) (not (file-exists-p fullpath)))) (if (or (not whitelist) (member file whitelist :test #'equal)) (form-to-file (funcall parser (file-to-char-ls full-src-path)) fullpath))) ((not (is-file-p full-src-path)) (assert nil) )) ))) files) (git-unbranch curbr) (popdir) )) (defun expand-commit (repo commit) (if (equal commit :head) (git-head-commit repo) commit)) (lol:defmacro! expand-commit! (r c) `(setf ,c (expand-commit ,r ,c))) (defun list-files-at-commit (repo commit &key suf pref antipref) (expand-commit! repo commit) (let ((files (files-present-at-commit repo commit)) (list '())) (assert files) (map 'nil #'(lambda (file) (if (and (if (and suf) (is-str-suffix suf file) t) (if (and pref) (is-str-prefix pref file) t) (if (and antipref) (not (is-str-prefix antipref file)) t) ) (pushr! list file))) files) (stable-sort list #'string<) ) ) (defun ast-path (repo file commit) (expand-commit! repo commit) (let* ((revid (git-file-latest-commit-until repo file commit))) (str-cat blip-asts repo "/" file "/" revid))) (defun load-ast (repo file commit) (file-to-form (ast-path repo file commit))) (defun js-path-cat-aux (str ls files) (let* ((dstr (str-cat str (car ls) "/")) (fstr (str-cat str (car ls) ".js")) (lfstr (str-cat str (car ls))) (istr (str-cat str (car ls) "/index.js")) (exists (member lfstr files :test #'equal)) (fexists (member fstr files :test #'equal)) (iexists (member istr files :test #'equal))) (cond ((and ls (cdr ls)) (js-path-cat-aux dstr (cdr ls) files)) ((and ls (not (cdr ls)) fexists) (js-path-cat-aux fstr (cdr ls) files)) ((and ls (not (cdr ls)) iexists) (js-path-cat-aux istr (cdr ls) files)) ((and ls (not (cdr ls)) exists) (js-path-cat-aux lfstr (cdr ls) files)) ((and t) str)))) (defun js-path-cat (pls files) (js-path-cat-aux "" pls files)) (defun expand-path (current path &key when-module) (let ((c (popr (str-split "/" current)))) (if (or (= 1 (length path)) (= 0 (length (car path))) ;an absolute path in the FS (CHAR/= #\. (char (car path) 0))) (if (not when-module) nil path) (progn (map 'nil #'(lambda (p) (cond ((equal p "..") (popr! c)) ((not (equal p ".")) (pushr! c p)))) path) c) ))) (defun js-file-deps (repo file commit files) (let* ((ast (load-ast repo file commit)) (reqs (get-require-arg0 ast)) (exp-reqs (map 'list #'(lambda (r) (expand-path file r :when-module nil)) reqs)) (raw (map 'list #'(lambda (r) (list file r)) (remove-if #'not exp-reqs))) (pretty (map 'list #'(lambda (e) (list (car e) (js-path-cat (cadr e) files))) raw))) pretty)) (defun js-all-file-deps (repo commit files) (expand-commit! repo commit) (let* ((deps '())) (map 'nil #'(lambda (f) (pushr! deps (js-file-deps repo f commit files))) files) (reduce #'append (remove-if #'not deps))) ) (defun js-cache-file-deps (repo commit files) (expand-commit! repo commit) (let ((dir (str-cat blip-repo-meta repo "/deps")) (dep-table (js-all-file-deps repo commit files))) (mkdir dir) (pushdir dir) (form-to-file dep-table (str-cat dir "/" commit)) (popdir) ) ) (defun js-load-file-deps (repo commit) (expand-commit! repo commit) (let* ((file (str-cat blip-repo-meta repo "/deps/" commit))) (file-to-form file) )) (defun js-fdeps (repo commit files &optional force) (expand-commit! repo commit) (let ((deps (if (and force) nil (js-load-file-deps repo commit)))) (cond ((not deps) (js-cache-file-deps repo commit files) (setf deps (js-load-file-deps repo commit)) )) deps)) (defun js-what-requires (repo commit dep files &optional force) (let ((ret '()) (table (js-fdeps repo commit files force))) (map 'nil #'(lambda (x) (if (equal dep (cadr x)) (pushr! ret (car x)))) table) ret) ) (defun js-requires-what (repo commit dep files &optional force) (let ((ret '()) (table (js-fdeps repo commit files force))) (map 'nil #'(lambda (x) (if (equal dep (car x)) (pushr! ret (cadr x)))) table) ret) ) (defun get-column (list n) (remove-duplicates (map 'list #'(lambda (e) (car (popl-n e n))) list) :test #'equal)) (defun js-top-deps (repo commit files &optional force) (let* ((table (js-fdeps repo commit files force)) (left (get-column table 0)) (right (get-column table 1)) (left-only '())) (map 'nil #'(lambda (e) (if (not (member e right :test #'equal)) (pushr! left-only e))) left) left-only)) (defun js-bottom-deps (repo commit files &optional force) (let* ((table (js-fdeps repo commit files force)) (left (get-column table 0)) (right (get-column table 1)) (right-only '())) (map 'nil #'(lambda (e) (if (not (member e left :test #'equal)) (pushr! right-only e))) right) right-only)) (defun remove-dep (table dep side) (remove-if #'(lambda (x) (equal dep x)) table :key (if (equal side :left) #'car #'cadr))) (defun mk-ticket (str) (mkdir (str-cat blip-tickets str))) (defun test-fwapi-parse () (let ((target "github/joyent/sdc-fwapi")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-mike-sdb-parse () (let ((target "github/sdimitro/minions")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".c" :pref "sdb" :parser #'c-to-ast) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".h" :pref "sdb" :parser #'c-to-ast) )) (defun test-docker-parse () (let ((target "github/joyent/sdc-docker")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-bunyan-parse () (let ((target "github/trentm/node-bunyan")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-warden-parse () (let ((target "github/joyent/node-restify-warden")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-vasync-parse () (let ((target "github/davepacheco/node-vasync")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-async-parse () (let ((target "github/caolan/async")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-tmux-parse () (let ((target "github/caolan/async")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".c" :parser #'c-to-ast) )) (defun test-cueball-parse () (let ((target "github/joyent/node-cueball")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-mooremachine-parse () (let ((target "github/joyent/node-mooremachine")) (parse-x-files-at-commit target (git-head-commit target) :force t :suf ".js" :parser #'js-to-ast) )) (defun test-docker-create-index () (list "lib/backends/sdc/containers.js" (pipeline (load-ast "github/joyent/sdc-docker" "lib/backends/sdc/containers.js" :head) #'index-all-js-paths))) (defun test-mooremachine-ast () (load-ast "github/joyent/node-mooremachine" "lib/fsm.js" :head)) (defun test-mooremachine-create-index () (list "lib/fsm.js" (pipeline (load-ast "github/joyent/node-mooremachine" "lib/fsm.js" :head) #'index-all-js-paths))) (defun test-mike-create-index () (list "sdb/libsdc/libsdb_lwrap.c" (pipeline (load-ast "github/sdimitro/minions" "sdb/libsdb/libsdb_lwrap.c" :head) #'index-all-c-paths))) (defun test-docker-print-index () (print-js-paths (test-docker-create-index))) (defun test-mooremachine-print-index () (print-js-paths (test-mooremachine-create-index))) (defun test-mooremachine-get-subtree (path &optional pov) (map 'list #'ast-to-str (get-path-subtree path (test-mooremachine-create-index) pov))) (defun test-mike-print-index () (print-js-paths (test-mike-create-index))) (defun test-docker-print-index-raw () (print-js-paths-raw (test-docker-create-index))) (defun test-docker-get-subtree (path &optional pov) (map 'list #'ast-to-str (get-path-subtree path (test-docker-create-index) pov))) (defun test-mike-get-subtree (path &optional pov) (map 'list #'ast-to-str (get-path-subtree path (test-mike-create-index) pov))) (defun test-docker-prefix (pref &optional pov) (get-path-with-prefix pref (test-docker-create-index) pov)) (defun test-docker-suffix (suf &optional pov) (get-path-with-suffix suf (test-docker-create-index) pov)) (defun test-docker-uniq (&optional pov) (uniq-path (test-docker-create-index) :pov pov :fmt t :sort-path t :sort-count t)) (defun test-docker-path-depth (&optional pov) (paths-by-depth (test-docker-create-index) :pov pov :fmt t)) (defun test-mooremachine-path-depth (&optional pov) (paths-by-depth (test-mooremachine-create-index) :pov pov :fmt t)) (defun test-mike-path-depth (&optional pov) (paths-by-depth (test-mike-create-index) :pov pov :fmt t)) (defun test-mooremachine-prefix (pref &optional pov) (get-path-with-prefix pref (test-mooremachine-create-index) pov)) (defun format-alist (alist) (map nil #'(lambda (cell) (format t "~a ~a ~%" (car cell) (cdr cell))) alist)) (defun test-docker-word-count () (format-alist (js-word-count (load-ast "github/joyent/sdc-docker" "lib/backends/sdc/containers.js" :head)))) (defun test-docker-fcall-count () (format-alist (js-fcall-count (load-ast "github/joyent/sdc-docker" "lib/backends/sdc/containers.js" :head)))) (defun test-docker-fcall-params-count () (format-alist (js-fcall-params-count (load-ast "github/joyent/sdc-docker" "lib/backends/sdc/containers.js" :head)))) (defun test-docker-fdef-count () (format-alist (js-fdef-count (load-ast "github/joyent/sdc-docker" "lib/backends/sdc/containers.js" :head)))) (defun test-docker-fcommit-count () (format-alist (file-commit-count (load-git-log "github/joyent/sdc-docker")))) (defun test-docker-req-strs () (let* ((repo "github/joyent/sdc-docker") (file "lib/backends/sdc/containers.js") (reqs (get-require-arg0 (load-ast repo file :head))) (exp-reqs (map 'list #'(lambda (r) (expand-path file r :when-module nil)) reqs))) (map 'list #'(lambda (r) (list file r)) (remove-if #'not exp-reqs)) )) (load "envs.lisp")
170,932
Common Lisp
.lisp
4,752
27.609217
230
0.541792
nickziv/blip
0
0
0
MPL-2.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
574a2f48fa3cae6c431276a3f401e56dab53e1bb7dd1b80b7d62058dce31b8fe
32,244
[ -1 ]
32,265
parse.lisp
epeld_class-files/parse.lisp
(in-package :java-parse) (defun read-chunk (stream &optional (count 512)) "Rpead a chunk of unsigned bytes from a file stream. START can be negative and indicates an offset from the end of the file" (unless (< count 100000) (error "Too high count ~a" count)) (let ((buffer (make-array `(,count) :element-type '(unsigned-byte 8)))) ;; Read as far as possible, then pad with zeroes (loop for i from (read-sequence buffer stream) below (length buffer) do (setf (aref buffer i) 0)) buffer)) (defun read-chunk-from-file (path &optional (count 512)) "Rpead a chunk of unsigned bytes from a file. START can be negative and indicates an offset from the end of the file" (with-open-file (in path :element-type '(unsigned-byte 8)) (let ((buffer (make-array `(,count) :element-type '(unsigned-byte 8)))) ;; Read as far as possible, then pad with zeroes (loop for i from (read-sequence buffer in) below (length buffer) do (setf (aref buffer i) 0)) buffer))) (defun asciip (x) (and (>= x 32) (< x 127))) (defun find-strings (seq &optional (start 0) end) (let ((count 0) found result) (dolist (c seq) ;; Exit the loop (when (and end (zerop (- end start count))) (return)) (incf count) (cond ((< 0 start) (decf start)) (found (if (asciip c) (push (code-char c) found) (progn (push (coerce (reverse found) 'string) result) (setf found nil)))) ((asciip c) (push (code-char c) found)) (t (push c result)))) (when found (push (coerce (reverse found) 'string) result)) (reverse result))) (defparameter magic-number #xcafebabe "Java magic number") (defun number-from-bytes (buffer &optional (count (length buffer))) (let ((number 0)) (loop for i from 0 below count do (setf number (logior number (ash (aref buffer i) (* 8 (- count i 1))))) finally (return number)))) (defun read-unsigned-int (stream count) "Read an unsigned integer from the stream, consisting of COUNT shifted unsigned bytes ored together. BIG ENDIAN" (let ((buffer (make-array `(,count) :element-type '(unsigned-byte 8)))) (unless (eql count (read-sequence buffer stream :end count)) (error "Expected to read ~a unsigned bytes" count)) (number-from-bytes buffer count))) (defun read-signed-int (stream count) "Read an signed integer from the stream, consisting of COUNT shifted unsigned bytes ored together. BIG ENDIAN twos complement" (let ((buffer (make-array `(,count)))) (unless (eql count (read-sequence buffer stream :end count)) (error "Expected to read ~a unsigned bytes" count)) (number-from-bytes buffer count))) (defun read-string (stream length) "Read a UTF-8 encoded string consisting of LENGTH bytes" ;;(declare (optimize debug)) (let ((buffer (make-array `(,length)))) (unless (eql length (read-sequence buffer stream :end length)) (error "Expected to read a string of byte-length ~a" length)) ;; Convert to character (loop for ix from 0 below length do (setf (aref buffer ix) (code-char (aref buffer ix)))) (coerce buffer 'string))) (defun read-length-string (stream) "Read a length followed by a utf-8-like string" (read-string stream (read-unsigned-int stream 2))) (defun read-constant-pool-string-entry (stream) "Read an entry from the constant pool entry table" (let ((string (read-string stream (read-unsigned-int stream 2)))) `(:string ,string))) (defun read-constant-pool-integer-entry (stream) "Read an entry from the constant pool entry table" (let ((int (read-signed-int stream 4))) `(:integer ,int))) (defun read-constant-pool-long-entry (stream) "Read an entry from the constant pool entry table" (let ((int (read-signed-int stream 8))) `(:long ,int))) (defun read-constant-pool-float-entry (stream) "Read an entry from the constant pool entry table" (let ((uint (read-unsigned-int stream 4))) `(:float ,(ieee-floats:decode-float32 uint)))) (defun read-constant-pool-double-entry (stream) "Read an entry from the constant pool entry table" (let ((uint (read-unsigned-int stream 8))) `(:double ,(ieee-floats:decode-float64 uint)))) (defun read-constant-pool-method-reference (stream) "Read an entry from the constant pool entry table" (let* ((class-ix (read-unsigned-int stream 2)) (name-ix (read-unsigned-int stream 2))) `(:method-reference ,class-ix ,name-ix))) (defun read-constant-pool-interface-method-reference (stream) "Read an entry from the constant pool entry table" (let* ((class-ix (read-unsigned-int stream 2)) (name-ix (read-unsigned-int stream 2))) `(:interface-method-reference ,class-ix ,name-ix))) (defun read-constant-pool-field-reference (stream) "Read an entry from the constant pool entry table" (let* ((class-ix (read-unsigned-int stream 2)) (name-ix (read-unsigned-int stream 2))) `(:field-reference ,class-ix ,name-ix))) (defun read-constant-pool-string-reference (stream) "Read an entry from the constant pool entry table" (let* ((ix (read-unsigned-int stream 2))) `(:string-reference ,ix))) (defun read-constant-pool-class-reference (stream) "Read an entry from the constant pool entry table" (let* ((ix (read-unsigned-int stream 2))) `(:class-reference ,ix))) (defun read-constant-pool-type-decriptor (stream) "Read an entry from the constant pool entry table" (let* ((name-ix (read-unsigned-int stream 2)) (type-ix (read-unsigned-int stream 2))) `(:type-descriptor ,name-ix ,type-ix))) (defun read-constant-pool-method-handle (stream) "Read an entry from the constant pool entry table" (let* ((type-descriptor (read-unsigned-int stream 8)) (index (read-unsigned-int stream 2))) `(:method-handle ,type-descriptor ,index))) (defun read-constant-pool-method-type (stream) "Read an entry from the constant pool entry table" (let* ((index (read-unsigned-int stream 2))) `(:method-type ,index))) (defun read-constant-pool-invoke-dynamic (stream) "Read an entry from the constant pool entry table" (declare (ignore stream)) (cerror "Use placeholder" "Invoke dynamic constant pool entries currently unsupported") '(:invoke-dynamic-placeholder)) (defun resolve-constant-references (entry table) (loop for item in entry collect (if (numberp item) (resolve-constant-references (aref table (1- item)) table) item))) (defun compile-constant-table (constants) (let ((table (make-array `(,(length constants)) :initial-contents constants))) (loop for ix from 0 below (length table) do (setf (aref table ix) (resolve-constant-references (aref table ix) table))) table)) (defun read-constant-pool-entry (stream) "Read an entry from the constant pool entry table" (let ((tag (read-unsigned-int stream 1))) (cond ((eql tag 5) (list (read-constant-pool-long-entry stream) nil)) ((eql tag 6) (list (read-constant-pool-double-entry stream) nil)) (t (list (ecase tag (1 (read-constant-pool-string-entry stream)) (3 (read-constant-pool-integer-entry stream)) (4 (read-constant-pool-float-entry stream)) (7 (read-constant-pool-class-reference stream)) (8 (read-constant-pool-string-reference stream)) (9 (read-constant-pool-field-reference stream)) (10 (read-constant-pool-method-reference stream)) (11 (read-constant-pool-interface-method-reference stream)) (12 (read-constant-pool-type-decriptor stream)) (15 (read-constant-pool-method-handle stream)) (16 (read-constant-pool-invoke-dynamic stream)))))))) (defun read-utf8-info (stream) (let* ((tag (read-unsigned-int stream 1))) `(:utf8 ,tag ,(read-length-string stream)))) (defun parse-code-attribute (stream constants) (declare (optimize debug)) (let* ((max-stack (read-unsigned-int stream 2)) (max-locals (read-unsigned-int stream 2)) (code-length (read-unsigned-int stream 4)) (code (read-chunk stream code-length)) (exception-table-length (read-unsigned-int stream 2)) (exception-table (loop for i from 1 upto exception-table-length collect (read-exception-table-entry stream))) (attr-count (read-unsigned-int stream 2)) (attrs (loop for i from 1 upto attr-count collect (read-attribute stream constants)))) `(:code (:max-stack ,max-stack) (:max-locals ,max-locals) (:exceptions ,exception-table) ,attrs ,code))) (defun read-attribute (stream constants) ;;(declare (optimize debug)) (let ((name (string-constant constants (read-unsigned-int stream 2))) (length (read-unsigned-int stream 4))) (cond ((string= name "Code") (parse-code-attribute stream constants)) ((string= name "SourceFile") `(:source-file ,(string-constant constants (read-unsigned-int stream 2)))) ((string= name "Exceptions") `(:exceptions ,(loop for i from 0 below (read-unsigned-int stream 2) collect (string-constant constants (read-unsigned-int stream 2))))) (t `(:attribute ,name ,(read-chunk stream length)))))) (defun read-field (stream constants) "Read a field_info structure" ;; (declare (optimize debug)) (let* ((access-flags (read-unsigned-int stream 2)) (name-index (read-unsigned-int stream 2)) (descriptor-index (read-unsigned-int stream 2)) (attributes-count (read-unsigned-int stream 2)) ;;(foo (break "HERE")) (attributes (loop for i from 1 upto attributes-count collect (read-attribute stream constants)))) (make-instance 'java-field :access-flags (decode-field-access-flags access-flags) :name (string-constant constants name-index) :attributes attributes :descriptor (decode-type-descriptor (string-constant constants descriptor-index))))) (defun read-method (stream constants) "Read a method_info structure" (let* ((access-flags (read-unsigned-int stream 2)) (name-index (read-unsigned-int stream 2)) (descriptor-index (read-unsigned-int stream 2)) (attributes-count (read-unsigned-int stream 2)) (attributes (loop for i from 1 upto attributes-count collect (read-attribute stream constants)))) (make-instance 'java-method :access-flags (decode-method-access-flags access-flags) :name (string-constant constants name-index) :attributes attributes :descriptor (decode-type-descriptor (string-constant constants descriptor-index))))) ;; See https://en.wikipedia.org/wiki/Class_(file_format)#File_layout_and_structure (defun parse-class-stream (stream) (declare (optimize debug)) (let* (major minor constant-pool-count constants access-flags interface-count interfaces fields-count fields methods-count methods attributes-count attributes this-class-ix super-class-ix) ;; Magic number checking 4 bytes (let ((number (read-unsigned-int stream 4))) (unless (eql magic-number number) (error "Not a class file ~a ~a" magic-number number))) ;; Minor version 2 bytes (setf minor (read-unsigned-int stream 2)) ;; Major version 2 bytes (setf major (read-unsigned-int stream 2)) ;; Constant pool count 2 bytes (setf constant-pool-count (read-unsigned-int stream 2)) (let ((index 1) (entries (make-array (list constant-pool-count) :initial-element nil))) (loop do (loop for item in (read-constant-pool-entry stream) do (setf (aref entries index) item) (incf index)) until (>= index constant-pool-count)) (setf constants entries)) ;; Access flags (setf access-flags (read-unsigned-int stream 2)) ;; This class (setf this-class-ix (read-unsigned-int stream 2)) ;; Super class (setf super-class-ix (read-unsigned-int stream 2)) ;; Interface count (setf interface-count (read-unsigned-int stream 2)) (setf interfaces (loop for i from 1 upto interface-count collect (read-unsigned-int stream 2))) (setf fields-count (read-unsigned-int stream 2)) (setf fields (loop for i from 1 upto fields-count collect (read-field stream constants))) (setf methods-count (read-unsigned-int stream 2)) (setf methods (loop for i from 1 upto methods-count collect (read-method stream constants))) (setf attributes-count (read-unsigned-int stream 2)) (setf attributes (loop for i from 1 upto attributes-count collect (read-attribute stream constants))) (make-instance 'java-class :access-flags (decode-class-access-flags access-flags) :major major :minor minor :constants constants :interfaces interfaces :fields fields :methods methods :attributes attributes :this-index this-class-ix :super-index super-class-ix))) (defun parse-class-file (path) (with-open-file (in path :element-type '(unsigned-byte 8)) (parse-class-stream in))) (defun read-exception-table-entry (stream) (let* ((start-pc (read-unsigned-int stream 2)) (end-pc (read-unsigned-int stream 2)) (handler-pc (read-unsigned-int stream 2)) (catch-type (read-unsigned-int stream 2))) `(:exception-table-entry ,start-pc ,end-pc ,handler-pc ,catch-type)))
14,488
Common Lisp
.lisp
318
37.069182
118
0.639794
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
6f745717f4c4102ae23b099ebe981339bc9e2c492bfd2e2dbc60e026240aa2f7
32,265
[ -1 ]
32,266
opcode-parse.lisp
epeld_class-files/opcode-parse.lisp
(in-package :java-parse) (loop for op in raw-opcodes when (search "invoke" (first op)) collect op) (defvar raw-opcodes nil "Cached list of opcodes") (defun read-raw-opcodes () (with-open-file (in "opcodes.lisp" :direction :input) (read in))) (setf raw-opcodes (read-raw-opcodes)) ;; ;; Opcode Parsing ;; (defun parse-opcodes () (let ((codes (read-raw-opcodes))) (loop for opcode in codes collect `(,(parse-integer (second opcode) :radix 16) . ,(lispify-opcode-mnemonic (first opcode)))))) (defparameter opcode-alist (parse-opcodes)) (defun opcode-string (opcode) "Translate an opcode number to its mnemonic string value" (let ((s (cdr (assoc opcode opcode-alist)))) (unless s (cerror "Ignore" "Unknown opcode ~a" opcode)) s)) (defun string-opcode (string) "Lookup an opcode's byte value, given its string mnemonic" (let ((op (rassoc string opcode-alist :test #'string=))) (unless op (cerror "Ignore" "Unknown opcode mnemonic ~a" string)) op)) (defun parse-operand-string (string) (unless (zerop (length string)) (let ((nr (subseq string 0 (search '(#\:) string)))) (if (or (find #\+ nr) (find #\/ nr)) (cerror "OK" "Unhandled ~a" nr) (parse-integer nr))))) (defun operand-string-special-case-p (string) (or (find #\+ string) (find #\/ string))) (defparameter operand-special-cases (loop for op in raw-opcodes when (operand-string-special-case-p (fourth op)) collect (parse-integer (second op) :radix 16)) "All opcodes that require special treatment when counting their operands") (quote (loop for op in raw-opcodes unless (or (zerop (length (fourth op))) (operand-string-special-case-p (fourth op))) collect (fourth op))) (defparameter operand-opcodes-alist (loop for op in raw-opcodes unless (or (zerop (length (fourth op))) (operand-string-special-case-p (fourth op))) collect `(,(parse-integer (second op) :radix 16) . ,(parse-operand-string (fourth op)))) "All opcodes that take operands (minus special cases) in an alist with their respective operand count") (defun opcode-operand-count (opcode) "Return how many operands an opcode requires" (when (member opcode operand-special-cases) (error "Operand special case ~s requires context" (opcode-string opcode))) (or (cdr (assoc opcode operand-opcodes-alist)) 0)) (defun parse-instruction (stream) "Parse an opcode along with its operands (if any)" (let* ((opcode (read-unsigned-int stream 1)) (operands (opcode-operand-count opcode))) (if (find opcode operand-special-cases) (error "Special case operands not supported yet") `(,(opcode-string opcode) ,@(loop for i from 1 upto operands collect (read-unsigned-int stream 1)))))) (defparameter code-example #(42 43 3 43 190 182 0 16 172)) ;; (parse-instructions code-example) (defun parse-instructions (machine-code) "Given a sequence of machine codes, parse it into 'human readable' form" (flexi-streams:with-input-from-sequence (in machine-code) (let (codes) (loop do (push (ignore-errors (parse-instruction in)) codes) until (null (car codes))) (reverse (cdr codes))))) (defun lispify-opcode-mnemonic (string) "Convert an opcode mnemonic into a keyword" (loop for i from 0 below (length string) do (setf (aref string i) (if (eq (aref string i) #\_) #\- (aref string i)))) (intern (string-upcase string))) (defparameter invoking-opcodes (loop for op in raw-opcodes when (search "invoke" (first op)) collect (lispify-opcode-mnemonic (first op)))) (defparameter storing-opcodes (loop for op in raw-opcodes when (search "store" (first op)) collect (lispify-opcode-mnemonic (first op)))) (defparameter loading-opcodes (loop for op in raw-opcodes when (search "load" (first op)) collect (lispify-opcode-mnemonic (first op))))
4,128
Common Lisp
.lisp
96
36.760417
110
0.659825
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
969122a45b0d7bdc2ba9d930bbb7b2970b8bf9e446b7ccf1efcb0884f6f54d85
32,266
[ -1 ]
32,267
package.lisp
epeld_class-files/package.lisp
(ql:quickload :zip) (ql:quickload :flexi-streams) (ql:quickload 'ieee-floats) (defpackage :java (:nicknames :java-class :java-parse :java-jar) (:use :cl :ieee-floats :flexi-streams :zip) (:export :read-jar :java-class-name :referenced-classes :system-class-p :standard-class-p :class-info-string :class-fields :class-methods :field-info-string :field-access-flags :field-name :field-type-descriptor :method-parsed-machine-code :method-info-string :method-access-flags :method-name :method-type-descriptor)) (ql:quickload :hunchentoot) (ql:quickload :cl-who) (defpackage :server (:use :cl :hunchentoot :cl-who :java)) #| (defpackage :java-class (:use :cl) (:export :java-class :java-method)) (defpackage :java-parse (:use :cl :java-class) (:export :parse-class-stream :parse-class-file)) (defpackage :java-jar (:use :cl :java-parse :java-class) (:export :read-jar)) |#
1,099
Common Lisp
.lisp
40
20.7
48
0.609943
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
fba6912edc511a76d2284f87d4993cf002d0b5284d0fd6498521e9d009ab585f
32,267
[ -1 ]
32,268
server.lisp
epeld_class-files/server.lisp
(in-package :server) (defvar server-instance nil "The global server instance, when running") (defun start-server (&optional force) "Start the server.." (when (and server-instance (not force)) (cerror "Continue anyway" "Server already running. Really start again?!")) (setf server-instance (make-instance 'hunchentoot:easy-acceptor :port 8080)) (start server-instance) :ok) (defun stop-server () "Stop the server" (hunchentoot:stop server-instance) (setf server-instance nil) :ok) (defvar known-classes nil "List of known classes") (defun load-jar (path) "Load a new jar file with all contained classes into the list of known classes. Returns the number of new classes added" (let ((len (length known-classes))) (setf known-classes (union (read-jar path) known-classes :key #'java-class-name :test #'string=)) (setf known-classes (sort known-classes #'string<= :key #'java-class-name)) (- (length known-classes) len))) (hunchentoot:define-easy-handler (home :uri "/home") (jar-file) (let ((num-known (length known-classes)) (num-loaded (if jar-file (load-jar (first jar-file)) 0))) (cl-who:with-html-output-to-string (s) (:h1 "Hello") (unless (zerop (+ num-loaded num-known)) (htm (:div (str (format nil "~a known java classes. " (+ num-loaded num-known))) (:a :href "/classes" "View the Class List!")))) (:div ) (:div "To add classes, please POST a jar file below and you will receive info") (:hr) (when jar-file (htm (:p (str (format nil "Jar file ~s loaded (~a new classes)~%" (second jar-file) num-loaded))) (:hr))) (:form :name "file-upload" :method "post" :enctype "multipart/form-data" (:label :for "jar-file" "Jar File:") (:input :type "file" :name "jar-file" :size "1000000") (:input :type "submit" :name "upload" :value "Upload"))))) (hunchentoot:define-easy-handler (class-list :uri "/classes") () (cl-who:with-html-output-to-string (s) (:h1 "List of Known Classes") (:div "You can add more classes by uploading jar-files on " (:a :href "/home" "the index-page")) (:ul (loop for c in known-classes do (htm (:li (:a :href (str (format nil "/class/~a" (java-class-name c))) (str (java-class-name c))))))))) (defun render-not-found-page () (with-html-output-to-string (s) (:h1 "404 - Not Found") (:a :href "/classes" "Back to Class List"))) (defun render-class-page (class) (let ((render-code nil)) (with-html-output-to-string (s) (:h1 (str "Class Overview - ") (str (java-class-name class))) (:h3 (str (class-info-string class))) (:a :href "/classes" "Back to Class List") (:hr) (:div (:h2 "Fields") (:ul (loop for f in (class-fields class) do (htm (:li (:b (str (escape-string (field-name f)))) (str " - ") (str (escape-string (field-info-string f)))))))) (:div (:h2 "Methods") (:ul (loop for m in (class-methods class) do (htm (:li (:b (str (escape-string (method-name m)))) (str " - ") (str (escape-string (method-info-string m))) ;; Note: Comment this out too see the byte code (when render-code (:small (loop for instr in (method-parsed-machine-code m) do (htm (:div (str (format nil "~a" instr)))))))))))) (:div (:h2 "Referenced Classes") (:ul (loop for c in (referenced-classes class) unless (standard-class-p c) do (htm (:li (:a :href (str (format nil "/class/~a" c)) (str c)))))))))) (defun class-handler () (when (search "/class/" (request-uri*) :end2 (length "/class/")) (let* ((name (subseq (request-uri*) (length "/class/"))) (class (find name known-classes :key #'java-class-name :test #'string=))) (if class (render-class-page class) (render-not-found-page))))) (defun my-handler () (class-handler)) (defvar class-dispatcher (create-prefix-dispatcher "/class/" #'my-handler)) (pushnew class-dispatcher *dispatch-table*)
4,461
Common Lisp
.lisp
105
33.695238
122
0.572825
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
da6f27cdb787c5e9515a77b230c86dc57f031729f9a9eb9490b3074187898052
32,268
[ -1 ]
32,269
jar.lisp
epeld_class-files/jar.lisp
(in-package :java-jar) (defun suffixp (suffix string) "Return true if STRING is suffixed by SUFFIX" (search suffix string :from-end t)) (defun system-class-p (string) "Predicate for filtering out 'system'-like classes, e.g junit etc so that only user defined classes remain" (or (search "org/junit" string) (search "org/hamcrest" string) (search "junit/" string))) (defun read-jar (file-path &optional (user t)) (zip:with-zipfile (z file-path) (let (classes) (zip:do-zipfile-entries (name entry z) (when (suffixp ".class" name) (let ((stream (flexi-streams:make-in-memory-input-stream (zip:zipfile-entry-contents entry)))) (push (parse-class-stream stream) classes)))) ;; Filter if necessary (if user (let ((user-classes (remove-if #'system-class-p classes :key #'java-class-name))) (values user-classes (- (length classes) (length user-classes)))) (values classes 0))))) (defparameter test-classes (read-jar "~/jedit.jar"))
1,046
Common Lisp
.lisp
24
37.541667
109
0.662389
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
a59b78d346931d245729dd1960debc83cfe9e0364c52ec093a531d0488a64672
32,269
[ -1 ]
32,270
opcodes.lisp
epeld_class-files/opcodes.lisp
(("aaload" "32" "0011 0010" "" "arrayref, index → value" "load onto the stack a reference from an array") ("aastore" "53" "0101 0011" "" "arrayref, index, value →" "store into a reference in an array") ("aconst_null" "01" "0000 0001" "" "→ null" "push a <i>null</i> reference onto the stack") ("aload" "19" "0001 1001" "1: index" "→ objectref" "load a reference onto the stack from a local variable <i>#index</i>") ("aload_0" "2a" "0010 1010" "" "→ objectref" "load a reference onto the stack from local variable 0") ("aload_1" "2b" "0010 1011" "" "→ objectref" "load a reference onto the stack from local variable 1") ("aload_2" "2c" "0010 1100" "" "→ objectref" "load a reference onto the stack from local variable 2") ("aload_3" "2d" "0010 1101" "" "→ objectref" "load a reference onto the stack from local variable 3") ("anewarray" "bd" "1011 1101" "2: indexbyte1, indexbyte2" "count → arrayref" "create a new array of references of length <i>count</i> and component type identified by the class reference <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>) in the constant pool") ("areturn" "b0" "1011 0000" "" "objectref → [empty]" "return a reference from a method") ("arraylength" "be" "1011 1110" "" "arrayref → length" "get the length of an array") ("astore" "3a" "0011 1010" "1: index" "objectref →" "store a reference into a local variable <i>#index</i>") ("astore_0" "4b" "0100 1011" "" "objectref →" "store a reference into local variable 0") ("astore_1" "4c" "0100 1100" "" "objectref →" "store a reference into local variable 1") ("astore_2" "4d" "0100 1101" "" "objectref →" "store a reference into local variable 2") ("astore_3" "4e" "0100 1110" "" "objectref →" "store a reference into local variable 3") ("athrow" "bf" "1011 1111" "" "objectref → [empty], objectref" "throws an error or exception (notice that the rest of the stack is cleared, leaving only a reference to the Throwable)") ("baload" "33" "0011 0011" "" "arrayref, index → value" "load a byte or Boolean value from an array") ("bastore" "54" "0101 0100" "" "arrayref, index, value →" "store a byte or Boolean value into an array") ("bipush" "10" "0001 0000" "1: byte" "→ value" "push a <i>byte</i> onto the stack as an integer <i>value</i>") ("breakpoint" "ca" "1100 1010" "" "" "reserved for breakpoints in Java debuggers; should not appear in any class file") ("caload" "34" "0011 0100" "" "arrayref, index → value" "load a char from an array") ("castore" "55" "0101 0101" "" "arrayref, index, value →" "store a char into an array") ("checkcast" "c0" "1100 0000" "2: indexbyte1, indexbyte2" "objectref → objectref" "checks whether an <i>objectref</i> is of a certain type, the class reference of which is in the constant pool at <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("d2f" "90" "1001 0000" "" "value → result" "convert a double to a float") ("d2i" "8e" "1000 1110" "" "value → result" "convert a double to an int") ("d2l" "8f" "1000 1111" "" "value → result" "convert a double to a long") ("dadd" "63" "0110 0011" "" "value1, value2 → result" "add two doubles") ("daload" "31" "0011 0001" "" "arrayref, index → value" "load a double from an array") ("dastore" "52" "0101 0010" "" "arrayref, index, value →" "store a double into an array") ("dcmpg" "98" "1001 1000" "" "value1, value2 → result" "compare two doubles") ("dcmpl" "97" "1001 0111" "" "value1, value2 → result" "compare two doubles") ("dconst_0" "0e" "0000 1110" "" "→ 0.0" "push the constant <i>0.0</i> (a <i>double</i>) onto the stack") ("dconst_1" "0f" "0000 1111" "" "→ 1.0" "push the constant <i>1.0</i> (a <i>double</i>) onto the stack") ("ddiv" "6f" "0110 1111" "" "value1, value2 → result" "divide two doubles") ("dload" "18" "0001 1000" "1: index" "→ value" "load a double <i>value</i> from a local variable <i>#index</i>") ("dload_0" "26" "0010 0110" "" "→ value" "load a double from local variable 0") ("dload_1" "27" "0010 0111" "" "→ value" "load a double from local variable 1") ("dload_2" "28" "0010 1000" "" "→ value" "load a double from local variable 2") ("dload_3" "29" "0010 1001" "" "→ value" "load a double from local variable 3") ("dmul" "6b" "0110 1011" "" "value1, value2 → result" "multiply two doubles") ("dneg" "77" "0111 0111" "" "value → result" "negate a double") ("drem" "73" "0111 0011" "" "value1, value2 → result" "get the remainder from a division between two doubles") ("dreturn" "af" "1010 1111" "" "value → [empty]" "return a double from a method") ("dstore" "39" "0011 1001" "1: index" "value →" "store a double <i>value</i> into a local variable <i>#index</i>") ("dstore_0" "47" "0100 0111" "" "value →" "store a double into local variable 0") ("dstore_1" "48" "0100 1000" "" "value →" "store a double into local variable 1") ("dstore_2" "49" "0100 1001" "" "value →" "store a double into local variable 2") ("dstore_3" "4a" "0100 1010" "" "value →" "store a double into local variable 3") ("dsub" "67" "0110 0111" "" "value1, value2 → result" "subtract a double from another") ("dup" "59" "0101 1001" "" "value → value, value" "duplicate the value on top of the stack") ("dup_x1" "5a" "0101 1010" "" "value2, value1 → value1, value2, value1" "insert a copy of the top value into the stack two values from the top. value1 and value2 must not be of the type double or long.") ("dup_x2" "5b" "0101 1011" "" "value3, value2, value1 → value1, value3, value2, value1" "insert a copy of the top value into the stack two (if value2 is double or long it takes up the entry of value3, too) or three values (if value2 is neither double nor long) from the top") ("dup2" "5c" "0101 1100" "" "{value2, value1} → {value2, value1}, {value2, value1}" "duplicate top two stack words (two values, if value1 is not double nor long; a single value, if value1 is double or long)") ("dup2_x1" "5d" "0101 1101" "" "value3, {value2, value1} → {value2, value1}, value3, {value2, value1}" "duplicate two words and insert beneath third word (see explanation above)") ("dup2_x2" "5e" "0101 1110" "" "{value4, value3}, {value2, value1} → {value2, value1}, {value4, value3}, {value2, value1}" "duplicate two words and insert beneath fourth word") ("f2d" "8d" "1000 1101" "" "value → result" "convert a float to a double") ("f2i" "8b" "1000 1011" "" "value → result" "convert a float to an int") ("f2l" "8c" "1000 1100" "" "value → result" "convert a float to a long") ("fadd" "62" "0110 0010" "" "value1, value2 → result" "add two floats") ("faload" "30" "0011 0000" "" "arrayref, index → value" "load a float from an array") ("fastore" "51" "0101 0001" "" "arrayref, index, value →" "store a float in an array") ("fcmpg" "96" "1001 0110" "" "value1, value2 → result" "compare two floats") ("fcmpl" "95" "1001 0101" "" "value1, value2 → result" "compare two floats") ("fconst_0" "0b" "0000 1011" "" "→ 0.0f" "push <i>0.0f</i> on the stack") ("fconst_1" "0c" "0000 1100" "" "→ 1.0f" "push <i>1.0f</i> on the stack") ("fconst_2" "0d" "0000 1101" "" "→ 2.0f" "push <i>2.0f</i> on the stack") ("fdiv" "6e" "0110 1110" "" "value1, value2 → result" "divide two floats") ("fload" "17" "0001 0111" "1: index" "→ value" "load a float <i>value</i> from a local variable <i>#index</i>") ("fload_0" "22" "0010 0010" "" "→ value" "load a float <i>value</i> from local variable 0") ("fload_1" "23" "0010 0011" "" "→ value" "load a float <i>value</i> from local variable 1") ("fload_2" "24" "0010 0100" "" "→ value" "load a float <i>value</i> from local variable 2") ("fload_3" "25" "0010 0101" "" "→ value" "load a float <i>value</i> from local variable 3") ("fmul" "6a" "0110 1010" "" "value1, value2 → result" "multiply two floats") ("fneg" "76" "0111 0110" "" "value → result" "negate a float") ("frem" "72" "0111 0010" "" "value1, value2 → result" "get the remainder from a division between two floats") ("freturn" "ae" "1010 1110" "" "value → [empty]" "return a float") ("fstore" "38" "0011 1000" "1: index" "value →" "store a float <i>value</i> into a local variable <i>#index</i>") ("fstore_0" "43" "0100 0011" "" "value →" "store a float <i>value</i> into local variable 0") ("fstore_1" "44" "0100 0100" "" "value →" "store a float <i>value</i> into local variable 1") ("fstore_2" "45" "0100 0101" "" "value →" "store a float <i>value</i> into local variable 2") ("fstore_3" "46" "0100 0110" "" "value →" "store a float <i>value</i> into local variable 3") ("fsub" "66" "0110 0110" "" "value1, value2 → result" "subtract two floats") ("getfield" "b4" "1011 0100" "2: indexbyte1, indexbyte2" "objectref → value" "get a field <i>value</i> of an object <i>objectref</i>, where the field is identified by field reference in the constant pool <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("getstatic" "b2" "1011 0010" "2: indexbyte1, indexbyte2" "→ value" "get a static field <i>value</i> of a class, where the field is identified by field reference in the constant pool <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("goto" "a7" "1010 0111" "2: branchbyte1, branchbyte2" "[no change]" "goes to another instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("goto_w" "c8" "1100 1000" "4: branchbyte1, branchbyte2, branchbyte3, branchbyte4" "[no change]" "goes to another instruction at <i>branchoffset</i> (signed int constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 24 + branchbyte2 &lt;&lt; 16 + branchbyte3 &lt;&lt; 8 + branchbyte4</span>)") ("i2b" "91" "1001 0001" "" "value → result" "convert an int into a byte") ("i2c" "92" "1001 0010" "" "value → result" "convert an int into a character") ("i2d" "87" "1000 0111" "" "value → result" "convert an int into a double") ("i2f" "86" "1000 0110" "" "value → result" "convert an int into a float") ("i2l" "85" "1000 0101" "" "value → result" "convert an int into a long") ("i2s" "93" "1001 0011" "" "value → result" "convert an int into a short") ("iadd" "60" "0110 0000" "" "value1, value2 → result" "add two ints") ("iaload" "2e" "0010 1110" "" "arrayref, index → value" "load an int from an array") ("iand" "7e" "0111 1110" "" "value1, value2 → result" "perform a bitwise AND on two integers") ("iastore" "4f" "0100 1111" "" "arrayref, index, value →" "store an int into an array") ("iconst_m1" "02" "0000 0010" "" "→ -1" "load the int value −1 onto the stack") ("iconst_0" "03" "0000 0011" "" "→ 0" "load the int value 0 onto the stack") ("iconst_1" "04" "0000 0100" "" "→ 1" "load the int value 1 onto the stack") ("iconst_2" "05" "0000 0101" "" "→ 2" "load the int value 2 onto the stack") ("iconst_3" "06" "0000 0110" "" "→ 3" "load the int value 3 onto the stack") ("iconst_4" "07" "0000 0111" "" "→ 4" "load the int value 4 onto the stack") ("iconst_5" "08" "0000 1000" "" "→ 5" "load the int value 5 onto the stack") ("idiv" "6c" "0110 1100" "" "value1, value2 → result" "divide two integers") ("if_acmpeq" "a5" "1010 0101" "2: branchbyte1, branchbyte2" "value1, value2 →" "if references are equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_acmpne" "a6" "1010 0110" "2: branchbyte1, branchbyte2" "value1, value2 →" "if references are not equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmpeq" "9f" "1001 1111" "2: branchbyte1, branchbyte2" "value1, value2 →" "if ints are equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmpge" "a2" "1010 0010" "2: branchbyte1, branchbyte2" "value1, value2 →" "if <i>value1</i> is greater than or equal to <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmpgt" "a3" "1010 0011" "2: branchbyte1, branchbyte2" "value1, value2 →" "if <i>value1</i> is greater than <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmple" "a4" "1010 0100" "2: branchbyte1, branchbyte2" "value1, value2 →" "if <i>value1</i> is less than or equal to <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmplt" "a1" "1010 0001" "2: branchbyte1, branchbyte2" "value1, value2 →" "if <i>value1</i> is less than <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("if_icmpne" "a0" "1010 0000" "2: branchbyte1, branchbyte2" "value1, value2 →" "if ints are not equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifeq" "99" "1001 1001" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifge" "9c" "1001 1100" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is greater than or equal to 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifgt" "9d" "1001 1101" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is greater than 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifle" "9e" "1001 1110" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is less than or equal to 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("iflt" "9b" "1001 1011" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is less than 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifne" "9a" "1001 1010" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is not 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifnonnull" "c7" "1100 0111" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is not null, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("ifnull" "c6" "1100 0110" "2: branchbyte1, branchbyte2" "value →" "if <i>value</i> is null, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)") ("iinc" "84" "1000 0100" "2: index, const" "[No change]" "increment local variable <i>#index</i> by signed byte <i>const</i>") ("iload" "15" "0001 0101" "1: index" "→ value" "load an int <i>value</i> from a local variable <i>#index</i>") ("iload_0" "1a" "0001 1010" "" "→ value" "load an int <i>value</i> from local variable 0") ("iload_1" "1b" "0001 1011" "" "→ value" "load an int <i>value</i> from local variable 1") ("iload_2" "1c" "0001 1100" "" "→ value" "load an int <i>value</i> from local variable 2") ("iload_3" "1d" "0001 1101" "" "→ value" "load an int <i>value</i> from local variable 3") ("impdep1" "fe" "1111 1110" "" "" "reserved for implementation-dependent operations within debuggers; should not appear in any class file") ("impdep2" "ff" "1111 1111" "" "" "reserved for implementation-dependent operations within debuggers; should not appear in any class file") ("imul" "68" "0110 1000" "" "value1, value2 → result" "multiply two integers") ("ineg" "74" "0111 0100" "" "value → result" "negate int") ("instanceof" "c1" "1100 0001" "2: indexbyte1, indexbyte2" "objectref → result" "determines if an object <i>objectref</i> is of a given type, identified by class reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("invokedynamic" "ba" "1011 1010" "4: indexbyte1, indexbyte2, 0, 0" "[arg1, [arg2 ...]] → result" "invokes a dynamic method and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("invokeinterface" "b9" "1011 1001" "4: indexbyte1, indexbyte2, count, 0" "objectref, [arg1, arg2, ...] → result" "invokes an interface method on object <i>objectref</i> and puts the result on the stack (might be void); the interface method is identified by method reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("invokespecial" "b7" "1011 0111" "2: indexbyte1, indexbyte2" "objectref, [arg1, arg2, ...] → result" "invoke instance method on object <i>objectref</i> and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("invokestatic" "b8" "1011 1000" "2: indexbyte1, indexbyte2" "[arg1, arg2, ...] → result" "invoke a static method and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("invokevirtual" "b6" "1011 0110" "2: indexbyte1, indexbyte2" "objectref, [arg1, arg2, ...] → result" "invoke virtual method on object <i>objectref</i> and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("ior" "80" "1000 0000" "" "value1, value2 → result" "bitwise int OR") ("irem" "70" "0111 0000" "" "value1, value2 → result" "logical int remainder") ("ireturn" "ac" "1010 1100" "" "value → [empty]" "return an integer from a method") ("ishl" "78" "0111 1000" "" "value1, value2 → result" "int shift left") ("ishr" "7a" "0111 1010" "" "value1, value2 → result" "int arithmetic shift right") ("istore" "36" "0011 0110" "1: index" "value →" "store int <i>value</i> into variable <i>#index</i>") ("istore_0" "3b" "0011 1011" "" "value →" "store int <i>value</i> into variable 0") ("istore_1" "3c" "0011 1100" "" "value →" "store int <i>value</i> into variable 1") ("istore_2" "3d" "0011 1101" "" "value →" "store int <i>value</i> into variable 2") ("istore_3" "3e" "0011 1110" "" "value →" "store int <i>value</i> into variable 3") ("isub" "64" "0110 0100" "" "value1, value2 → result" "int subtract") ("iushr" "7c" "0111 1100" "" "value1, value2 → result" "int logical shift right") ("ixor" "82" "1000 0010" "" "value1, value2 → result" "int xor") ("jsr" "a8" "1010 1000" "2: branchbyte1, branchbyte2" "→ address" "jump to subroutine at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 8 + branchbyte2</span>) and place the return address on the stack") ("jsr_w" "c9" "1100 1001" "4: branchbyte1, branchbyte2, branchbyte3, branchbyte4" "→ address" "jump to subroutine at <i>branchoffset</i> (signed int constructed from unsigned bytes <span style=\"font-family: monospace, monospace;\">branchbyte1 &lt;&lt; 24 + branchbyte2 &lt;&lt; 16 + branchbyte3 &lt;&lt; 8 + branchbyte4</span>) and place the return address on the stack") ("l2d" "8a" "1000 1010" "" "value → result" "convert a long to a double") ("l2f" "89" "1000 1001" "" "value → result" "convert a long to a float") ("l2i" "88" "1000 1000" "" "value → result" "convert a long to a int") ("ladd" "61" "0110 0001" "" "value1, value2 → result" "add two longs") ("laload" "2f" "0010 1111" "" "arrayref, index → value" "load a long from an array") ("land" "7f" "0111 1111" "" "value1, value2 → result" "<a href=\"/wiki/Bitwise_operation\" title=\"Bitwise operation\">bitwise</a> AND of two longs") ("lastore" "50" "0101 0000" "" "arrayref, index, value →" "store a long to an array") ("lcmp" "94" "1001 0100" "" "value1, value2 → result" "push 0 if the two longs are the same, 1 if value1 is greater than value2, -1 otherwise") ("lconst_0" "09" "0000 1001" "" "→ 0L" "push <i>0L</i> (the number <a href=\"/wiki/Zero\" class=\"mw-redirect\" title=\"Zero\">zero</a> with type <i>long</i>) onto the stack") ("lconst_1" "0a" "0000 1010" "" "→ 1L" "push <i>1L</i> (the number <a href=\"/wiki/One\" class=\"mw-redirect\" title=\"One\">one</a> with type <i>long</i>) onto the stack") ("ldc" "12" "0001 0010" "1: index" "→ value" "push a constant <i>#index</i> from a constant pool (String, int, float, Class, java.lang.invoke.MethodType, or java.lang.invoke.MethodHandle) onto the stack") ("ldc_w" "13" "0001 0011" "2: indexbyte1, indexbyte2" "→ value" "push a constant <i>#index</i> from a constant pool (String, int, float, Class, java.lang.invoke.MethodType, or java.lang.invoke.MethodHandle) onto the stack (wide <i>index</i> is constructed as <span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("ldc2_w" "14" "0001 0100" "2: indexbyte1, indexbyte2" "→ value" "push a constant <i>#index</i> from a constant pool (double or long) onto the stack (wide <i>index</i> is constructed as <span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("ldiv" "6d" "0110 1101" "" "value1, value2 → result" "divide two longs") ("lload" "16" "0001 0110" "1: index" "→ value" "load a long value from a local variable <i>#index</i>") ("lload_0" "1e" "0001 1110" "" "→ value" "load a long value from a local variable 0") ("lload_1" "1f" "0001 1111" "" "→ value" "load a long value from a local variable 1") ("lload_2" "20" "0010 0000" "" "→ value" "load a long value from a local variable 2") ("lload_3" "21" "0010 0001" "" "→ value" "load a long value from a local variable 3") ("lmul" "69" "0110 1001" "" "value1, value2 → result" "multiply two longs") ("lneg" "75" "0111 0101" "" "value → result" "negate a long") ("lookupswitch" "ab" "1010 1011" "8+: &lt;0–3 bytes padding&gt;, defaultbyte1, defaultbyte2, defaultbyte3, defaultbyte4, npairs1, npairs2, npairs3, npairs4, match-offset pairs..." "key →" "a target address is looked up from a table using a key and execution continues from the instruction at that address") ("lor" "81" "1000 0001" "" "value1, value2 → result" "bitwise OR of two longs") ("lrem" "71" "0111 0001" "" "value1, value2 → result" "remainder of division of two longs") ("lreturn" "ad" "1010 1101" "" "value → [empty]" "return a long value") ("lshl" "79" "0111 1001" "" "value1, value2 → result" "bitwise shift left of a long <i>value1</i> by int <i>value2</i> positions") ("lshr" "7b" "0111 1011" "" "value1, value2 → result" "bitwise shift right of a long <i>value1</i> by int <i>value2</i> positions") ("lstore" "37" "0011 0111" "1: index" "value →" "store a long <i>value</i> in a local variable <i>#index</i>") ("lstore_0" "3f" "0011 1111" "" "value →" "store a long <i>value</i> in a local variable 0") ("lstore_1" "40" "0100 0000" "" "value →" "store a long <i>value</i> in a local variable 1") ("lstore_2" "41" "0100 0001" "" "value →" "store a long <i>value</i> in a local variable 2") ("lstore_3" "42" "0100 0010" "" "value →" "store a long <i>value</i> in a local variable 3") ("lsub" "65" "0110 0101" "" "value1, value2 → result" "subtract two longs") ("lushr" "7d" "0111 1101" "" "value1, value2 → result" "bitwise shift right of a long <i>value1</i> by int <i>value2</i> positions, unsigned") ("lxor" "83" "1000 0011" "" "value1, value2 → result" "bitwise XOR of two longs") ("monitorenter" "c2" "1100 0010" "" "objectref →" "enter monitor for object (\"grab the lock\" – start of synchronized() section)") ("monitorexit" "c3" "1100 0011" "" "objectref →" "exit monitor for object (\"release the lock\" – end of synchronized() section)") ("multianewarray" "c5" "1100 0101" "3: indexbyte1, indexbyte2, dimensions" "count1, [count2,...] → arrayref" "create a new array of <i>dimensions</i> dimensions with elements of type identified by class reference in constant pool <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>); the sizes of each dimension is identified by <i>count1</i>, [<i>count2</i>, etc.]") ("new" "bb" "1011 1011" "2: indexbyte1, indexbyte2" "→ objectref" "create new object of type identified by class reference in constant pool <i>index</i> (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("newarray" "bc" "1011 1100" "1: atype" "count → arrayref" "create new array with <i>count</i> elements of primitive type identified by <i>atype</i>") ("nop" "00" "0000 0000" "" "[No change]" "perform no operation") ("pop" "57" "0101 0111" "" "value →" "discard the top value on the stack") ("pop2" "58" "0101 1000" "" "{value2, value1} →" "discard the top two values on the stack (or one value, if it is a double or long)") ("putfield" "b5" "1011 0101" "2: indexbyte1, indexbyte2" "objectref, value →" "set field to <i>value</i> in an object <i>objectref</i>, where the field is identified by a field reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("putstatic" "b3" "1011 0011" "2: indexbyte1, indexbyte2" "value →" "set static field to <i>value</i> in a class, where the field is identified by a field reference <i>index</i> in constant pool (<span style=\"font-family: monospace, monospace;\">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)") ("ret" "a9" "1010 1001" "1: index" "[No change]" "continue execution from address taken from a local variable <i>#index</i> (the asymmetry with jsr is intentional)") ("return" "b1" "1011 0001" "" "→ [empty]" "return void from method") ("saload" "35" "0011 0101" "" "arrayref, index → value" "load short from array") ("sastore" "56" "0101 0110" "" "arrayref, index, value →" "store short to array") ("sipush" "11" "0001 0001" "2: byte1, byte2" "→ value" "push a short onto the stack as an integer <i>value</i>") ("swap" "5f" "0101 1111" "" "value2, value1 → value1, value2" "swaps two top words on the stack (note that value1 and value2 must not be double or long)") ("tableswitch" "aa" "1010 1010" "16+: [0–3 bytes padding], defaultbyte1, defaultbyte2, defaultbyte3, defaultbyte4, lowbyte1, lowbyte2, lowbyte3, lowbyte4, highbyte1, highbyte2, highbyte3, highbyte4, jump offsets..." "index →" "continue execution from an address in the table at offset <i>index</i>") ("wide" "c4" "1100 0100" "3/5: opcode, indexbyte1, indexbyte2<br /> or<br /> iinc, indexbyte1, indexbyte2, countbyte1, countbyte2" "[same as for corresponding instructions]" "execute <i>opcode</i>, where <i>opcode</i> is either iload, fload, aload, lload, dload, istore, fstore, astore, lstore, dstore, or ret, but assume the <i>index</i> is 16 bit; or execute iinc, where the <i>index</i> is 16 bits and the constant to increment by is a signed 16 bit short"))
28,778
Common Lisp
.lisp
3
9,455.333333
27,974
0.67172
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
8b5c7e6cb93ccd9aef7d13e6d92457b74ce314f3408bded51dbb3ef1531af777
32,270
[ -1 ]
32,271
Sample.class
epeld_class-files/Sample.class
Êþº¾4  MY_INTI ConstantValue!MY_FLOATFB0 MY_StringLjava/lang/String;<init>()VCodeLineNumberTablegetIt()Z<clinit> SourceFile Sample.java  FIFTY FIVE Samplejava/lang/Object    I *·±¬³±
448
Common Lisp
.cl
5
88.6
172
0.324324
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
33284b979e1986a3b4c683e399abe343d572afa0c4e3fee5e72a74c91175a760
32,271
[ -1 ]
32,272
Main.class
epeld_class-files/Main.class
Êþº¾4    <init>()VCodeLineNumberTableMain([Ljava/lang/String;)V SourceFile Main.java  HELLO java/lang/Objectjava/lang/SystemoutLjava/io/PrintStream;java/io/PrintStreamprintln(Ljava/lang/String;)V! *·±   % ²¶±  
400
Common Lisp
.cl
7
56.142857
219
0.411168
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
1a7a5751bbe1ff176c542c3bcff707979f792668b65d1e096f0411de3b03be82
32,272
[ -1 ]
32,277
opcodes2.html
epeld_class-files/opcodes2.html
<table class="wikitable sortable"> <tr> <th scope="col">Mnemonic</th> <th scope="col">Opcode<br /> <i>(in hexadecimal)</i></th> <th>Opcode (in binary)</th> <th scope="col">Other bytes</th> <th scope="col">Stack<br /> [before]→[after]</th> <th scope="col" class="unsortable">Description</th> </tr> <tr> <td>aaload</td> <td>32</td> <td>0011 0010</td> <td></td> <td>arrayref, index → value</td> <td>load onto the stack a reference from an array</td> </tr> <tr> <td>aastore</td> <td>53</td> <td>0101 0011</td> <td></td> <td>arrayref, index, value →</td> <td>store into a reference in an array</td> </tr> <tr> <td>aconst_null</td> <td>01</td> <td>0000 0001</td> <td></td> <td>→ null</td> <td>push a <i>null</i> reference onto the stack</td> </tr> <tr> <td>aload</td> <td>19</td> <td>0001 1001</td> <td>1: index</td> <td>→ objectref</td> <td>load a reference onto the stack from a local variable <i>#index</i></td> </tr> <tr> <td>aload_0</td> <td>2a</td> <td>0010 1010</td> <td></td> <td>→ objectref</td> <td>load a reference onto the stack from local variable 0</td> </tr> <tr> <td>aload_1</td> <td>2b</td> <td>0010 1011</td> <td></td> <td>→ objectref</td> <td>load a reference onto the stack from local variable 1</td> </tr> <tr> <td>aload_2</td> <td>2c</td> <td>0010 1100</td> <td></td> <td>→ objectref</td> <td>load a reference onto the stack from local variable 2</td> </tr> <tr> <td>aload_3</td> <td>2d</td> <td>0010 1101</td> <td></td> <td>→ objectref</td> <td>load a reference onto the stack from local variable 3</td> </tr> <tr> <td>anewarray</td> <td>bd</td> <td>1011 1101</td> <td>2: indexbyte1, indexbyte2</td> <td>count → arrayref</td> <td>create a new array of references of length <i>count</i> and component type identified by the class reference <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>) in the constant pool</td> </tr> <tr> <td>areturn</td> <td>b0</td> <td>1011 0000</td> <td></td> <td>objectref → [empty]</td> <td>return a reference from a method</td> </tr> <tr> <td>arraylength</td> <td>be</td> <td>1011 1110</td> <td></td> <td>arrayref → length</td> <td>get the length of an array</td> </tr> <tr> <td>astore</td> <td>3a</td> <td>0011 1010</td> <td>1: index</td> <td>objectref →</td> <td>store a reference into a local variable <i>#index</i></td> </tr> <tr> <td>astore_0</td> <td>4b</td> <td>0100 1011</td> <td></td> <td>objectref →</td> <td>store a reference into local variable 0</td> </tr> <tr> <td>astore_1</td> <td>4c</td> <td>0100 1100</td> <td></td> <td>objectref →</td> <td>store a reference into local variable 1</td> </tr> <tr> <td>astore_2</td> <td>4d</td> <td>0100 1101</td> <td></td> <td>objectref →</td> <td>store a reference into local variable 2</td> </tr> <tr> <td>astore_3</td> <td>4e</td> <td>0100 1110</td> <td></td> <td>objectref →</td> <td>store a reference into local variable 3</td> </tr> <tr> <td>athrow</td> <td>bf</td> <td>1011 1111</td> <td></td> <td>objectref → [empty], objectref</td> <td>throws an error or exception (notice that the rest of the stack is cleared, leaving only a reference to the Throwable)</td> </tr> <tr> <td>baload</td> <td>33</td> <td>0011 0011</td> <td></td> <td>arrayref, index → value</td> <td>load a byte or Boolean value from an array</td> </tr> <tr> <td>bastore</td> <td>54</td> <td>0101 0100</td> <td></td> <td>arrayref, index, value →</td> <td>store a byte or Boolean value into an array</td> </tr> <tr> <td>bipush</td> <td>10</td> <td>0001 0000</td> <td>1: byte</td> <td>→ value</td> <td>push a <i>byte</i> onto the stack as an integer <i>value</i></td> </tr> <tr> <td>breakpoint</td> <td>ca</td> <td>1100 1010</td> <td></td> <td></td> <td>reserved for breakpoints in Java debuggers; should not appear in any class file</td> </tr> <tr> <td>caload</td> <td>34</td> <td>0011 0100</td> <td></td> <td>arrayref, index → value</td> <td>load a char from an array</td> </tr> <tr> <td>castore</td> <td>55</td> <td>0101 0101</td> <td></td> <td>arrayref, index, value →</td> <td>store a char into an array</td> </tr> <tr> <td>checkcast</td> <td>c0</td> <td>1100 0000</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref → objectref</td> <td>checks whether an <i>objectref</i> is of a certain type, the class reference of which is in the constant pool at <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>d2f</td> <td>90</td> <td>1001 0000</td> <td></td> <td>value → result</td> <td>convert a double to a float</td> </tr> <tr> <td>d2i</td> <td>8e</td> <td>1000 1110</td> <td></td> <td>value → result</td> <td>convert a double to an int</td> </tr> <tr> <td>d2l</td> <td>8f</td> <td>1000 1111</td> <td></td> <td>value → result</td> <td>convert a double to a long</td> </tr> <tr> <td>dadd</td> <td>63</td> <td>0110 0011</td> <td></td> <td>value1, value2 → result</td> <td>add two doubles</td> </tr> <tr> <td>daload</td> <td>31</td> <td>0011 0001</td> <td></td> <td>arrayref, index → value</td> <td>load a double from an array</td> </tr> <tr> <td>dastore</td> <td>52</td> <td>0101 0010</td> <td></td> <td>arrayref, index, value →</td> <td>store a double into an array</td> </tr> <tr> <td>dcmpg</td> <td>98</td> <td>1001 1000</td> <td></td> <td>value1, value2 → result</td> <td>compare two doubles</td> </tr> <tr> <td>dcmpl</td> <td>97</td> <td>1001 0111</td> <td></td> <td>value1, value2 → result</td> <td>compare two doubles</td> </tr> <tr> <td>dconst_0</td> <td>0e</td> <td>0000 1110</td> <td></td> <td>→ 0.0</td> <td>push the constant <i>0.0</i> (a <i>double</i>) onto the stack</td> </tr> <tr> <td>dconst_1</td> <td>0f</td> <td>0000 1111</td> <td></td> <td>→ 1.0</td> <td>push the constant <i>1.0</i> (a <i>double</i>) onto the stack</td> </tr> <tr> <td>ddiv</td> <td>6f</td> <td>0110 1111</td> <td></td> <td>value1, value2 → result</td> <td>divide two doubles</td> </tr> <tr> <td>dload</td> <td>18</td> <td>0001 1000</td> <td>1: index</td> <td>→ value</td> <td>load a double <i>value</i> from a local variable <i>#index</i></td> </tr> <tr> <td>dload_0</td> <td>26</td> <td>0010 0110</td> <td></td> <td>→ value</td> <td>load a double from local variable 0</td> </tr> <tr> <td>dload_1</td> <td>27</td> <td>0010 0111</td> <td></td> <td>→ value</td> <td>load a double from local variable 1</td> </tr> <tr> <td>dload_2</td> <td>28</td> <td>0010 1000</td> <td></td> <td>→ value</td> <td>load a double from local variable 2</td> </tr> <tr> <td>dload_3</td> <td>29</td> <td>0010 1001</td> <td></td> <td>→ value</td> <td>load a double from local variable 3</td> </tr> <tr> <td>dmul</td> <td>6b</td> <td>0110 1011</td> <td></td> <td>value1, value2 → result</td> <td>multiply two doubles</td> </tr> <tr> <td>dneg</td> <td>77</td> <td>0111 0111</td> <td></td> <td>value → result</td> <td>negate a double</td> </tr> <tr> <td>drem</td> <td>73</td> <td>0111 0011</td> <td></td> <td>value1, value2 → result</td> <td>get the remainder from a division between two doubles</td> </tr> <tr> <td>dreturn</td> <td>af</td> <td>1010 1111</td> <td></td> <td>value → [empty]</td> <td>return a double from a method</td> </tr> <tr> <td>dstore</td> <td>39</td> <td>0011 1001</td> <td>1: index</td> <td>value →</td> <td>store a double <i>value</i> into a local variable <i>#index</i></td> </tr> <tr> <td>dstore_0</td> <td>47</td> <td>0100 0111</td> <td></td> <td>value →</td> <td>store a double into local variable 0</td> </tr> <tr> <td>dstore_1</td> <td>48</td> <td>0100 1000</td> <td></td> <td>value →</td> <td>store a double into local variable 1</td> </tr> <tr> <td>dstore_2</td> <td>49</td> <td>0100 1001</td> <td></td> <td>value →</td> <td>store a double into local variable 2</td> </tr> <tr> <td>dstore_3</td> <td>4a</td> <td>0100 1010</td> <td></td> <td>value →</td> <td>store a double into local variable 3</td> </tr> <tr> <td>dsub</td> <td>67</td> <td>0110 0111</td> <td></td> <td>value1, value2 → result</td> <td>subtract a double from another</td> </tr> <tr> <td>dup</td> <td>59</td> <td>0101 1001</td> <td></td> <td>value → value, value</td> <td>duplicate the value on top of the stack</td> </tr> <tr> <td>dup_x1</td> <td>5a</td> <td>0101 1010</td> <td></td> <td>value2, value1 → value1, value2, value1</td> <td>insert a copy of the top value into the stack two values from the top. value1 and value2 must not be of the type double or long.</td> </tr> <tr> <td>dup_x2</td> <td>5b</td> <td>0101 1011</td> <td></td> <td>value3, value2, value1 → value1, value3, value2, value1</td> <td>insert a copy of the top value into the stack two (if value2 is double or long it takes up the entry of value3, too) or three values (if value2 is neither double nor long) from the top</td> </tr> <tr> <td>dup2</td> <td>5c</td> <td>0101 1100</td> <td></td> <td>{value2, value1} → {value2, value1}, {value2, value1}</td> <td>duplicate top two stack words (two values, if value1 is not double nor long; a single value, if value1 is double or long)</td> </tr> <tr> <td>dup2_x1</td> <td>5d</td> <td>0101 1101</td> <td></td> <td>value3, {value2, value1} → {value2, value1}, value3, {value2, value1}</td> <td>duplicate two words and insert beneath third word (see explanation above)</td> </tr> <tr> <td>dup2_x2</td> <td>5e</td> <td>0101 1110</td> <td></td> <td>{value4, value3}, {value2, value1} → {value2, value1}, {value4, value3}, {value2, value1}</td> <td>duplicate two words and insert beneath fourth word</td> </tr> <tr> <td>f2d</td> <td>8d</td> <td>1000 1101</td> <td></td> <td>value → result</td> <td>convert a float to a double</td> </tr> <tr> <td>f2i</td> <td>8b</td> <td>1000 1011</td> <td></td> <td>value → result</td> <td>convert a float to an int</td> </tr> <tr> <td>f2l</td> <td>8c</td> <td>1000 1100</td> <td></td> <td>value → result</td> <td>convert a float to a long</td> </tr> <tr> <td>fadd</td> <td>62</td> <td>0110 0010</td> <td></td> <td>value1, value2 → result</td> <td>add two floats</td> </tr> <tr> <td>faload</td> <td>30</td> <td>0011 0000</td> <td></td> <td>arrayref, index → value</td> <td>load a float from an array</td> </tr> <tr> <td>fastore</td> <td>51</td> <td>0101 0001</td> <td></td> <td>arrayref, index, value →</td> <td>store a float in an array</td> </tr> <tr> <td>fcmpg</td> <td>96</td> <td>1001 0110</td> <td></td> <td>value1, value2 → result</td> <td>compare two floats</td> </tr> <tr> <td>fcmpl</td> <td>95</td> <td>1001 0101</td> <td></td> <td>value1, value2 → result</td> <td>compare two floats</td> </tr> <tr> <td>fconst_0</td> <td>0b</td> <td>0000 1011</td> <td></td> <td>→ 0.0f</td> <td>push <i>0.0f</i> on the stack</td> </tr> <tr> <td>fconst_1</td> <td>0c</td> <td>0000 1100</td> <td></td> <td>→ 1.0f</td> <td>push <i>1.0f</i> on the stack</td> </tr> <tr> <td>fconst_2</td> <td>0d</td> <td>0000 1101</td> <td></td> <td>→ 2.0f</td> <td>push <i>2.0f</i> on the stack</td> </tr> <tr> <td>fdiv</td> <td>6e</td> <td>0110 1110</td> <td></td> <td>value1, value2 → result</td> <td>divide two floats</td> </tr> <tr> <td>fload</td> <td>17</td> <td>0001 0111</td> <td>1: index</td> <td>→ value</td> <td>load a float <i>value</i> from a local variable <i>#index</i></td> </tr> <tr> <td>fload_0</td> <td>22</td> <td>0010 0010</td> <td></td> <td>→ value</td> <td>load a float <i>value</i> from local variable 0</td> </tr> <tr> <td>fload_1</td> <td>23</td> <td>0010 0011</td> <td></td> <td>→ value</td> <td>load a float <i>value</i> from local variable 1</td> </tr> <tr> <td>fload_2</td> <td>24</td> <td>0010 0100</td> <td></td> <td>→ value</td> <td>load a float <i>value</i> from local variable 2</td> </tr> <tr> <td>fload_3</td> <td>25</td> <td>0010 0101</td> <td></td> <td>→ value</td> <td>load a float <i>value</i> from local variable 3</td> </tr> <tr> <td>fmul</td> <td>6a</td> <td>0110 1010</td> <td></td> <td>value1, value2 → result</td> <td>multiply two floats</td> </tr> <tr> <td>fneg</td> <td>76</td> <td>0111 0110</td> <td></td> <td>value → result</td> <td>negate a float</td> </tr> <tr> <td>frem</td> <td>72</td> <td>0111 0010</td> <td></td> <td>value1, value2 → result</td> <td>get the remainder from a division between two floats</td> </tr> <tr> <td>freturn</td> <td>ae</td> <td>1010 1110</td> <td></td> <td>value → [empty]</td> <td>return a float</td> </tr> <tr> <td>fstore</td> <td>38</td> <td>0011 1000</td> <td>1: index</td> <td>value →</td> <td>store a float <i>value</i> into a local variable <i>#index</i></td> </tr> <tr> <td>fstore_0</td> <td>43</td> <td>0100 0011</td> <td></td> <td>value →</td> <td>store a float <i>value</i> into local variable 0</td> </tr> <tr> <td>fstore_1</td> <td>44</td> <td>0100 0100</td> <td></td> <td>value →</td> <td>store a float <i>value</i> into local variable 1</td> </tr> <tr> <td>fstore_2</td> <td>45</td> <td>0100 0101</td> <td></td> <td>value →</td> <td>store a float <i>value</i> into local variable 2</td> </tr> <tr> <td>fstore_3</td> <td>46</td> <td>0100 0110</td> <td></td> <td>value →</td> <td>store a float <i>value</i> into local variable 3</td> </tr> <tr> <td>fsub</td> <td>66</td> <td>0110 0110</td> <td></td> <td>value1, value2 → result</td> <td>subtract two floats</td> </tr> <tr> <td>getfield</td> <td>b4</td> <td>1011 0100</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref → value</td> <td>get a field <i>value</i> of an object <i>objectref</i>, where the field is identified by field reference in the constant pool <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>getstatic</td> <td>b2</td> <td>1011 0010</td> <td>2: indexbyte1, indexbyte2</td> <td>→ value</td> <td>get a static field <i>value</i> of a class, where the field is identified by field reference in the constant pool <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>goto</td> <td>a7</td> <td>1010 0111</td> <td>2: branchbyte1, branchbyte2</td> <td>[no change]</td> <td>goes to another instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>goto_w</td> <td>c8</td> <td>1100 1000</td> <td>4: branchbyte1, branchbyte2, branchbyte3, branchbyte4</td> <td>[no change]</td> <td>goes to another instruction at <i>branchoffset</i> (signed int constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 24 + branchbyte2 &lt;&lt; 16 + branchbyte3 &lt;&lt; 8 + branchbyte4</span>)</td> </tr> <tr> <td>i2b</td> <td>91</td> <td>1001 0001</td> <td></td> <td>value → result</td> <td>convert an int into a byte</td> </tr> <tr> <td>i2c</td> <td>92</td> <td>1001 0010</td> <td></td> <td>value → result</td> <td>convert an int into a character</td> </tr> <tr> <td>i2d</td> <td>87</td> <td>1000 0111</td> <td></td> <td>value → result</td> <td>convert an int into a double</td> </tr> <tr> <td>i2f</td> <td>86</td> <td>1000 0110</td> <td></td> <td>value → result</td> <td>convert an int into a float</td> </tr> <tr> <td>i2l</td> <td>85</td> <td>1000 0101</td> <td></td> <td>value → result</td> <td>convert an int into a long</td> </tr> <tr> <td>i2s</td> <td>93</td> <td>1001 0011</td> <td></td> <td>value → result</td> <td>convert an int into a short</td> </tr> <tr> <td>iadd</td> <td>60</td> <td>0110 0000</td> <td></td> <td>value1, value2 → result</td> <td>add two ints</td> </tr> <tr> <td>iaload</td> <td>2e</td> <td>0010 1110</td> <td></td> <td>arrayref, index → value</td> <td>load an int from an array</td> </tr> <tr> <td>iand</td> <td>7e</td> <td>0111 1110</td> <td></td> <td>value1, value2 → result</td> <td>perform a bitwise AND on two integers</td> </tr> <tr> <td>iastore</td> <td>4f</td> <td>0100 1111</td> <td></td> <td>arrayref, index, value →</td> <td>store an int into an array</td> </tr> <tr> <td>iconst_m1</td> <td>02</td> <td>0000 0010</td> <td></td> <td>→ -1</td> <td>load the int value −1 onto the stack</td> </tr> <tr> <td>iconst_0</td> <td>03</td> <td>0000 0011</td> <td></td> <td>→ 0</td> <td>load the int value 0 onto the stack</td> </tr> <tr> <td>iconst_1</td> <td>04</td> <td>0000 0100</td> <td></td> <td>→ 1</td> <td>load the int value 1 onto the stack</td> </tr> <tr> <td>iconst_2</td> <td>05</td> <td>0000 0101</td> <td></td> <td>→ 2</td> <td>load the int value 2 onto the stack</td> </tr> <tr> <td>iconst_3</td> <td>06</td> <td>0000 0110</td> <td></td> <td>→ 3</td> <td>load the int value 3 onto the stack</td> </tr> <tr> <td>iconst_4</td> <td>07</td> <td>0000 0111</td> <td></td> <td>→ 4</td> <td>load the int value 4 onto the stack</td> </tr> <tr> <td>iconst_5</td> <td>08</td> <td>0000 1000</td> <td></td> <td>→ 5</td> <td>load the int value 5 onto the stack</td> </tr> <tr> <td>idiv</td> <td>6c</td> <td>0110 1100</td> <td></td> <td>value1, value2 → result</td> <td>divide two integers</td> </tr> <tr> <td>if_acmpeq</td> <td>a5</td> <td>1010 0101</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if references are equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_acmpne</td> <td>a6</td> <td>1010 0110</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if references are not equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmpeq</td> <td>9f</td> <td>1001 1111</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if ints are equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmpge</td> <td>a2</td> <td>1010 0010</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if <i>value1</i> is greater than or equal to <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmpgt</td> <td>a3</td> <td>1010 0011</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if <i>value1</i> is greater than <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmple</td> <td>a4</td> <td>1010 0100</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if <i>value1</i> is less than or equal to <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmplt</td> <td>a1</td> <td>1010 0001</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if <i>value1</i> is less than <i>value2</i>, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>if_icmpne</td> <td>a0</td> <td>1010 0000</td> <td>2: branchbyte1, branchbyte2</td> <td>value1, value2 →</td> <td>if ints are not equal, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifeq</td> <td>99</td> <td>1001 1001</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifge</td> <td>9c</td> <td>1001 1100</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is greater than or equal to 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifgt</td> <td>9d</td> <td>1001 1101</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is greater than 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifle</td> <td>9e</td> <td>1001 1110</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is less than or equal to 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>iflt</td> <td>9b</td> <td>1001 1011</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is less than 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifne</td> <td>9a</td> <td>1001 1010</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is not 0, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifnonnull</td> <td>c7</td> <td>1100 0111</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is not null, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>ifnull</td> <td>c6</td> <td>1100 0110</td> <td>2: branchbyte1, branchbyte2</td> <td>value →</td> <td>if <i>value</i> is null, branch to instruction at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>)</td> </tr> <tr> <td>iinc</td> <td>84</td> <td>1000 0100</td> <td>2: index, const</td> <td>[No change]</td> <td>increment local variable <i>#index</i> by signed byte <i>const</i></td> </tr> <tr> <td>iload</td> <td>15</td> <td>0001 0101</td> <td>1: index</td> <td>→ value</td> <td>load an int <i>value</i> from a local variable <i>#index</i></td> </tr> <tr> <td>iload_0</td> <td>1a</td> <td>0001 1010</td> <td></td> <td>→ value</td> <td>load an int <i>value</i> from local variable 0</td> </tr> <tr> <td>iload_1</td> <td>1b</td> <td>0001 1011</td> <td></td> <td>→ value</td> <td>load an int <i>value</i> from local variable 1</td> </tr> <tr> <td>iload_2</td> <td>1c</td> <td>0001 1100</td> <td></td> <td>→ value</td> <td>load an int <i>value</i> from local variable 2</td> </tr> <tr> <td>iload_3</td> <td>1d</td> <td>0001 1101</td> <td></td> <td>→ value</td> <td>load an int <i>value</i> from local variable 3</td> </tr> <tr> <td>impdep1</td> <td>fe</td> <td>1111 1110</td> <td></td> <td></td> <td>reserved for implementation-dependent operations within debuggers; should not appear in any class file</td> </tr> <tr> <td>impdep2</td> <td>ff</td> <td>1111 1111</td> <td></td> <td></td> <td>reserved for implementation-dependent operations within debuggers; should not appear in any class file</td> </tr> <tr> <td>imul</td> <td>68</td> <td>0110 1000</td> <td></td> <td>value1, value2 → result</td> <td>multiply two integers</td> </tr> <tr> <td>ineg</td> <td>74</td> <td>0111 0100</td> <td></td> <td>value → result</td> <td>negate int</td> </tr> <tr> <td>instanceof</td> <td>c1</td> <td>1100 0001</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref → result</td> <td>determines if an object <i>objectref</i> is of a given type, identified by class reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>invokedynamic</td> <td>ba</td> <td>1011 1010</td> <td>4: indexbyte1, indexbyte2, 0, 0</td> <td>[arg1, [arg2 ...]] → result</td> <td>invokes a dynamic method and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>invokeinterface</td> <td>b9</td> <td>1011 1001</td> <td>4: indexbyte1, indexbyte2, count, 0</td> <td>objectref, [arg1, arg2, ...] → result</td> <td>invokes an interface method on object <i>objectref</i> and puts the result on the stack (might be void); the interface method is identified by method reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>invokespecial</td> <td>b7</td> <td>1011 0111</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref, [arg1, arg2, ...] → result</td> <td>invoke instance method on object <i>objectref</i> and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>invokestatic</td> <td>b8</td> <td>1011 1000</td> <td>2: indexbyte1, indexbyte2</td> <td>[arg1, arg2, ...] → result</td> <td>invoke a static method and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>invokevirtual</td> <td>b6</td> <td>1011 0110</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref, [arg1, arg2, ...] → result</td> <td>invoke virtual method on object <i>objectref</i> and puts the result on the stack (might be void); the method is identified by method reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>ior</td> <td>80</td> <td>1000 0000</td> <td></td> <td>value1, value2 → result</td> <td>bitwise int OR</td> </tr> <tr> <td>irem</td> <td>70</td> <td>0111 0000</td> <td></td> <td>value1, value2 → result</td> <td>logical int remainder</td> </tr> <tr> <td>ireturn</td> <td>ac</td> <td>1010 1100</td> <td></td> <td>value → [empty]</td> <td>return an integer from a method</td> </tr> <tr> <td>ishl</td> <td>78</td> <td>0111 1000</td> <td></td> <td>value1, value2 → result</td> <td>int shift left</td> </tr> <tr> <td>ishr</td> <td>7a</td> <td>0111 1010</td> <td></td> <td>value1, value2 → result</td> <td>int arithmetic shift right</td> </tr> <tr> <td>istore</td> <td>36</td> <td>0011 0110</td> <td>1: index</td> <td>value →</td> <td>store int <i>value</i> into variable <i>#index</i></td> </tr> <tr> <td>istore_0</td> <td>3b</td> <td>0011 1011</td> <td></td> <td>value →</td> <td>store int <i>value</i> into variable 0</td> </tr> <tr> <td>istore_1</td> <td>3c</td> <td>0011 1100</td> <td></td> <td>value →</td> <td>store int <i>value</i> into variable 1</td> </tr> <tr> <td>istore_2</td> <td>3d</td> <td>0011 1101</td> <td></td> <td>value →</td> <td>store int <i>value</i> into variable 2</td> </tr> <tr> <td>istore_3</td> <td>3e</td> <td>0011 1110</td> <td></td> <td>value →</td> <td>store int <i>value</i> into variable 3</td> </tr> <tr> <td>isub</td> <td>64</td> <td>0110 0100</td> <td></td> <td>value1, value2 → result</td> <td>int subtract</td> </tr> <tr> <td>iushr</td> <td>7c</td> <td>0111 1100</td> <td></td> <td>value1, value2 → result</td> <td>int logical shift right</td> </tr> <tr> <td>ixor</td> <td>82</td> <td>1000 0010</td> <td></td> <td>value1, value2 → result</td> <td>int xor</td> </tr> <tr> <td>jsr</td> <td>a8</td> <td>1010 1000</td> <td>2: branchbyte1, branchbyte2</td> <td>→ address</td> <td>jump to subroutine at <i>branchoffset</i> (signed short constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 8 + branchbyte2</span>) and place the return address on the stack</td> </tr> <tr> <td>jsr_w</td> <td>c9</td> <td>1100 1001</td> <td>4: branchbyte1, branchbyte2, branchbyte3, branchbyte4</td> <td>→ address</td> <td>jump to subroutine at <i>branchoffset</i> (signed int constructed from unsigned bytes <span style="font-family: monospace, monospace;">branchbyte1 &lt;&lt; 24 + branchbyte2 &lt;&lt; 16 + branchbyte3 &lt;&lt; 8 + branchbyte4</span>) and place the return address on the stack</td> </tr> <tr> <td>l2d</td> <td>8a</td> <td>1000 1010</td> <td></td> <td>value → result</td> <td>convert a long to a double</td> </tr> <tr> <td>l2f</td> <td>89</td> <td>1000 1001</td> <td></td> <td>value → result</td> <td>convert a long to a float</td> </tr> <tr> <td>l2i</td> <td>88</td> <td>1000 1000</td> <td></td> <td>value → result</td> <td>convert a long to a int</td> </tr> <tr> <td>ladd</td> <td>61</td> <td>0110 0001</td> <td></td> <td>value1, value2 → result</td> <td>add two longs</td> </tr> <tr> <td>laload</td> <td>2f</td> <td>0010 1111</td> <td></td> <td>arrayref, index → value</td> <td>load a long from an array</td> </tr> <tr> <td>land</td> <td>7f</td> <td>0111 1111</td> <td></td> <td>value1, value2 → result</td> <td><a href="/wiki/Bitwise_operation" title="Bitwise operation">bitwise</a> AND of two longs</td> </tr> <tr> <td>lastore</td> <td>50</td> <td>0101 0000</td> <td></td> <td>arrayref, index, value →</td> <td>store a long to an array</td> </tr> <tr> <td>lcmp</td> <td>94</td> <td>1001 0100</td> <td></td> <td>value1, value2 → result</td> <td>push 0 if the two longs are the same, 1 if value1 is greater than value2, -1 otherwise</td> </tr> <tr> <td>lconst_0</td> <td>09</td> <td>0000 1001</td> <td></td> <td>→ 0L</td> <td>push <i>0L</i> (the number <a href="/wiki/Zero" class="mw-redirect" title="Zero">zero</a> with type <i>long</i>) onto the stack</td> </tr> <tr> <td>lconst_1</td> <td>0a</td> <td>0000 1010</td> <td></td> <td>→ 1L</td> <td>push <i>1L</i> (the number <a href="/wiki/One" class="mw-redirect" title="One">one</a> with type <i>long</i>) onto the stack</td> </tr> <tr> <td>ldc</td> <td>12</td> <td>0001 0010</td> <td>1: index</td> <td>→ value</td> <td>push a constant <i>#index</i> from a constant pool (String, int, float, Class, java.lang.invoke.MethodType, or java.lang.invoke.MethodHandle) onto the stack</td> </tr> <tr> <td>ldc_w</td> <td>13</td> <td>0001 0011</td> <td>2: indexbyte1, indexbyte2</td> <td>→ value</td> <td>push a constant <i>#index</i> from a constant pool (String, int, float, Class, java.lang.invoke.MethodType, or java.lang.invoke.MethodHandle) onto the stack (wide <i>index</i> is constructed as <span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>ldc2_w</td> <td>14</td> <td>0001 0100</td> <td>2: indexbyte1, indexbyte2</td> <td>→ value</td> <td>push a constant <i>#index</i> from a constant pool (double or long) onto the stack (wide <i>index</i> is constructed as <span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>ldiv</td> <td>6d</td> <td>0110 1101</td> <td></td> <td>value1, value2 → result</td> <td>divide two longs</td> </tr> <tr> <td>lload</td> <td>16</td> <td>0001 0110</td> <td>1: index</td> <td>→ value</td> <td>load a long value from a local variable <i>#index</i></td> </tr> <tr> <td>lload_0</td> <td>1e</td> <td>0001 1110</td> <td></td> <td>→ value</td> <td>load a long value from a local variable 0</td> </tr> <tr> <td>lload_1</td> <td>1f</td> <td>0001 1111</td> <td></td> <td>→ value</td> <td>load a long value from a local variable 1</td> </tr> <tr> <td>lload_2</td> <td>20</td> <td>0010 0000</td> <td></td> <td>→ value</td> <td>load a long value from a local variable 2</td> </tr> <tr> <td>lload_3</td> <td>21</td> <td>0010 0001</td> <td></td> <td>→ value</td> <td>load a long value from a local variable 3</td> </tr> <tr> <td>lmul</td> <td>69</td> <td>0110 1001</td> <td></td> <td>value1, value2 → result</td> <td>multiply two longs</td> </tr> <tr> <td>lneg</td> <td>75</td> <td>0111 0101</td> <td></td> <td>value → result</td> <td>negate a long</td> </tr> <tr> <td>lookupswitch</td> <td>ab</td> <td>1010 1011</td> <td>8+: &lt;0–3 bytes padding&gt;, defaultbyte1, defaultbyte2, defaultbyte3, defaultbyte4, npairs1, npairs2, npairs3, npairs4, match-offset pairs...</td> <td>key →</td> <td>a target address is looked up from a table using a key and execution continues from the instruction at that address</td> </tr> <tr> <td>lor</td> <td>81</td> <td>1000 0001</td> <td></td> <td>value1, value2 → result</td> <td>bitwise OR of two longs</td> </tr> <tr> <td>lrem</td> <td>71</td> <td>0111 0001</td> <td></td> <td>value1, value2 → result</td> <td>remainder of division of two longs</td> </tr> <tr> <td>lreturn</td> <td>ad</td> <td>1010 1101</td> <td></td> <td>value → [empty]</td> <td>return a long value</td> </tr> <tr> <td>lshl</td> <td>79</td> <td>0111 1001</td> <td></td> <td>value1, value2 → result</td> <td>bitwise shift left of a long <i>value1</i> by int <i>value2</i> positions</td> </tr> <tr> <td>lshr</td> <td>7b</td> <td>0111 1011</td> <td></td> <td>value1, value2 → result</td> <td>bitwise shift right of a long <i>value1</i> by int <i>value2</i> positions</td> </tr> <tr> <td>lstore</td> <td>37</td> <td>0011 0111</td> <td>1: index</td> <td>value →</td> <td>store a long <i>value</i> in a local variable <i>#index</i></td> </tr> <tr> <td>lstore_0</td> <td>3f</td> <td>0011 1111</td> <td></td> <td>value →</td> <td>store a long <i>value</i> in a local variable 0</td> </tr> <tr> <td>lstore_1</td> <td>40</td> <td>0100 0000</td> <td></td> <td>value →</td> <td>store a long <i>value</i> in a local variable 1</td> </tr> <tr> <td>lstore_2</td> <td>41</td> <td>0100 0001</td> <td></td> <td>value →</td> <td>store a long <i>value</i> in a local variable 2</td> </tr> <tr> <td>lstore_3</td> <td>42</td> <td>0100 0010</td> <td></td> <td>value →</td> <td>store a long <i>value</i> in a local variable 3</td> </tr> <tr> <td>lsub</td> <td>65</td> <td>0110 0101</td> <td></td> <td>value1, value2 → result</td> <td>subtract two longs</td> </tr> <tr> <td>lushr</td> <td>7d</td> <td>0111 1101</td> <td></td> <td>value1, value2 → result</td> <td>bitwise shift right of a long <i>value1</i> by int <i>value2</i> positions, unsigned</td> </tr> <tr> <td>lxor</td> <td>83</td> <td>1000 0011</td> <td></td> <td>value1, value2 → result</td> <td>bitwise XOR of two longs</td> </tr> <tr> <td>monitorenter</td> <td>c2</td> <td>1100 0010</td> <td></td> <td>objectref →</td> <td>enter monitor for object ("grab the lock" – start of synchronized() section)</td> </tr> <tr> <td>monitorexit</td> <td>c3</td> <td>1100 0011</td> <td></td> <td>objectref →</td> <td>exit monitor for object ("release the lock" – end of synchronized() section)</td> </tr> <tr> <td>multianewarray</td> <td>c5</td> <td>1100 0101</td> <td>3: indexbyte1, indexbyte2, dimensions</td> <td>count1, [count2,...] → arrayref</td> <td>create a new array of <i>dimensions</i> dimensions with elements of type identified by class reference in constant pool <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>); the sizes of each dimension is identified by <i>count1</i>, [<i>count2</i>, etc.]</td> </tr> <tr> <td>new</td> <td>bb</td> <td>1011 1011</td> <td>2: indexbyte1, indexbyte2</td> <td>→ objectref</td> <td>create new object of type identified by class reference in constant pool <i>index</i> (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>newarray</td> <td>bc</td> <td>1011 1100</td> <td>1: atype</td> <td>count → arrayref</td> <td>create new array with <i>count</i> elements of primitive type identified by <i>atype</i></td> </tr> <tr> <td>nop</td> <td>00</td> <td>0000 0000</td> <td></td> <td>[No change]</td> <td>perform no operation</td> </tr> <tr> <td>pop</td> <td>57</td> <td>0101 0111</td> <td></td> <td>value →</td> <td>discard the top value on the stack</td> </tr> <tr> <td>pop2</td> <td>58</td> <td>0101 1000</td> <td></td> <td>{value2, value1} →</td> <td>discard the top two values on the stack (or one value, if it is a double or long)</td> </tr> <tr> <td>putfield</td> <td>b5</td> <td>1011 0101</td> <td>2: indexbyte1, indexbyte2</td> <td>objectref, value →</td> <td>set field to <i>value</i> in an object <i>objectref</i>, where the field is identified by a field reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>putstatic</td> <td>b3</td> <td>1011 0011</td> <td>2: indexbyte1, indexbyte2</td> <td>value →</td> <td>set static field to <i>value</i> in a class, where the field is identified by a field reference <i>index</i> in constant pool (<span style="font-family: monospace, monospace;">indexbyte1 &lt;&lt; 8 + indexbyte2</span>)</td> </tr> <tr> <td>ret</td> <td>a9</td> <td>1010 1001</td> <td>1: index</td> <td>[No change]</td> <td>continue execution from address taken from a local variable <i>#index</i> (the asymmetry with jsr is intentional)</td> </tr> <tr> <td>return</td> <td>b1</td> <td>1011 0001</td> <td></td> <td>→ [empty]</td> <td>return void from method</td> </tr> <tr> <td>saload</td> <td>35</td> <td>0011 0101</td> <td></td> <td>arrayref, index → value</td> <td>load short from array</td> </tr> <tr> <td>sastore</td> <td>56</td> <td>0101 0110</td> <td></td> <td>arrayref, index, value →</td> <td>store short to array</td> </tr> <tr> <td>sipush</td> <td>11</td> <td>0001 0001</td> <td>2: byte1, byte2</td> <td>→ value</td> <td>push a short onto the stack as an integer <i>value</i></td> </tr> <tr> <td>swap</td> <td>5f</td> <td>0101 1111</td> <td></td> <td>value2, value1 → value1, value2</td> <td>swaps two top words on the stack (note that value1 and value2 must not be double or long)</td> </tr> <tr> <td>tableswitch</td> <td>aa</td> <td>1010 1010</td> <td>16+: [0–3 bytes padding], defaultbyte1, defaultbyte2, defaultbyte3, defaultbyte4, lowbyte1, lowbyte2, lowbyte3, lowbyte4, highbyte1, highbyte2, highbyte3, highbyte4, jump offsets...</td> <td>index →</td> <td>continue execution from an address in the table at offset <i>index</i></td> </tr> <tr> <td>wide</td> <td>c4</td> <td>1100 0100</td> <td>3/5: opcode, indexbyte1, indexbyte2<br /> or<br /> iinc, indexbyte1, indexbyte2, countbyte1, countbyte2</td> <td>[same as for corresponding instructions]</td> <td>execute <i>opcode</i>, where <i>opcode</i> is either iload, fload, aload, lload, dload, istore, fstore, astore, lstore, dstore, or ret, but assume the <i>index</i> is 16 bit; or execute iinc, where the <i>index</i> is 16 bits and the constant to increment by is a signed 16 bit short</td> </tr> <tr> <td><i>(no name)</i></td> <td>cb-fd</td> <td></td> <td></td> <td></td> <td>these values are currently unassigned for opcodes and are reserved for future use</td> </tr> </table>
39,613
Common Lisp
.l
1,662
22.591456
317
0.668549
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
397980501fee3d2d2e608bfd25d03d5612464a7a0cb5ceb367eb9fc9bf877f4c
32,277
[ -1 ]
32,283
Sample.java
epeld_class-files/Sample.java
class Sample { public static final int MY_INT = 33; public static final float MY_FLOAT = 44; public static volatile String MY_String = "FIFTY FIVE"; public boolean getIt() { return true; } }
221
Common Lisp
.l
8
22.875
59
0.663507
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
c3ddbb4f8fe12f2071d9253182446f42fe18796f044a70833ec94ada83cbfc1f
32,283
[ -1 ]
32,284
opcode.el
epeld_class-files/opcode.el
(defun read-cell-content () (let (start content) ;; Enter cell (nxml-down-element) (setq start (point)) ;; Go to end of cell content (nxml-up-element) (backward-sexp) (setq content (buffer-substring-no-properties start (point))) (nxml-up-element) content)) (defun parse-row-content () (nxml-down-element) (let (cells) (dolist (ix '(1 2 3 4 5 6)) (push (read-cell-content) cells)) (nxml-up-element) (reverse cells))) (defun skip-header-row () ;; Find first header cell (search-forward "th") ;; Exit th-cell (nxml-up-element) ;; Exit header row (nxml-up-element)) (defun parse-opcodes () "Parse opcode table in an nxml-mode buffer in emacs" (skip-header-row) (let (current all) (while (setq current (ignore-errors (parse-row-content))) (unless (string-match-p "(no name)" (car current)) (push current all))) (reverse all))) (defun compile-opcode-file () (find-file "opcodes2.html") (goto-char (point-min)) (let ((result (parse-opcodes))) (find-file "opcodes.lisp") (erase-buffer) (insert (prin1-to-string `(defparameter opcodes ',result)))))
1,180
Common Lisp
.l
40
25
65
0.653846
epeld/class-files
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
94e3f8a9cdd1617acd79d8f43e821ba6d813351d8363a0309ed5bd5aa863164f
32,284
[ -1 ]
32,299
standing-speed-diff-cube.lisp
tobbelobb_standing-speed-diff-cube/standing-speed-diff-cube.lisp
(defun first-round (l h lh e f mid &optional (temp 190)) (let* ((w (* 2 h)) (r (* 2 (+ l w))) (skirt 10) (lw (* e 6))) (values `((m107) ; Fan off (m104 :s ,temp) ; Set hot end temp (g28) (g92 :x 0 :y 0 :z 0 :e 0) ; Prep nozzle (g1 :z 5 :f 1000) ; Lift nozzle (m109 :s ,temp) ; wait for hot end temperature to be reached (g21) ; set units to millimeters (g90) ; use absolute coordinates (m82) ; use absolute distances for extrusion (g92 :e 0) (g1 :z ,lh) (g1 :x ,(- mid h skirt) :y ,(- mid (/ l 2) skirt) :z ,lh :f ,f) (g1 :x ,(+ mid h skirt) :e ,(* e (+ w (* 2 skirt)))) (g1 :y ,(+ mid (/ l 2) skirt) :e ,(* e (+ w (* 4 skirt) l))) (g1 :x ,(- mid h skirt) :e ,(* e (+ w (* 6 skirt) l w))) (g1 :y ,(- mid (/ l 2) skirt) :e ,(* e (+ w (* 8 skirt) l w l))) (g92 :e 0) ; Skirt done (g1 :x ,(- mid h lw) :y ,(- mid (/ l 2) lw) :z ,lh :f ,f) (g1 :x ,(+ mid h lw) :e ,(* e (+ w (* 2 lw)))) (g1 :y ,(+ mid (/ l 2) lw) :e ,(* e (+ w (* 4 lw) l))) (g1 :x ,(- mid h lw) :e ,(* e (+ w (* 6 lw) l w))) (g1 :y ,(- mid (/ l 2) lw) :e ,(* e (+ w (* 8 lw) l w l))) (g92 :e 0) ; Round one done (g1 :x ,(- mid h) :y ,(- mid (/ l 2)) :z ,0 :f ,f) (g1 :x ,(+ mid h) :y ,(- mid (/ l 2)) :z ,(* lh (/ w r)) :e ,(* (/ w r) e w)) (g1 :x ,(+ mid h) :y ,(+ mid (/ l 2)) :z ,(* lh (/ (+ w l) r)) :e ,(+ (* (/ w r) e w) (* (/ (+ w l) r) e l))) (g1 :x ,(- mid h) :y ,(+ mid (/ l 2)) :z ,(* lh (/ (+ w l w) r)) :e ,(+ (* (/ w r) e w) (* (/ (+ w l) r) e l) (* (/ (+ w l w) r) e w))) (g1 :x ,(- mid h) :y ,(- mid (/ l 2)) :z ,lh :e ,(+ (* (/ w r) e w) (* (/ (+ w l) r) e l) (* (/ (+ w l w) r) e w) (* e l))) (g92 :e 0) ; Round three done (g1 :x ,(+ (- mid h) lw) :y ,(+ (- mid (/ l 2)) lw) :z ,lh :f ,f) (g1 :x ,(- (+ mid h) lw) :e ,(* e (- w (* 2 lw)))) (g1 :y ,(- (+ mid (/ l 2)) lw) :e ,(* e (- (+ w l) (* 4 lw)))) (g1 :x ,(+ (- mid h) lw) :e ,(* e (- (+ w l w) (* 6 lw)))) (g1 :y ,(+ (- mid (/ l 2)) lw) :e ,(* e (- (+ w l w l) (* 8 lw)))) (g1 :x ,(- mid h) :y ,(- mid (/ l 2)) :z ,lh)) (- mid h) lh))) (defun linspace (start stop segs) "Return a list of segs+1 elements evently distributed between start and stop. Start and stop values included." (loop for i from 0 to segs collect (+ start (* (- stop start) (/ i segs))))) (defun x (p) "Extract the x value of gcode or other list p" (destructuring-bind (&key x &allow-other-keys) (rest p) x)) (defun f (p) "Extract the x value of gcode or other list p" (destructuring-bind (&key f &allow-other-keys) (rest p) f)) (defun x-speed0 (xs z l h fl fh segs) (loop with l2 = (/ (* (sqrt 2) l) segs) with flist = (list (+ fl (* (- fh fl) (/ (+ z h) (* (sqrt 2) l)))) (- fh (* (- fh fl) (/ (+ z h) (* (sqrt 2) l))))) repeat (ceiling (/ (length xs) 2)) append (if (evenp (floor (- (first xs) (/ l (sqrt 2)) 0.001) l2)) flist (reverse flist)))) (defun y-speed0 (ys z l h fl fh y-segs) (loop with above? = (> (+ z h) (/ l (sqrt 2))) with zh = (if above? (- (+ z h) (/ l (sqrt 2))) (+ z h)) for y in ys collect (if (evenp (floor y (/ l y-segs))) (if above? (+ fl (* (- fh fl) (/ zh (/ l (sqrt 2))))) (+ fl (* (- fh fl) (/ zh (/ l (sqrt 2)))))) (if above? (- fh (* (- fh fl) (/ zh (/ l (sqrt 2))))) (- fh (* (- fh fl) (/ zh (/ l (sqrt 2))))))))) (defun angle-move (x z l h lh e fl fh mid x-segs y-segs) "Moves printer along x axis. Doesn't change printer's z position." (let ((op0 (if (< (- x mid) 0) ;; A few changes of sign only difference between #'+ ;; left->right moves and right->left moves #'-)) (op1 (if (< (- x mid) 0) #'- #'+)) (op2 (if (< (+ z h) (/ l (sqrt 2))) #'+ #'-))) (let ((lin-x (nreverse (cons (+ mid mid (- x) (funcall op2 (/ (funcall op0 lh) 2))) (remove-if #'(lambda (p) (> (abs (- p mid)) (abs (- x mid)))) (linspace (funcall op0 mid (/ l (sqrt 2))) (funcall op1 mid (/ l (sqrt 2))) x-segs))))) (lin-y (rest (linspace (funcall op1 mid (/ l 2)) (funcall op0 mid (/ l 2)) y-segs))) (lin-z (rest (linspace z (+ z (/ lh 2)) y-segs)))) (values (append (cons '(g92 :e 0) ; The x-moves (mapcar #'(lambda (x e f) (list 'g1 :x x :e e :f f)) lin-x (mapcar #'(lambda (new-x) (* e (abs (- (first (last lin-x)) x)) (/ (- new-x x) (- (first (last lin-x)) x)))) lin-x) (x-speed0 lin-x z l h fl fh x-segs))) (cons '(g92 :e 0) ; The y-moves (mapcar #'(lambda (y z e f) (list 'g1 :y y :z z :e e :f f)) lin-y lin-z (rest (linspace 0 (* e l) y-segs)) (y-speed0 lin-y z l h fl fh y-segs)))) (first (last lin-x)) (first (last lin-z)))))) (defun spir (x z l h lh e fl fh &optional (mid 100) (segs 8) (y-segs 5)) "Make gcode for a full spiral. Also return the last x-position and z-position of the spiral." (multiple-value-bind (gcode1 x1 z1) (angle-move x z l h lh e fl fh mid segs y-segs) (multiple-value-bind (gcode2 x2 z2) (angle-move x1 z1 l h lh e fl fh mid segs y-segs) (values (append gcode1 gcode2) x2 z2)))) (defun last-gcodes () '((m107) ; turn fan off (m104 :s 0) ; turn hot end off (g28 :x 0))) ; home x axis (defun inner-round (x l e f mid) (let ((lw (* 6 e))) (let ((x0 (+ x lw)) (y0 (+ (- mid (/ l 2)) lw)) (x1 (- (+ x (* 2 (abs (- mid x)))) (/ lw 2))) (y2 (- (+ mid (/ l 2)) lw))) `((g92 :e 0) (g1 :x ,x0 :y ,y0 :f ,f) (g1 :x ,x1 :e ,(* e (+ (abs (- x1 x0))))) (g1 :y ,y2 :e ,(* e (+ (abs (- x1 x0)) (abs (- y2 y0))))) (g1 :x ,x0 :e ,(* e (+ (abs (- x1 x0)) (abs (- y2 y0)) (abs (- x1 x0))))) (g1 :y ,y0 :e ,(* e (+ (abs (- x1 x0)) (abs (- y2 y0)) (abs (- x1 x0)) (abs (- y2 y0))))) (g1 :x ,x :y ,(- mid (/ l 2))))))) (defun full-gcode (l h lh e fl fh mid segs y-segs &key (double-wall t)) (multiple-value-bind (first-gcode first-x first-z) (first-round l h lh e fl mid) (append first-gcode ;;'((m106 :s 250)) ; Get cooling fan going (loop with (gcode x z) = (multiple-value-list (spir first-x first-z l h lh e fl fh mid segs y-segs)) with inner-round = (inner-round x l e fh mid) append (if (or (not double-wall) (> (* 12 e) (- (- (* l (sqrt 2)) h) z))) gcode (append gcode inner-round)) do (setf (values gcode x z) (spir x z l h lh e fl fh mid segs y-segs)) (setf inner-round (inner-round x l e fh mid)) while (< z (- (* l (sqrt 2)) h))) (last-gcodes)))) (defun print-gcodes (gcodes &optional (stream t)) (loop for gcode in gcodes do (format stream "~a" (first gcode)) (loop for param in (rest gcode) do (if (numberp param) (format stream "~,3f" param) (format stream " ~a" param))) (format stream "~%"))) (defun make-gcode (filename) (with-open-file (s filename :if-does-not-exist :create :if-exists :supersede :direction :output) (let ((l 100) (h 10) (lh 0.35) (e 0.13) (fl 800) (fh 2500) (mid 100) (segs 8) (y-segs 5) (double-wall t)) (format s "; Gcode generated by standing-speed-diff-cube.lisp~%") (format s "; l ~a~%; h ~a~%; lh ~a~%; e ~a~%; fl ~a~%; fh ~a~%; mid ~a~%; segs ~a~%; y-segs ~a~%; double-wall ~a~%" l h lh e fl fh mid segs y-segs double-wall) (print-gcodes (full-gcode l h lh e fl fh mid segs y-segs :double-wall double-wall) s))))
9,052
Common Lisp
.lisp
189
35.079365
118
0.402373
tobbelobb/standing-speed-diff-cube
0
0
0
GPL-3.0
9/19/2024, 11:42:22 AM (Europe/Amsterdam)
9fbeaab4a5de94b3835ebe74107ac24766a625ddefa02b64e9d80d697d85d654
32,299
[ -1 ]
32,316
xet1.lisp
aaron-lebo_lisp-engine/xet1.lisp
(in-package :xet) (require :cl-opengl) (require :pngload) (require :sdl2) (defparameter *db-path* "comanche.db") (defparameter *create-chunk-radius* 10) (defparameter *render-chunk-radius* 10) (defparameter *delete-chunk-radius* 14) (defparameter *render-sign-radius* 4) (defvar *window*) (defvar *online*) (defun load-texture (active-tex file &optional wrap) (pngload:with-png-in-static-vector (png file :flip-y t) (let ((tex (gl:gen-texture))) (gl:active-texture active-tex) (gl:bind-texture :texture-2d tex) (gl:tex-parameter :texture-2d :texture-min-filter :linear) (gl:tex-parameter :texture-2d :texture-mag-filter :linear) (when wrap (gl:tex-parameter :texture-2d :texture-wrap-s :clamp-to-edge) (gl:tex-parameter :texture-2d :texture-wrap-t :clamp-to-edge)) (gl:tex-image-2d :texture-2d 0 :rgba (pngload:width png) (pngload:height png) 0 :rgba :unsigned-byte (pngload:data png))))) (defclass program () ((id :initarg :id) position normal uv matrix sampler camera timer sky-sampler daylight fog-distance ortho is-sign)) (defun read-file (file) (with-open-file (stream file) (let ((str (make-string (file-length stream)))) (read-sequence str stream) str))) (defun load-shader (program name type) (let ((src (read-file (format nil "shaders/~a_~a.glsl" name type))) (shader (gl:create-shader (if (eq type "vertex") :vertex-shader :fragment-shader)))) (gl:shader-source shader src) (gl:compile-shader shader) (gl:attach-shader program shader) shader)) (defun load-program (name &optional attribs uniforms) (let* ((prg (gl:create-program)) (vert (load-shader prg name "vertex")) (frag (load-shader prg name "fragment")) (program (make-instance 'program :id prg))) (gl:link-program prg) (gl:detach-shader prg vert) (gl:detach-shader prg frag) (gl:delete-shader vert) (gl:delete-shader frag) (loop :for (slot str) :on attribs :by #'cddr :while str :do (setf (slot-value program slot) (gl:get-attrib-location prg str))) (loop :for (slot str) :on uniforms :by #'cddr :while str :do (setf (slot-value program slot) (gl:get-uniform-location prg str))) program)) (defun make-buffer (verts) (let* ((len (length verts)) (arr (gl:alloc-gl-array :float len)) (buf (gl:gen-buffer))) (gl:bind-buffer :array-buffer buf) (dotimes (i len) (setf (gl:glaref arr i) (aref verts i))) (gl:buffer-data :array-buffer :static-draw arr) (gl:free-gl-array arr) (gl:bind-buffer :array-buffer 0) buf)) (defparameter *rgb* #(0.5 0.5 0.5)) (defun render-swap (buf program) (gl:clear :color-buffer-bit :depth-buffer-bit) (gl:use-program program) (gl:uniformfv (gl:get-uniform-location program "color") *rgb*) (gl:enable-vertex-attrib-array 0) (gl:bind-buffer :array-buffer buf) (gl:vertex-attrib-pointer 0 3 :float nil 0 (cffi:null-pointer)) (gl:draw-arrays :triangles 0 3) (gl:disable-vertex-attrib-array 0) (gl:use-program 0) (sdl2:gl-swap-window *window*)) (defun main () (sdl2:with-init (:everything) (sdl2:gl-set-attr :context-major-version 3) (sdl2:gl-set-attr :context-minor-version 3) (sdl2:with-window (win :flags '(:opengl :shown)) (setf *window* win) (sdl2:with-gl-context (gl-context win) (sdl2:gl-make-current win gl-context) (gl:enable :cull-face) (gl:enable :depth-test) (gl:logic-op :invert) (gl:clear-color 0.0 0.0 0.0 1.0) (load-texture :texture0 "textures/texture.png") (load-texture :texture1 "textures/font.png") (load-texture :texture2 "textures/sky.png" t) (load-texture :texture3 "textures/sign.png") (let ((block-prg (load-program "block" '(position "position" normal "normal" uv "uv") '(matrix "matrix" sampler "sampler" camera "camera" timer "timer" sky-sampler "sky_sampler" daylight "daylight" fog-distance "fog_distance" ortho "ortho"))) (line-prg (load-program "line" '(position "position") '(matrix "matrix"))) (text-prg (load-program "text" '(position "position" uv "uv") '(matrix "matrix" sampler "sampler" is-sign "is_sign"))) (sky-prg (load-program "sky" '(position "position" normal "normal" uv "uv") '(matrix "matrix" sampler "sampler" timer "timer"))) (triangle-prg (load-program "triangle")) (vao (gl:gen-vertex-array)) (buf (make-buffer #(-0.5 -0.5 0.0 0.5 -0.5 0.0 0.0 0.5 0.0)))) (gl:bind-vertex-array vao) (sdl2:with-event-loop (:method :poll) (:idle () (render-swap buf (slot-value triangle-prg 'id))) (:quit () t)))))))
5,719
Common Lisp
.lisp
137
29.927007
129
0.541487
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
1acaea400a2e9361941c0a36584fe5c1e26602e4e6b8130740f45460f67797c0
32,316
[ -1 ]
32,317
xet.lisp
aaron-lebo_lisp-engine/xet.lisp
(in-package :xet) (require :cl-opengl) (require :pngload) (require :sdl2) (defparameter *rgb* #(0.5 0.5 0.5)) (defvar *window*) (defclass program () ((id :initarg :id))) (defun read-file (path) (with-open-file (stream path) (let ((str (make-string (file-length stream)))) (read-sequence str stream) str))) (defun load-shader (program name type) (let ((src (read-file (format nil "shaders/~a_~a.glsl" name type))) (shader (gl:create-shader (if (eq type "vertex") :vertex-shader :fragment-shader)))) (gl:shader-source shader src) (gl:compile-shader shader) (gl:attach-shader program shader) shader)) (defun load-program (name &optional attribs uniforms) (let* ((prg (gl:create-program)) (vert (load-shader prg name "vertex")) (frag (load-shader prg name "fragment")) (program (make-instance 'program :id prg))) (gl:link-program prg) (loop :for shader :in (list vert frag) :do (gl:detach-shader prg shader) (gl:delete-shader shader)) (loop :for (slot str) :on attribs :by #'cddr :while str :do (setf (slot-value program slot) (gl:get-attrib-location prg str))) (loop :for (slot str) :on uniforms :by #'cddr :while str :do (setf (slot-value program slot) (gl:get-uniform-location prg str))) program)) (defun make-buffer (items &optional (type :array-buffer)) (let* ((len (length items)) (arr (gl:alloc-gl-array (if (eq type :array-buffer) :float :unsigned-short) len)) (buf (gl:gen-buffer))) (gl:bind-buffer type buf) (dotimes (i len) (setf (gl:glaref arr i) (aref items i))) (gl:buffer-data type :static-draw arr) (gl:free-gl-array arr) (gl:bind-buffer type 0) buf)) (defun render-swap (vertex-buf index-buf program) (gl:clear :color-buffer-bit :depth-buffer-bit) (gl:use-program program) (gl:uniformfv (gl:get-uniform-location program "color") *rgb*) (gl:enable-vertex-attrib-array 0) (gl:bind-buffer :array-buffer vertex-buf) (gl:vertex-attrib-pointer 0 3 :float nil 0 (cffi:null-pointer)) (gl:bind-buffer :element-array-buffer index-buf) (gl:draw-elements :triangles (gl:make-null-gl-array :unsigned-short) :count 3) (gl:disable-vertex-attrib-array 0) (gl:use-program 0) (sdl2:gl-swap-window *window*)) (defun main () (sdl2:with-init (:everything) (sdl2:gl-set-attr :context-major-version 3) (sdl2:gl-set-attr :context-minor-version 3) (sdl2:with-window (win :flags '(:opengl :shown)) (setf *window* win) (sdl2:with-gl-context (gl-context win) (sdl2:gl-make-current win gl-context) (gl:enable :cull-face) (gl:enable :depth-test) (gl:logic-op :invert) (gl:clear-color 0.0 0.0 0.0 1.0) (let ((vao (gl:gen-vertex-array)) (vertex-buf (make-buffer #(-0.5 -0.5 0.0 +0.5 -0.5 0.0 +0.0 0.5 0.0))) (index-buf (make-buffer #(0 1 2) :element-array-buffer)) (triangle-prg (load-program "triangle"))) (gl:bind-vertex-array vao) (sdl2:with-event-loop (:method :poll) (:idle () (render-swap vertex-buf index-buf (slot-value triangle-prg 'id))) (:quit () t)))))))
3,305
Common Lisp
.lisp
79
35.063291
92
0.622236
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
2287fcf648aa718d19c584d4b5446b7d2a0377d1515bedc2cb2eedb80777d2e9
32,317
[ -1 ]
32,318
xet.asd
aaron-lebo_lisp-engine/xet.asd
(asdf:defsystem #:xet :description "Describe xet here" :author "Your Name <[email protected]>" :license "Specify license here" :depends-on (#:cl-opengl #:pngload #:sdl2) :serial t :components ((:file "package") (:file "xet")))
288
Common Lisp
.asd
10
22.1
45
0.582734
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
97f3bf9fc10b2946340da824537a4836db75622522f2f3d15e61af7e12e8ebbe
32,318
[ -1 ]
32,322
triangle_vertex.glsl
aaron-lebo_lisp-engine/shaders/triangle_vertex.glsl
#version 330 core layout(location = 0) in vec3 xyz; void main() { gl_Position.xyz = xyz; gl_Position.w = 1.0; }
121
Common Lisp
.l
6
17.666667
33
0.657895
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
2cf07f5c72590404f755e20681ab979c7d31f38e9728df826849cabc8245a58b
32,322
[ -1 ]
32,323
block_vertex.glsl
aaron-lebo_lisp-engine/shaders/block_vertex.glsl
#version 120 uniform mat4 matrix; uniform vec3 camera; uniform float fog_distance; uniform int ortho; attribute vec4 position; attribute vec3 normal; attribute vec4 uv; varying vec2 fragment_uv; varying float fragment_ao; varying float fragment_light; varying float fog_factor; varying float fog_height; varying float diffuse; const float pi = 3.14159265; const vec3 light_direction = normalize(vec3(-1.0, 1.0, -1.0)); void main() { gl_Position = matrix * position; fragment_uv = uv.xy; fragment_ao = 0.3 + (1.0 - uv.z) * 0.7; fragment_light = uv.w; diffuse = max(0.0, dot(normal, light_direction)); if (bool(ortho)) { fog_factor = 0.0; fog_height = 0.0; } else { float camera_distance = distance(camera, vec3(position)); fog_factor = pow(clamp(camera_distance / fog_distance, 0.0, 1.0), 4.0); float dy = position.y - camera.y; float dx = distance(position.xz, camera.xz); fog_height = (atan(dy, dx) + pi / 2) / pi; } }
1,017
Common Lisp
.l
34
26.058824
79
0.667689
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
38198e405b88520279d909494ab1d9eda373240580f0ac93b9ade1d60ccd7a0d
32,323
[ -1 ]
32,324
block_fragment.glsl
aaron-lebo_lisp-engine/shaders/block_fragment.glsl
#version 120 uniform sampler2D sampler; uniform sampler2D sky_sampler; uniform float timer; uniform float daylight; uniform int ortho; varying vec2 fragment_uv; varying float fragment_ao; varying float fragment_light; varying float fog_factor; varying float fog_height; varying float diffuse; const float pi = 3.14159265; void main() { vec3 color = vec3(texture2D(sampler, fragment_uv)); if (color == vec3(1.0, 0.0, 1.0)) { discard; } bool cloud = color == vec3(1.0, 1.0, 1.0); if (cloud && bool(ortho)) { discard; } float df = cloud ? 1.0 - diffuse * 0.2 : diffuse; float ao = cloud ? 1.0 - (1.0 - fragment_ao) * 0.2 : fragment_ao; ao = min(1.0, ao + fragment_light); df = min(1.0, df + fragment_light); float value = min(1.0, daylight + fragment_light); vec3 light_color = vec3(value * 0.3 + 0.2); vec3 ambient = vec3(value * 0.3 + 0.2); vec3 light = ambient + light_color * df; color = clamp(color * light * ao, vec3(0.0), vec3(1.0)); vec3 sky_color = vec3(texture2D(sky_sampler, vec2(timer, fog_height))); color = mix(color, sky_color, fog_factor); gl_FragColor = vec4(color, 1.0); }
1,180
Common Lisp
.l
35
30.085714
75
0.652936
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
417e72a90df35ac1f19d4f6304b9b40a6a4052c7600b1dbe3c66caa32e811dcc
32,324
[ -1 ]
32,325
sky_vertex.glsl
aaron-lebo_lisp-engine/shaders/sky_vertex.glsl
#version 120 uniform mat4 matrix; attribute vec4 position; attribute vec3 normal; attribute vec2 uv; varying vec2 fragment_uv; void main() { gl_Position = matrix * position; fragment_uv = uv; }
206
Common Lisp
.l
10
18.4
36
0.765625
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
a98ca20f8f4158c058f70c11af323295b34265b30735b6d6dbe2e0e0e1046dcc
32,325
[ -1 ]
32,326
line_fragment.glsl
aaron-lebo_lisp-engine/shaders/line_fragment.glsl
#version 120 void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); }
75
Common Lisp
.l
4
16.5
44
0.585714
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
b4e57136aa2784e31665907f2e948053a276284d6c503ce382795a91db7e7e42
32,326
[ -1 ]
32,327
line_vertex.glsl
aaron-lebo_lisp-engine/shaders/line_vertex.glsl
#version 120 uniform mat4 matrix; attribute vec4 position; void main() { gl_Position = matrix * position; }
115
Common Lisp
.l
6
17
36
0.754717
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
63717dbd4e13bc8c827e094fa9f1060fbfaf59a8a2b57cd2854fe17e76447fe1
32,327
[ -1 ]
32,328
text_vertex.glsl
aaron-lebo_lisp-engine/shaders/text_vertex.glsl
#version 120 uniform mat4 matrix; attribute vec4 position; attribute vec2 uv; varying vec2 fragment_uv; void main() { gl_Position = matrix * position; fragment_uv = uv; }
183
Common Lisp
.l
9
18
36
0.752941
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
9a053a18edab6e050d835a2d44f8c74d2bdbfa17260f5eedb8b2ebfab9db33e4
32,328
[ -1 ]
32,329
triangle_fragment.glsl
aaron-lebo_lisp-engine/shaders/triangle_fragment.glsl
#version 330 core uniform vec3 color; out vec3 colr; void main() { colr = color; }
89
Common Lisp
.l
6
12.833333
19
0.716049
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
28a25029059550b6efa2777e84ee3612ba0239e82b344e69ab4852ee7874cd42
32,329
[ -1 ]
32,330
text_fragment.glsl
aaron-lebo_lisp-engine/shaders/text_fragment.glsl
#version 120 uniform sampler2D sampler; uniform bool is_sign; varying vec2 fragment_uv; void main() { vec4 color = texture2D(sampler, fragment_uv); if (is_sign) { if (color == vec4(1.0)) { discard; } } else { color.a = max(color.a, 0.4); } gl_FragColor = color; }
327
Common Lisp
.l
16
15.5
49
0.581169
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
7ab942990d5b5efc5f5ef70ef7181ceee5e97c6410757a955ecf399f23fde62a
32,330
[ -1 ]
32,331
sky_fragment.glsl
aaron-lebo_lisp-engine/shaders/sky_fragment.glsl
#version 120 uniform sampler2D sampler; uniform float timer; varying vec2 fragment_uv; void main() { vec2 uv = vec2(timer, fragment_uv.t); gl_FragColor = texture2D(sampler, uv); }
191
Common Lisp
.l
8
21.5
42
0.744444
aaron-lebo/lisp-engine
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
47d6239efa9ea6940de593e64467c75c5a26ec2f6dc281e0286851f30950ba63
32,331
[ -1 ]
32,346
svg.lisp
jfjhh_curvy-wurvy/src/svg.lisp
;;;; ;;;; SVG output language. ;;;; Alex Striff. ;;;; (in-package #:parametric) (defparameter *debug-stream* *standard-output*) (defparameter *out-width* 1920) (defparameter *out-height* 1080) (defparameter *svg-indent* 4) (defparameter *svg-depth* *svg-indent*) (defparameter *svg-spaces* "") (defparameter *text-start-x* 64) (defparameter *text-start-y* 64) (defparameter *text-x* *text-start-x*) (defparameter *text-y* *text-start-y*) (defparameter *text-size* 16) (defmacro svg-header (&body body) `(progn (format t "<?xml version='1.0' encoding='UTF-8' ?> <svg version='1.1' viewbox='0 0 ~d ~d' xmlns='http://www.w3.org/2000/svg'>~%" *out-width* *out-height*) (setf *svg-indent* 4) (setf *svg-depth* *svg-indent*) (setf *svg-spaces* (make-string *svg-depth* :initial-element #\Space)) ,@body (format t "</svg>~%"))) (defmacro svg-file (filename &body body) `(with-open-file (*standard-output* ,filename :direction :output :if-exists :supersede) (svg-header ,@body))) (defun svg-attributes (attributes &optional (prev "")) (if (null attributes) prev (svg-attributes (cddr attributes) (concatenate 'string prev (format nil " ~:[~a~;~(~a~)~]='~f'" (symbolp (car attributes)) (car attributes) (cadr attributes)))))) (defmacro svg-tag (tag attributes &body body) (make-string 3 :initial-element #\*) (if (null body) `(format t "~a<~a~a />~%" *svg-spaces* ,tag (svg-attributes ,attributes)) `(progn (let ((istext (equal (format nil "~(~a~)" ,tag) "text"))) (format t "~a<~a~a>~:[~%~;~]" *svg-spaces* ,tag (svg-attributes ,attributes) istext) (incf *svg-depth* *svg-indent*) (setf *svg-spaces* (make-string *svg-depth* :initial-element #\Space)) ,@body (decf *svg-depth* *svg-indent*) (setf *svg-spaces* (make-string *svg-depth* :initial-element #\Space)) (format t "~:[~a~;~*~]</~a>~%" istext *svg-spaces* ,tag))))) (defun svg-comment (text) (format t "<!--~%~a~&-->~%" text)) (defun svg-text (text &rest attributes) (svg-tag "text" (append (list 'x *text-x* 'y *text-y*) attributes) (format t "~a" text)) (incf *text-y* (* 2 *text-size*))) (defgeneric svg-curve-text (curve) (:documentation "Outputs SVG tags that give mostly textual information about the given curve.")) (defun svg-line (x1 y1 x2 y2) (svg-tag "line" (list 'x1 x1 'y1 y1 'x2 x2 'y2 y2))) (defmacro svg-test-curve (&body body) `(svg-file "./test.svg" (svg-tag "defs" nil (svg-tag "linearGradient" (list "id" "paramgrad" ;;"gradientUnits" "userSpaceOnUse" ) ;; Rainbow gradient. (svg-tag "stop" (list 'offset "00%" 'stop-color "#0000ff" 'stop-opacity 1)) (svg-tag "stop" (list 'offset "25%" 'stop-color "#00ffff" 'stop-opacity 1)) (svg-tag "stop" (list 'offset "50%" 'stop-color "#00ff00" 'stop-opacity 1)) (svg-tag "stop" (list 'offset "75%" 'stop-color "#ffff00" 'stop-opacity 1)) (svg-tag "stop" (list 'offset "100%" 'stop-color "#ff0000" 'stop-opacity 1)) ;;(svg-tag "stop" (list 'offset "0%" 'stop-color "#f0f" 'stop-opacity 1)) ;;(svg-tag "stop" (list 'offset "100%" 'stop-color "#0ff" 'stop-opacity 1)) )) (let ((dur "1s")) (svg-tag "linearGradient" (list "id" "paramgrad_anim") ;; Rainbow gradient. (svg-tag "stop" (list 'offset "00%" 'stop-color "#0000ff" 'stop-opacity 1) (svg-tag "animate" (list "attributeName" "stop-color" "values" "#00f; #f00; #00f" "dur" dur "repeatCount" "indefinite")) ) (svg-tag "stop" (list 'offset "25%" 'stop-color "#00ffff" 'stop-opacity 1) (svg-tag "animate" (list "attributeName" "stop-color" "values" "#0ff; #ff0; #0ff" "dur" dur "repeatCount" "indefinite")) ) (svg-tag "stop" (list 'offset "50%" 'stop-color "#00ff00" 'stop-opacity 1) (svg-tag "animate" (list "attributeName" "stop-color" "values" "#0f0; #f0f; #0f0" "dur" dur "repeatCount" "indefinite")) ) (svg-tag "stop" (list 'offset "75%" 'stop-color "#ffff00" 'stop-opacity 1) (svg-tag "animate" (list "attributeName" "stop-color" "values" "#ff0; #0ff; #ff0" "dur" dur "repeatCount" "indefinite")) ) (svg-tag "stop" (list 'offset "100%" 'stop-color "#ff0000" 'stop-opacity 1) (svg-tag "animate" (list "attributeName" "stop-color" "values" "#f00; #00f; #f00" "dur" dur "repeatCount" "indefinite")) ))) ;;(svg-tag "stop" (list 'offset "0%" 'stop-color "#f0f" 'stop-opacity 1)) ;;(svg-tag "stop" (list 'offset "100%" 'stop-color "#0ff" 'stop-opacity 1)) (svg-tag "rect" (list 'x 0 'y 0 'width *out-width* 'height *out-height* 'fill "#000" 'stroke "#f0f" 'stroke-width 2)) ,@body))
4,795
Common Lisp
.lisp
119
35.487395
103
0.6103
jfjhh/curvy-wurvy
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
654d58e1272ce1f3ab1d83831b93ef9a57953f3895c9e2f89565490b111df6e5
32,346
[ -1 ]
32,347
packages.lisp
jfjhh_curvy-wurvy/src/packages.lisp
;;;; ;;;; Parametric package definitions. ;;;; Alex Striff. ;;;; (defpackage #:parametric (:use #:cl #:asdf #:alexandria))
127
Common Lisp
.lisp
6
19.5
36
0.647059
jfjhh/curvy-wurvy
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
b30f276e04c332ac0c2e8107f759f7c610b8c8a0da62debc25a238179edd01a0
32,347
[ -1 ]
32,348
parametric.asd
jfjhh_curvy-wurvy/parametric.asd
;;;; ;;;; The Parametric system definition. ;;;; Alex Striff. ;;;; (defsystem "parametric" :description "Parametric: A parametric curve exploration tool." :version "0.0.1" :author "Alex Striff" :licence "MIT License" :depends-on ("alexandria") :components ((:file "src/packages") (:file "src/param" :depends-on ("src/packages")) (:file "src/svg" :depends-on ("src/packages"))))
422
Common Lisp
.asd
13
28.076923
65
0.636364
jfjhh/curvy-wurvy
0
0
0
GPL-3.0
9/19/2024, 11:42:39 AM (Europe/Amsterdam)
67a9cbfc2b9ae8f9f50c4f0f3300d85d3ea298d31254c846232d9259414f3b8c
32,348
[ -1 ]
32,366
1.hola-mundo.lisp
MoiRouhs_lisp/1.hola-mundo.lisp
(format t "Hola mundo desde format") ; Permite imprimir variables sin tener que concatenarlas (print "Hola mundo desde print") ; Imprime en consola sin salto de linea (write "Hola mundo desde write") ; Imprimer cadenas de texto entre comillas dobles en consola sin salto de linea (write-line "Hola mundo") ; Imprime cadenas de texto en consola con salto de linea.
363
Common Lisp
.lisp
4
90
112
0.783333
MoiRouhs/lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
0679ba94fa99bdad6193acc2f26f5631a913d47480ae1812121efda1beec87d7
32,366
[ -1 ]
32,367
3.decisiones.lisp
MoiRouhs_lisp/3.decisiones.lisp
(defun comparar (a b) (if (> a b) (write-line (concatenate 'string "A es mayor " (write-to-string a))) (write-line (concatenate 'string "B es mayor " (write-to-string b))) ) ) (comparar 12 26) (defun comvarios (a b) (cond ((= a b) (write "Son iguales")) ((> a b) (write (concatenate 'string "A es mayor " (write-to-string a)))) ((< a b) (write (concatenate 'string "B es mayor " (write-to-string b)))) ) ) (comvarios 122 13) (defun cuando (a) (when (= 0 (mod a 2)) (write "es divisible en dos") ) ) (cuando 233)
551
Common Lisp
.lisp
21
23.380952
77
0.608696
MoiRouhs/lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
21b336b8151e84f98174c4406ae832617c459f46d3d8f1f42787fdfed8838ec2
32,367
[ -1 ]
32,368
4.ciclos.lisp
MoiRouhs_lisp/4.ciclos.lisp
(setq a 0) ; Se inicializa una variable en cero. (loop ; Se inicializa el loop (setq a (incf a 1)) ; Incrementea (incf) a en uno cada vez que se repite el ciclo. (write a) ; Se muestra en consola el valor de la variable a (terpri) ; Se haceun salto de linea (when (= a 7) (return a)) ; Si a es igual a 7 se devuelve a y se termina el ciclo. Este ciclo cuenta de 1 a 7. ) (loop for a from 10 to 20 ; Se inicia un ciclo que toma desde 10 a 20 do (print a) ; imprime el contenido en consola desde el 10 al 20. ) (do ((x 0 (incf x 1)) ; Primera exprecion a evaluar con su respectivo actualizacion, en este caso uincremente (y 10 (decf y 1))) ; Segunda exprecion a evaluar con su respectivo actualizacion, en este caso decrese ((= x y)) ; Expresion a evaluar si es falsa sigue haciendo ciclos hasta evaluar verdadera la exprecion (format t "~% x = ~d y = ~d" x y) ; imprime en temrnal siempre y cuanto la exprecon evaluada sea falsa. ) (dotimes (a 5) ; Repite 5 veces el ciclo empezando en cero. (print a) (prin1 (* a a)) ; a toma un valor de 0 a 4 dependiendo el ciclo en el que se encuentro y realiza la operacion, hasta repetir el ciclo las veces dichas en la primera linea de dotimes ) (dolist (d '(1 2 3 4 5)) ; Itinera sobre los valores de una lista (format t "~% Valor d: ~d, d al cuadrado: ~d" d (* d d)) ; realiza los procesos hasta terminar con la lista. )
1,399
Common Lisp
.lisp
21
63.952381
196
0.701091
MoiRouhs/lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
758d22d75417a453d391f4369dfc97a37de2c76c411a0394548ac9ac24f24aaa
32,368
[ -1 ]
32,369
5.funciones.lisp
MoiRouhs_lisp/5.funciones.lisp
; FUNCIONES (defun saludar (nombre) ; defun define la funcion, seguido del nombre y entre parentesis los parametros. (concatenate 'String "Hola " nombre) ; Este es el cuerpo de la funcion donde ejecuta el codigo, las funcones en lisp devuelven el ultimo valor definido. ) (write-line (saludar "Andres")) ;FUNCIONES CON VALORES OPCIONALES (defun valopcional (&optional h) ; Despues de &optional van los argumentos opcionales. (concatenate 'String "el argumento h es: " h) ; concatenate nos permite concatenar valores en este caso texto definido con 'String ) (write-line (valopcional)) (write-line (valopcional "esto")) ;FUNCIONES CON VALORES ADICIONALES (defun valadicional (a d &rest otros) ; Esta funcion pide dos argumentos como minimo dos agumentos a y d, el resto de argumentos se guardan en otros si existen estos se lleva cabo gracias a &rest (list a d otros) ) (print (valadicional "carlos" "juan")) ; Los dos argumentos obligatorios (print (valadicional "carlos" "juan" "Felipe" "Luis")) ; Argumentos obligatorios y dos argumentos de mas. ;FUNCIONES CON PALABRAS CLAVES (defun valclave (&key a b) ; La opcion &key nos permite especificar el valor para cada argumento al llamarlo. (concatenate 'String "hola " a " y " b) ) (print (valclave :b "Juan" :a "Maria")) ; cuando se invoca la funcion hay que especificar el argumento con : y el nombre del argumento, mas su valor. ;FUNCIONES CON RETORNO PREDETERMINADO (defun retorno (h) (print "Dentro de la funcion retorno y antes de return-from") (return-from retorno h) ; la palabra return-from nos permite devolver el valor que queramos explicitamente, no olvide que debe estar seguido del nombre de la funcion y lo que se quiere devolver, es importante saber que hasta este punto se ejecuta la funcion de ahi en adelante no se ejecuta. (print "Dentro de la funcion retorno y despues de return-from") ) (print (retorno "Hola"))
1,919
Common Lisp
.lisp
30
61.833333
295
0.765708
MoiRouhs/lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
a30a6c81cc6e173e8c933f543b10aa8bdd042935b15843f79ad0d0032fb373d8
32,369
[ -1 ]
32,370
2.variables.lisp
MoiRouhs_lisp/2.variables.lisp
(defvar x "defvar") ; Variable global (setq y "setq") ; Especifica el tipo de variable (write-line x) (write-line y) (let ((g "let") (e "let2")) ; Variables locales. (format t "esta es el valor de g: ~g y e: ~e" g e) ) (defconstant PI 3.141592) ; Variables constantes que nunca cambian. (print PI)
301
Common Lisp
.lisp
9
32.111111
67
0.687285
MoiRouhs/lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
e6f2b1c75342010696c3a36583912c33490d185b6942efe8548e4da1aab6a651
32,370
[ -1 ]
32,392
list.lisp
spartakos87_Lists_in_Common_Lisp/list.lisp
; Sum ,multiple,count list (defun sum (lst ) (eval (cons '+ lst)) ) (defun multi (lst) (eval (cons '* lst)) ) (defun count-lst (lst &optional (s 0)) (if (cdr lst) (count-lst (cdr lst) (+ s 1)) (+ s 1) ) ) (defun add-elem (lst &optional (a 1) ( temp '())) (if (cdr lst) (add-elem (cdr lst) a (cons (+ a (car lst)) temp)) (reverse (cons (+ a (car lst)) temp)) ) ) (defun multi-elem (lst &optional (a 1) ( temp '())) (if (cdr lst) (multi-elem (cdr lst) a (cons (* a (car lst)) temp)) (reverse (cons (* a (car lst)) temp)) ) ) (defun return-elem (lst idx &optional (c 0)) ;return element of list when we give a specific index (if (and (= c 0) (> idx (count-lst lst))) (write-line "Out of range") (progn (if (< c idx) (return-elem (cdr lst) idx (+ c 1)) (car lst) ) ))) (defun return-unq (lst &optional (c 0) (u '())) ;return unique elements of list (if (< c (count-lst lst)) (progn (if (find (return-elem lst c) u) (return-unq lst (+ c 1) u) (return-unq lst (+ c 1) (cons (return-elem lst c) u)) ) ) (reverse u) ) ) (defun return-indx-elem (lst n &optional (c 0) (idx_lst '())) ;return all indexs which appear a given element (if (< c (count-lst lst)) (progn (if (= (return-elem lst c) n) (return-indx-elem lst n (+ c 1) (cons c idx_lst)) (return-indx-elem lst n (+ c 1) idx_lst)) ) (reverse idx_lst))) (defun ce2 (lst unq-lst &optional (c 0) (hs '())) (if (< c (count-lst unq-lst)) (ce2 lst unq-lst (+ c 1) (acons (return-elem unq-lst c) (count-lst (return-indx-elem lst (return-elem unq-lst c))) hs)) (reverse hs) )) (defun count-elem (lst) ; return element and the number of them ;for example as input (1 2 2 3) => (1 . 1 2 . 2 3.1) (ce2 lst (return-unq lst)) ) (defun range ( e &optional (b 0) (s 1) (lst '())) (if (<= b e) (range e (+ b s) s (cons b lst)) (reverse lst))) (defun check-list-of-lists (lst) ;Check if lst is lst of lists (if (cdr lst) (progn (if (listp (car lst)) (check-list-of-lists (cdr lst)) nil)) (if (listp (car lst)) t nil))) (defun ml (a r) (if (cdr r) (ml (cons (car r) a) (cdr r)) (cons (car r) a))) (defun merge-lst (lst &optional (l '())) (if (check-list-of-lists lst) (progn (if (cdr lst) (merge-lst (cdr lst) (ml l (car lst))) (ml l (car lst)) )) "Not list of lists")) (defun euclidean-distance (lstA lstB &optional (l '())) (if (and (cdr lstA) (cdr lstB)) (euclidean-distance (cdr lstA) (cdr lstB) (cons (- (car lstB) (car lstA)) l)) (sqrt (eval (cons '+ (reverse (cons (- (car lstB) (car lstA)) l))))) )) ;praxeis metaxy liston px ((1 2 3) (1 2 3)) =+=> (2 4 6) (defun lists-add (lsts &optional (l '())) (if (cdr (car lsts)) (lists-add (mapcar #'cdr lsts) (cons (eval (cons '+ (mapcar #'car lsts))) l)) (reverse (cons (eval (cons '+ (mapcar #'car lsts))) l)))) (defun lists-sub (lsts &optional (l '())) (if (cdr (car lsts)) (lists-sub (mapcar #'cdr lsts) (cons (eval (cons '- (mapcar #'car lsts))) l)) (reverse (cons (eval (cons '- (mapcar #'car lsts))) l)))) (defun lists-multi (lsts &optional (l '())) (if (cdr (car lsts)) (lists-multi (mapcar #'cdr lsts) (cons (eval (cons '* (mapcar #'car lsts))) l)) (reverse (cons (eval (cons '* (mapcar #'car lsts))) l))))
3,615
Common Lisp
.lisp
108
27.759259
87
0.542566
spartakos87/Lists_in_Common_Lisp
0
0
0
GPL-3.0
9/19/2024, 11:42:47 AM (Europe/Amsterdam)
8e497e96f8fc604ceb5a704e45c30346f3f1624fbb59333e622b9aa018935ad8
32,392
[ -1 ]
32,409
atomics.lisp
fch_LispTools/lib/tools/atomics/atomics.lisp
; Some tools to handle lists even more efficiently ; Takes predicate and returns list of items satisfying it (defun those (p) (lambda (x) (if (funcall p x) (list x)))) ; Enable currying of parameters, so ; f: A_1 x ... x A_n -> B ; becomes ; f': A_1 -> (A_2 -> (...(A_n -> B)...)) (defun curry-param (fn p2) (lambda (p1) (funcall fn p1 p2))) ; Enable function composition: ; f: A -> B, g: B -> C ; f o g : x |-> (f o g)(x) := f(g(x)) (defun compose-fun (f g) (lambda (x) (funcall f (funcall g x))))
544
Common Lisp
.lisp
17
28.823529
58
0.568138
fch/LispTools
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
0a53c9a9c8c531ddc32e0e51f43d6bbc4ad8b82e7c53a180c1d0c1e4edae24ed
32,409
[ -1 ]
32,410
physics_calculator.lisp
fch_LispTools/lib/tools/physics_calculator/physics_calculator.lisp
; Simple calculator for MKSA-units ; Since every physical quantity can be written as ; Q * m^a * kg^b * s^c * A^d ; with a real number Q and integers a to d, ; we can represent this concept as a list ; (Q a b c d). ; ------ BASIC ARITHMETIC ------ (defun *u (a b) (cons (* (car a) (car b)) (mapcar #'+ (cdr a) (cdr b)))) (defun /u (a b) (cons (/ (car a) (car b)) (mapcar #'- (cdr a) (cdr b)))) (defun +u (a b) (if (equal (cdr a) (cdr b)) (cons (+ (car a) (car b)) (cdr a)) (error "Incompatible arguments at addition"))) (defun -u (a b) (if (equal (cdr a) (cdr b)) (cons (- (car a) (car b)) (cdr a)) (error "Incompatible arguments at substraction"))) ; ------ HELPER FUNCTIONS ------ ; M K S A ; ----------- (defun 1* (x) (list x 0 0 0 0)) (defun m (x) (list x 1 0 0 0)) (defun kg (x) (list x 0 1 0 0)) (defun s (x) (list x 0 0 1 0)) (defun a (x) (list x 0 0 0 1)) (defun m/s (x) (list x 1 0 -1 0)) (defun n (x) (list x 1 1 -2 0)) (defun v (x) (list x 2 1 -3 -1)) (defun j (x) (*u (n x) (m 1))) (defun ohm (x) (/u (v x) (a 1))) (defun km (x) (list (* 1000 x) 1 0 0 0)) (defun inch (x) (list (* x 0.0254) 1 0 0 0)) (defun minute (x) (list (* x 60) 0 0 1 0)) (defun h (x) (list (* x 60 60) 0 0 1 0)) ; ------ FORMAT OUTPUT ------ (defparameter *units* (list (cons 'm (cdr (m 1))) (cons 'kg (cdr (kg 1))) (cons 's (cdr (s 1))) (cons 'a (cdr (a 1))) (cons 'j (cdr (j 1))) (cons 'm/s (cdr (m/s 1))) (cons 'v (cdr (v 1))) (cons 'ohm (cdr (ohm 1))) (cons 'Nm (cdr (*u (n 1) (m 1)))) )) (defun find-unit (x) (car (find (cdr x) *units* :key #'cdr :test #'equal))) (defun u (x) (let ((unit (find-unit x))) (if unit (list unit (car x)) (cons 'list x))))
2,144
Common Lisp
.lisp
58
33.034483
57
0.425243
fch/LispTools
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
6d1a285edce3ffe1e39ebb3a37ca88d015fefd972f3e83eab9cbd3c0960292d2
32,410
[ -1 ]
32,428
10_Primos.lisp
vitormmatos_lispHiragiEx/10_Primos.lisp
(defun divs (n c d) (if (> c n) d (divs n (+ c 1) (if (= (mod n c) 0) (+ d 1) d) ) ) ) (defun primo (n) (if (= (divs n 1 0) 2) T NIL ) ) (defun primos (n &optional (c 2)) (if (< n 1) nil (if (primo c) (progn (print c) (primos (- n 1) (+ c 1) ) ) (primos n (+ c 1))) ) ) (print "Digite um número N para ver quais os N primeros números primos: ") (setq num (read)) (primos num)
455
Common Lisp
.lisp
28
12.428571
74
0.481043
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
49b04f227edc9ad5e484c02a35772f819a8c93bb15d09ab152f2b52b9dcde224
32,428
[ -1 ]
32,429
5_Contar.lisp
vitormmatos_lispHiragiEx/5_Contar.lisp
(defun contar (fim) (if (> fim 3) (contar (- fim 3)) nil ) (print fim) ) (print "Esse programa conta de 3 em 3 até o número especificado") (print "Digite o número: ") (defvar num (read)) (contar num)
218
Common Lisp
.lisp
11
17.181818
65
0.64532
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
7bb630aa2f5689023fa7f26aa8b5462aca4fd3075665f0c693489f186632237d
32,429
[ -1 ]
32,430
6_ContarEmPassos.lisp
vitormmatos_lispHiragiEx/6_ContarEmPassos.lisp
(defun contar (inicio fim soma) (print inicio) (if (<= (+ inicio soma) fim) (contar (+ inicio soma) fim soma) nil ) ) (print "Digite o numero inicial: ") (defvar inicio (read)) (print "Digite o número de incremento: ") (defvar passo (read)) (print "Digite o numero final: ") (defvar fim (read)) (contar inicio fim passo)
337
Common Lisp
.lisp
14
22
42
0.680124
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
92a5745531206115a0c1852e8d583ebfe1480b2763f1b6d34462c831e01f945e
32,430
[ -1 ]
32,431
3_SomaMult.lisp
vitormmatos_lispHiragiEx/3_SomaMult.lisp
(defun somaMult (num1 num2 num3) (format t "~%A soma dos números ~d e ~d" num2 num3) (if(/= num1 (+ num2 num3)) (format t " não") ) (format t " é igual a ~d" num1) ) (print "Digite o primeiro número: ") (setq num1 (read)) (print "Digite o segundo número: ") (setq num2 (read)) (print "Digite o terceiro número: ") (setq num3 (read)) (somaMult num1 num2 num3)
378
Common Lisp
.lisp
14
24.642857
53
0.655462
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
8008b9ade9f549cb7edbf99766ceffb10449a0f5c1c370c76ea29cf6765a8e27
32,431
[ -1 ]
32,432
9_Compara.lisp
vitormmatos_lispHiragiEx/9_Compara.lisp
(defun compara (a b) (if(> a b) (format t "~%~d é maior que ~d" a b) (if(< a b) (format t "~%~d é menor que ~d" a b) (format t "~%~d é igual a ~d" a b) ) ) ) (print "Digite o primeiro valor: ") (defvar num1 (read)) (print "Digite o segundo valor: ") (defvar num2 (read)) (compara num1 num2)
325
Common Lisp
.lisp
14
19.785714
42
0.563934
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
e3b0f06c7769f0998d7f2baad43246dca570280a3bf37afd773defb184b21718
32,432
[ -1 ]
32,433
7_Fatorial.lisp
vitormmatos_lispHiragiEx/7_Fatorial.lisp
(defun fatorial (n &optional (intermediario 1)) (if (= n 1) (return-from fatorial intermediario)) (fatorial (1- n) (* n intermediario)) ) (print "Digite um número para ver seu fatorial:") (setq num (read)) (format t "~%O fatorial de ~d é ~d" num (fatorial num))
274
Common Lisp
.lisp
8
31.75
55
0.679389
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
498bd8182843ec7144fbe46921393b8fe45dbc7880a5256192d377eba95898e9
32,433
[ -1 ]
32,434
1_Dias.lisp
vitormmatos_lispHiragiEx/1_Dias.lisp
(defun dias (anos) (format t "~%~d anos equivalem a ~d dias" anos (* anos 365)) ) (print "Este programa calcula a quantidade de dias.") (print "Digite a quantidade de anos: ") (setq anos (read)) (dias anos)
210
Common Lisp
.lisp
7
28.571429
62
0.693069
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
f2b4b43adc26ca5da0209124f227aaa010da59d1e4d48d9671e3dd0098cc16ca
32,434
[ -1 ]
32,435
4_Contrario.lisp
vitormmatos_lispHiragiEx/4_Contrario.lisp
(defun contrario (palavra) (format t (subseq palavra (- (length palavra) 1) (length palavra))) (if (> (length palavra) 1) (contrario (subseq palavra 0 (- (length palavra) 1))) ) ) (print "Digite uma palavra: ") (defvar palavra (string (read))) (format t "~%O contrario de ~s é " palavra) (contrario palavra)
320
Common Lisp
.lisp
10
29.9
69
0.676375
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
4826b9713c1f93a652bfe0509ab510a5a6edcaede7d2c1ac77d329f8824cb8b5
32,435
[ -1 ]
32,436
8_Fibonacci.lisp
vitormmatos_lispHiragiEx/8_Fibonacci.lisp
(defun fibonacci(n) (cond ((eq n 1) 0) ((eq n 2) 1) ((+ (fibonacci (- n 1)) (fibonacci (- n 2)))) ) ) (print "Este programa calcula o valor de fibonacci de um termo N") (print "Digite N: ") (setq num (read)) (format t "~%O termo ~dº de fibonacci é ~d" num (fibonacci num))
296
Common Lisp
.lisp
12
21.75
66
0.597865
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
e4fa78f8cfe77f7f672da66bc339b02ff76c245e2ddd80885751bd65dc7f7f39
32,436
[ -1 ]
32,437
2_Salario.lisp
vitormmatos_lispHiragiEx/2_Salario.lisp
(defun converteSalario (salario) (format t "~%R$~,2f equivale a ~,2f dólares" salario (/ salario 3.25)) (format t "~%R$~,2f equivale a ~,2f salários mínimos" salario (/ salario 937)) ) (print "Digite um salário: ") (setq salario (read)) (converteSalario salario)
272
Common Lisp
.lisp
7
36.571429
80
0.7
vitormmatos/lispHiragiEx
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
9cb7413c022d11cf9e34c3188c3bff33fda54aa96ac1ad583b478c0572595072
32,437
[ -1 ]
32,463
app.lisp
miscoined_miscoined/app.lisp
(ql:quickload :miscoined) (defpackage miscoined.app (:use :cl) (:import-from :lack.builder :builder) (:import-from :ppcre :scan) (:import-from :miscoined.web :*web*) (:import-from :miscoined.config :config :productionp :*static-directory*)) (in-package :miscoined.app) (builder (:static :path (lambda (path) (when (ppcre:scan "^(?:/docs/|/fonts/|/images/|/css/|/js/|/robot\\.txt$|/favicon\\.ico$)" path) path)) :root *static-directory*) (unless (productionp) :accesslog) (when (getf (config) :error-log) `(:backtrace :output ,(getf (config) :error-log))) :session (unless (productionp) (lambda (app) (lambda (env) (funcall app env)))) *web*)
842
Common Lisp
.lisp
33
18.454545
88
0.546468
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
84689b75b56d865840987e2a5a81392a78de7f0e65e262df1801b7666d3c4d64
32,463
[ -1 ]
32,464
run.lisp
miscoined_miscoined/run.lisp
;;;; Simple script to load the package and run server (in-package :miscoined) (ql:quickload :miscoined) (miscoined:start)
124
Common Lisp
.lisp
4
29.5
53
0.779661
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
0609c9d0f78630929fd51e95740497f6c61563efc329a2fde7cc4f37093ebb30
32,464
[ -1 ]
32,465
main.lisp
miscoined_miscoined/src/main.lisp
(in-package :cl-user) (defpackage miscoined (:use :cl) (:import-from :miscoined.config :config) (:import-from :clack :clackup) (:export :start :stop)) (in-package :miscoined) (defvar *appfile-path* (asdf:system-relative-pathname :miscoined #P"app.lisp")) (defvar *handler* nil) (defun start (&rest args &key server port debug &allow-other-keys) (declare (ignore server port debug)) (when *handler* (restart-case (error "Server is already running.") (restart-server () :report "Restart the server" (stop)))) (setf *handler* (apply #'clackup *appfile-path* args))) (defun stop () (prog1 (clack:stop *handler*) (setf *handler* nil)))
740
Common Lisp
.lisp
26
23.269231
66
0.632394
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
bc82cfa17ce15142e5d35c6b8025d7f983e6aa093c9663de89dfc83026b26e6d
32,465
[ -1 ]
32,466
view.lisp
miscoined_miscoined/src/view.lisp
(in-package :cl-user) (defpackage miscoined.view (:use :cl) (:import-from :miscoined.config :*template-directory*) (:import-from :caveman2 :*response* :response-headers) (:import-from :djula :add-template-directory :compile-template* :render-template* :*djula-execute-package*) (:export :render)) (in-package :miscoined.view) (djula:add-template-directory *template-directory*) (defparameter *template-registry* (make-hash-table :test 'equal)) (defun render (template-path &optional env) (let ((template (gethash template-path *template-registry*))) (unless template (setf template (djula:compile-template* (princ-to-string template-path))) (setf (gethash template-path *template-registry*) template)) (apply #'djula:render-template* template nil env))) ;; ;; Execute package definition (defpackage miscoined.djula (:use :cl) (:import-from :miscoined.config :config :appenv :developmentp :productionp) (:import-from :caveman2 :url-for)) (setf djula:*djula-execute-package* (find-package :miscoined.djula))
1,264
Common Lisp
.lisp
37
26.189189
79
0.62326
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
f3f616e7b943b9e6d2143a868e0db8efb6356b4fdca3cc8f95f421b2d80fc3b5
32,466
[ -1 ]
32,467
config.lisp
miscoined_miscoined/src/config.lisp
(in-package :cl-user) (defpackage miscoined.config (:use :cl) (:import-from :envy :config-env-var :defconfig) (:export :config :*application-root* :*static-directory* :*template-directory* :appenv :developmentp :productionp)) (in-package :miscoined.config) (setf (config-env-var) "APP_ENV") (defparameter *application-root* (asdf:system-source-directory :miscoined)) (defparameter *static-directory* (merge-pathnames #P"static/" *application-root*)) (defparameter *template-directory* (merge-pathnames #P"templates/" *application-root*)) (defconfig :common `(:databases ((:maindb :sqlite3 :database-name ":memory:")))) (defconfig |development| '()) (defconfig |production| '()) (defconfig |test| '()) (defun config (&optional key) (envy:config #.(package-name *package*) key)) (defun appenv () (uiop:getenv (config-env-var #.(package-name *package*)))) (defun developmentp () (string= (appenv) "development")) (defun productionp () (string= (appenv) "production"))
1,099
Common Lisp
.lisp
34
27.5
87
0.658768
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
40fe10724e6100e0bb005d5457973cf3193f26136b80a127582654b319f61e09
32,467
[ -1 ]
32,468
web.lisp
miscoined_miscoined/src/web.lisp
(in-package :cl-user) (defpackage miscoined.web (:use :cl :caveman2 :miscoined.config :miscoined.view) (:export :*web*)) (in-package :miscoined.web) ;; for @route annotation (syntax:use-syntax :annot) ;; ;; Application (defclass <web> (<app>) ()) (defvar *web* (make-instance '<web>)) (clear-routing-rules *web*) ;; ;; Routing rules (defroute "/" () (render "index.html")) ;; ;; Error pages (defmethod on-exception ((app <web>) (code (eql 404))) (declare (ignore app)) (merge-pathnames #P"_errors/404.html" *template-directory*))
571
Common Lisp
.lisp
24
21.083333
62
0.661111
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
65faa6148b6431351eb5eb5d86376d52b2550db8d037e74cec43a5a1403d5211
32,468
[ -1 ]
32,469
miscoined.asd
miscoined_miscoined/miscoined.asd
(defsystem "miscoined" :version "0.1.0" :author "Kelly Stewart" :license "" :depends-on ("clack" "lack" "caveman2" "envy" "cl-ppcre" "uiop" ;; HTML Template "djula") :components ((:module "src" :components ((:file "main" :depends-on ("config" "view")) (:file "web" :depends-on ("view")) (:file "view" :depends-on ("config")) (:file "config")))) :description "" :in-order-to ((test-op (test-op "miscoined-test"))))
616
Common Lisp
.asd
20
19.7
61
0.444631
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
8064b1e59d95b69b640de053fac208103c266fabafd99af841ddf8eaf00e72b5
32,469
[ -1 ]
32,477
index.html
miscoined_miscoined/templates/index.html
{% extends "layouts/default.html" %} {% block title %}{% endblock %} {% block content %} <main class="landing"> <h1>Kelly Stewar<span class="swatches">t</span></h1> <nav> <a href="mailto:[email protected]"> <i class="fa fa-envelope" title="Email"></i> [email protected] </a> <a href="https://www.github.com/miscoined"> <i class="fa fa-github" title="Github"></i> @miscoined </a> <a href="/docs/cv.pdf"><i class="fa fa-download" title="Download"></i> CV</a> </nav> </main> {% endblock %}
567
Common Lisp
.l
16
30.4375
83
0.595628
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
aa817cb088a84a11037305e7c1dfb3fbe64a3ecf2f97367f0d597f417d33f0af
32,477
[ -1 ]
32,478
default.html
miscoined_miscoined/templates/layouts/default.html
<!DOCTYPE html> <meta charset="utf-8" /> <title>Kelly Stewart{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Cabin:400,700" /> <link rel="stylesheet" href="/css/main.css" /> <link rel="stylesheet" href="/css/cabin.css" /> <link rel="stylesheet" href="/css/bukhari-script.css" /> <script src="https://use.fontawesome.com/fef6f12071.js"></script> {% block content %}{% endblock %}
440
Common Lisp
.l
9
47.888889
86
0.700696
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
c815c35d0116b4f44eb8aa1e5cd5bac517f03d219543a48910da36af469ab81f
32,478
[ -1 ]
32,479
404.html
miscoined_miscoined/templates/_errors/404.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>404 NOT FOUND</title> <style type="text/css"> html { height: 100%; } body { height: 100%; font-family: 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif; background-color: #DFDFDF; } #main { display: table; width: 100%; height: 100%; } .error { display: table-cell; text-align: center; vertical-align: middle; } .error .code { font-size: 1600%; font-weight: bold; } .error .message { font-size: 400%; } </style> </head> <body> <div id="main"> <div class="error"> <div class="code">404</div> <div class="message">NOT FOUND</div> </div> </div> </body> </html>
683
Common Lisp
.l
42
13.761905
67
0.638365
miscoined/miscoined
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
f9f7b922143c3e5c8c4eb95e53bf2fe7ca20ae3e45f06d218aa3776cf5c2ea74
32,479
[ -1 ]
32,494
LogicResolustion.lisp
animeshjn_resolution-theorem-prover/LogicResolustion.lisp
;Animesh Jain (defun resolution(lc) ;lc is list of all clauses to be considered ;if empty list then no contradiction (cond ((null lc) (print "No contradiction (Empty clauses)") (return-from resolution t))) (setf remainder lc) ;initialize remaining clauses to be considered to all (loop for current_clause in lc ;remove first clause ;for each clause check for atoms in LHS and RHS do (cond ((and (atom current_clause) (not (equal current_clause nil))) (print "Invalid input, enter clausal form") ) ) (remove current_clause remainder) ; for each next clause consider finding all atoms of LHS current_clause in RHS ;if left = right remove one side ;if remainder is nil or nil nil then contradiction ; for each atom in LHS of this clause (loop for atomic_value_left in (first current_clause) ;LHS do (loop for next_clause in remainder do ; pick next clause and remove from remainder (setf remainder (remove next_clause remainder)) ;use option R checks RHS of next_clause (setf remainder (resolve_each next_clause remainder atomic_value_left 'R)) ;returns modified clause ) ) (loop for atomic_value_right in (first (rest current_clause)) ;RHS do (loop for next_clause in remainder do (setf remainder (remove next_clause remainder)) ;use option L to check LHS (setf remainder (resolve_each next_clause remainder atomic_value_right 'L)) ;returns modified clause ) ) ;get LHS to compare with all (setf current_left (first current_clause)) (setf current_right (first (rest current_clause)))) ; (print remainder) ; to print the current resolution ;condition to check for contradiction or resolution (cond ((null remainder) (print "A Contradiction has been found") NIL) ((and(null (first remainder)) (equal (rest remainder) (list NIL))) (print "A Contradiction has been found") NIL) (t (print "No contradiction has been found") t) )) ;resolve each function to resolve single clause with remaining list (defun resolve_each(current_clause remaining current_atom option) ;parameters: current_clause(clause to be considered) ;remaining : list with all the resolutions ;current_atom: atom to look for ;option: R to check RHS L to check LHS of given clause ;option L Left Side (if (equal option 'L) (progn ;remove duplicates from this side first (setf LHS (remove-duplicates (first current_clause))) (loop for atom_value in LHS do (if (equal atom_value current_atom) ;remove the atom if match found (progn (setf current_clause (append (list (remove atom_value (first current_clause))) (rest current_clause))) )))) ;else option R : Right Side (progn ;remove duplicates from this side first (setf RHS (remove-duplicates (first (rest current_clause)))) ;remove the atom if match found (loop for atom_value in RHS do (if (equal atom_value current_atom) (progn (setf current_clause (append (list(first current_clause)) (list (remove atom_value (first (rest current_clause)))) )) )) ))) ;condition to avoid appending NIL (cond ((and(null (first current_clause)) (equal (rest current_clause) (list NIL))) remaining) (t (append (list current_clause) remaining)) ) ;return the remaining list with resolvent ) ; end of resolve_each ;testing session (defun test-resolution() (print(resolution '( ((A)(B C)) ((B)()) ((C)())))) (print(resolution '( ((A)(B C)) ((B)()) (()(A)) ((C)()) ))) (print(resolution '( ((C D)(A)) ((A D E)()) (()(A C)) (()(D)) (()(E)) ))) (print(resolution '(((A B)())))) (print(resolution '( ((A B)()) ((B)()) ( (C)() ) ) )) (print(resolution '( ((A B)()) ((B C)()) ( ()(A B C) ) ) )) (print(resolution '( ((C D)()) ((B)()) ( ()(B C D) ) ) )) (print(resolution '( (()(X Y)) ((B)()) ) )) (print(resolution '() )) ;special case (print(resolution '( ((A)(B)) ((B)(A)) ) )) (print(resolution '(((X Y)()) (()(Y)) (() (X)) ) )) (print(resolution '(((X Z)()) ((Y)()) (() (X)) (() (Y Z))) )) t) (test-resolution)
4,716
Common Lisp
.lisp
92
40.967391
135
0.575244
animeshjn/resolution-theorem-prover
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
af5cfd881742de2ebb680c618e04d90a1886e28497cf6d293a0172f18de66dfc
32,494
[ -1 ]
32,497
LogicResolustion.lib
animeshjn_resolution-theorem-prover/LogicResolustion.lib
#0Y_ #0Y |CHARSET|::|UTF-8| (|SYSTEM|::|C-DEFUN| '|COMMON-LISP-USER|::|RESOLUTION| (|SYSTEM|::|LAMBDA-LIST-TO-SIGNATURE| '(|COMMON-LISP-USER|::|LC|))) (|SYSTEM|::|C-DEFUN| '|COMMON-LISP-USER|::|RESOLVE_EACH| (|SYSTEM|::|LAMBDA-LIST-TO-SIGNATURE| '(|COMMON-LISP-USER|::|CURRENT_CLAUSE| |COMMON-LISP-USER|::|REMAINING| |COMMON-LISP-USER|::|CURRENT_ATOM| |COMMON-LISP-USER|::|OPTION|))) (|SYSTEM|::|C-DEFUN| '|COMMON-LISP-USER|::|TEST-RESOLUTION| (|SYSTEM|::|LAMBDA-LIST-TO-SIGNATURE| '|COMMON-LISP|::|NIL|))
515
Common Lisp
.l
9
55.222222
72
0.658103
animeshjn/resolution-theorem-prover
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
6a816d0113c19fd50925d37d836919bd9321d31684328688a41311b7399a0ae0
32,497
[ -1 ]
32,498
LogicResolustion.fas
animeshjn_resolution-theorem-prover/LogicResolustion.fas
(|SYSTEM|::|VERSION| '(20080430.)) #0Y_ #0Y |CHARSET|::|UTF-8| #Y(#:|1 54 (DEFUN RESOLUTION (LC) ...)-1| #20Y(00 00 00 00 00 00 00 00 20 01 DA 2F 01 DA DC 32 9C C5 19 01) (|COMMON-LISP-USER|::|RESOLUTION| |SYSTEM|::|REMOVE-OLD-DEFINITIONS| #Y(|COMMON-LISP-USER|::|RESOLUTION| #207Y(00 00 00 00 01 00 00 00 26 02 93 01 08 9E 0F 01 14 63 1B 80 96 C5 1B 80 AE 87 01 00 21 08 93 00 05 DC 38 01 31 8E AC 6B 01 38 07 32 69 94 00 63 1B 28 87 01 00 6B 01 63 1B 18 87 01 00 14 6B 01 38 07 32 69 0F 01 AC 6B 01 B0 DD 2D 04 04 0F 01 83 01 AD 8D 9F 64 16 02 83 01 AD 8D 9F 54 16 02 9D 5C 78 63 1B 34 87 01 00 6B 01 63 1B 24 CD 1B 01 CE 14 38 01 31 8E 00 19 02 87 01 00 14 6B 01 38 07 32 69 0F 01 AC 6B 01 B0 DF 2D 04 04 0F 01 83 01 AD 8D 9F 64 16 02 83 01 AD 8D 9F 48 16 02 9D 5B 0F 06 9D 5C 5B 0F 07 83 01 AD 8D 9F FF 69 16 02 0E 01 1D FF B7 0E 01 5B 1C 0A 0E 01 79 63 7B 01 8E 14 FF AB CF 14 38 01 31 8E 02 19 02) ("No contradiction (Empty clauses)" |COMMON-LISP-USER|::|REMAINDER| "Invalid input, enter clausal form" |COMMON-LISP-USER|::|R| |COMMON-LISP-USER|::|RESOLVE_EACH| |COMMON-LISP-USER|::|L| |COMMON-LISP-USER|::|CURRENT_LEFT| |COMMON-LISP-USER|::|CURRENT_RIGHT| "A Contradiction has been found" "A Contradiction has been found" "No contradiction has been found") (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|) (|COMMON-LISP-USER|::|LC|) |COMMON-LISP|::|NIL| 1)) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|)) #Y(#:|57 93 (DEFUN RESOLVE_EACH (CURRENT_CLAUSE REMAINING CURRENT_ATOM ...) ...)-2| #20Y(00 00 00 00 00 00 00 00 20 01 DA 2F 01 DA DC 32 9C C5 19 01) (|COMMON-LISP-USER|::|RESOLVE_EACH| |SYSTEM|::|REMOVE-OLD-DEFINITIONS| #Y(|COMMON-LISP-USER|::|RESOLVE_EACH| #131Y(00 00 00 00 04 00 00 00 26 05 AD 24 00 0E A1 5C 78 38 06 32 6F 0F 02 14 63 1B 80 4C 94 04 38 06 32 6F 0F 01 14 63 1B 19 87 01 00 14 B1 8F 14 0F AC 94 07 38 07 72 69 7B 01 95 07 82 02 23 06 83 01 AD 8D 9F 63 16 02 1B 25 A0 19 05 87 01 00 14 B1 8F 14 12 94 06 7B 01 AD A5 5C 78 38 07 72 69 7B 01 82 02 23 06 83 01 AD 8D 9F 60 16 02 A1 5B 1C 08 95 04 63 7B 01 8E 14 4F B0 7B 01 B0 33 02 23 19 05) (|COMMON-LISP-USER|::|L| |COMMON-LISP-USER|::|LHS| |COMMON-LISP-USER|::|RHS|) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|) (|COMMON-LISP-USER|::|CURRENT_CLAUSE| |COMMON-LISP-USER|::|REMAINING| |COMMON-LISP-USER|::|CURRENT_ATOM| |COMMON-LISP-USER|::|OPTION|) |COMMON-LISP|::|NIL| 1)) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|)) #Y(#:|93 109 (DEFUN TEST-RESOLUTION NIL ...)-3| #20Y(00 00 00 00 00 00 00 00 20 01 DA 2F 01 DA DC 32 9C C5 19 01) (|COMMON-LISP-USER|::|TEST-RESOLUTION| |SYSTEM|::|REMOVE-OLD-DEFINITIONS| #Y(|COMMON-LISP-USER|::|TEST-RESOLUTION| #97Y(00 00 00 00 00 00 00 00 26 01 DA 6F 01 38 01 31 8E DC 6F 01 38 01 31 8E DD 6F 01 38 01 31 8E DE 6F 01 38 01 31 8E DF 6F 01 38 01 31 8E E0 6F 01 38 01 31 8E E1 6F 01 38 01 31 8E E2 6F 01 38 01 31 8E 63 6F 01 38 01 31 8E E3 6F 01 38 01 31 8E E4 6F 01 38 01 31 8E E5 6F 01 38 01 31 8E 02 19 01) ((((|COMMON-LISP-USER|::|A|) (|COMMON-LISP-USER|::|B| |COMMON-LISP-USER|::|C|)) ((|COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|C|) |COMMON-LISP|::|NIL|)) |COMMON-LISP-USER|::|RESOLUTION| (((|COMMON-LISP-USER|::|A|) (|COMMON-LISP-USER|::|B| |COMMON-LISP-USER|::|C|)) ((|COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|A|)) ((|COMMON-LISP-USER|::|C|) |COMMON-LISP|::|NIL|)) (((|COMMON-LISP-USER|::|C| |COMMON-LISP-USER|::|D|) (|COMMON-LISP-USER|::|A|)) ((|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|D| |COMMON-LISP-USER|::|E|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|C|)) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|D|)) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|E|))) (((|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|)) (((|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|C|) |COMMON-LISP|::|NIL|)) (((|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|B| |COMMON-LISP-USER|::|C|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|A| |COMMON-LISP-USER|::|B| |COMMON-LISP-USER|::|C|))) (((|COMMON-LISP-USER|::|C| |COMMON-LISP-USER|::|D|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|B| |COMMON-LISP-USER|::|C| |COMMON-LISP-USER|::|D|))) ((|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|X| |COMMON-LISP-USER|::|Y|)) ((|COMMON-LISP-USER|::|B|) |COMMON-LISP|::|NIL|)) (((|COMMON-LISP-USER|::|A|) (|COMMON-LISP-USER|::|B|)) ((|COMMON-LISP-USER|::|B|) (|COMMON-LISP-USER|::|A|))) (((|COMMON-LISP-USER|::|X| |COMMON-LISP-USER|::|Y|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|Y|)) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|X|))) (((|COMMON-LISP-USER|::|X| |COMMON-LISP-USER|::|Z|) |COMMON-LISP|::|NIL|) ((|COMMON-LISP-USER|::|Y|) |COMMON-LISP|::|NIL|) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|X|)) (|COMMON-LISP|::|NIL| (|COMMON-LISP-USER|::|Y| |COMMON-LISP-USER|::|Z|)))) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|) () |COMMON-LISP|::|NIL| 1)) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|)) #Y(#:|111 111 (TEST-RESOLUTION)-4| #14Y(00 00 00 00 00 00 00 00 20 01 2E 00 19 01) (|COMMON-LISP-USER|::|TEST-RESOLUTION|) (|COMMON-LISP|::|T| |COMMON-LISP|::|T| |COMMON-LISP|::|T|))
6,365
Common Lisp
.l
111
48.198198
83
0.544771
animeshjn/resolution-theorem-prover
0
0
0
GPL-3.0
9/19/2024, 11:42:55 AM (Europe/Amsterdam)
d865c6bf84712e5d9ca063c5c9e19219b97bf102b89744de7567ffd99c7694cd
32,498
[ -1 ]
32,513
wumpus.lisp
alexdijk_Lisp/wumpus.lisp
(load "/home/alexd/Documents/portacle/projects/dotgen.lisp") (defparameter *congestion-city-nodes* nil) (defparameter *congestion-city-edges* nil) (defparameter *visited-nodes* nil) (defparameter *node-num* 30) (defparameter *edge-num* 45) (defparameter *worm-num* 3) (defparameter *cop-odds* 15) (defun random-node () (1+ (random *node-num*))) (defun edge-pair (a b) (unless (eql a b) (list (cons a b) (cons b a)))) (defun make-edge-list () (apply #'append (loop repeat *edge-num* collect (edge-pair (random-node) (random-node))))) (defun direct-edges (node edge-list) (remove-if-not (lambda (x) (eql (car x) node)) edge-list)) (defun get-connected (node edge-list) (let ((visited nil)) (labels ((traverse (node) (unless (member node visited) (push node visited) (mapc (lambda (edge) (traverse (cdr edge))) (direct-edges node edge-list))))) (traverse node)) visited)) (defun find-islands (nodes edge-list) (let ((islands nil)) (labels ((find-island (nodes) (let* ((connected (get-connected (car nodes) edge-list)) (unconnected (set-difference nodes connected))) (push connected islands) (when unconnected (find-island unconnected))))) (find-island nodes)) islands)) (defun connect-with-bridges (islands) (when (cdr islands) (append (edge-pair (caar islands) (caadr islands)) (connect-with-bridges (cdr islands))))) (defun connect-all-islands (nodes edge-list) (append (connect-with-bridges (find-islands nodes edge-list)) edge-list)) (defun make-city-edges () (let* ((nodes (loop for i from 1 to *node-num* collect i)) (edge-list (connect-all-islands nodes (make-edge-list))) (cops (remove-if-not (lambda (x) (zerop (random *cop-odds*))) edge-list))) (add-cops (edges-to-alist edge-list) cops))) (defun edges-to-alist (edge-list) (mapcar (lambda (node1) (cons node1 (mapcar (lambda (edge) (list (cdr edge))) (remove-duplicates (direct-edges node1 edge-list) :test #'equal)))) (remove-duplicates (mapcar #'car edge-list)))) (defun add-cops (edge-alist edges-with-cops) (mapcar (lambda (x) (let ((node1 (car x)) (node1-edges (cdr x))) (cons node1 (mapcar (lambda (edge) (let ((node2 (car edge))) (if (intersection (edge-pair node1 node2) edges-with-cops :test #'equal) (list node2 'cops) edge))) node1-edges)))) edge-alist)) (defun neighbors (node edge-alist) (mapcar #'car (cdr (assoc node edge-alist)))) (defun within-one (a b edge-alist) (member b (neighbors a edge-alist))) (defun within-two (a b edge-alist) (or (within-one a b edge-alist) (some (lambda (x) (within-one x b edge-alist)) (neighbors a edge-alist)))) (defun make-city-nodes (edge-alist) (let ((wumpus (random-node)) (glow-worms (loop for i below *worm-num* collect (random-node)))) (loop for n from 1 to *node-num* collect (append (list n) (cond ((eql n wumpus) '(wumpus)) ((within-two n wumpus edge-alist) '(blood!))) (cond ((member n glow-worms) '(glow-worm)) ((some (lambda (worm) (within-one n worm edge-alist)) glow-worms) '(lights!))) (when (some #'cdr (cdr (assoc n edge-alist))) '(sirens!!)))))) (defun find-empty-node () (let ((x (random-node))) (if (cdr (assoc x *congestion-city-nodes*)) (find-empty-node) x))) (defun draw-city () (ugraph->png "city" *congestion-city-nodes* *congestion-city-edges*)) (defun known-city-nodes () (mapcar (lambda (node) (if (member node *visited-nodes*) (let ((n (assoc node *congestion-city-nodes*))) (if (eql node *player-pos*) (append n '(*)) n)) (list node '?))) (remove-duplicates (append *visited-nodes* (mapcan (lambda (node) (mapcar #'car (cdr (assoc node *congestion-city-edges*)))) *visited-nodes*))))) (defun known-city-edges () (mapcar (lambda (node) (cons node (mapcar (lambda (x) (if (member (car x) *visited-nodes*) x (list (car x)))) (cdr (assoc node *congestion-city-edges*))))) *visited-nodes*)) (defun draw-known-city () (ugraph->png "known-city" (known-city-nodes) (known-city-edges))) (defun new-game () (setf *congestion-city-edges* (make-city-edges)) (setf *congestion-city-nodes* (make-city-nodes *congestion-city-edges*)) (setf *player-pos* (find-empty-node)) (setf *visited-nodes* (list *player-pos*)) (draw-city) (draw-known-city)) (defun walk (pos) (handle-direction pos nil)) (defun charge (pos) (handle-direction pos t)) (defun handle-direction (pos charging) (let ((edge (assoc pos (cdr (assoc *player-pos* *congestion-city-edges*))))) (if edge (handle-new-place edge pos charging) (princ "That location does not exist!")))) (defun handle-new-place (edge pos charging) (let* ((node (assoc pos *congestion-city-nodes*)) (has-worm (and (member 'glow-worm node) (not (member pos *visited-nodes*))))) (pushnew pos *visited-nodes*) (setf *player-pos* pos) (draw-known-city) (cond ((member 'cops edge) (princ "You ran into the cops. Game over!")) ((member 'wumpus node) (if charging (princ "You found the Wumpus!") (princ "You ran into the Wumpus!"))) (charging (princ "You wasted your last bullet. Game Over!")) (has-worm (let ((new-pos (random-node))) (princ "You ran into a Glow Worm Gang! You're now at ") (princ new-pos) (handle-new-place nil new-pos nil))))))
7,043
Common Lisp
.lisp
165
29.309091
81
0.505623
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
75948f8178e158d7c60867fdd958bab389d9219853d402ef1ed2a72df172e637
32,513
[ -1 ]
32,514
machikoro.lisp
alexdijk_Lisp/machikoro.lisp
; simulation of the machi koro game (defun throw-dice (n) (if (eql n 1) (1+ (random 6)) (+ (1+ (random 6)) (1+ (random 6))))) (defun prodrnd () (loop for i from 1 to 100 do (format t "~D " (throw-dice 2))))
238
Common Lisp
.lisp
8
24.875
46
0.546256
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
282a430679162034420fe90c0fa0b7b79a790a94dac13639134ae12a16484b63
32,514
[ -1 ]
32,515
mcclim-ex1.lisp
alexdijk_Lisp/mcclim-ex1.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; McCLIM example (https://github.com/mcclim/mcclim ;; ;; Running: ;; 1. (ql:quickload "mcclim") ;; 2. load, run: ;; (app:app-main) ;; (in-package :common-lisp-user) (defpackage "APP" (:use :clim :clim-lisp) (:export "APP-MAIN")) (in-package :app) ;;; Define a application-frame (a.k.a. application window in traditional GUI's). (define-application-frame superapp () () ;; :panes section describes different parts of the ;; application-frame. This application has only one pane. (:panes (int :interactor :height 400 :width 600)) ;; :layouts section describes how the panes are layed out. ;; This application has one layout named "default" which has a single pane. (:layouts (default int))) ;;; Following function launches an instance of "superapp" application-frame. (defun app-main () (run-frame-top-level (make-application-frame 'superapp)))
950
Common Lisp
.lisp
28
31.785714
80
0.66048
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
b7cfd73ac29ac369aac99d3e58f7696b18a714a937441dc383fa6758d0aec1cf
32,515
[ -1 ]
32,516
gmn.lisp
alexdijk_Lisp/gmn.lisp
(defparameter *small* 1) (defparameter *big* 100) (defun guess-my-number () (ash (+ *small* *big*) -1)) (defun smaller () (setf *big* (1- (guess-my-number))) (guess-my-number)) (defun bigger () (setf *small* (1+ (guess-my-number))) (guess-my-number)) (defun start-over () (setf *small* 1) (setf *big* 100) (guess-my-number))
345
Common Lisp
.lisp
14
22.214286
39
0.629969
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
4e5e0429e70a6dcc486b4f2692b30b4601edda28341f2988b3a8d5fa8dc2c791
32,516
[ 431753, 433657, 448214 ]
32,517
towers.lisp
alexdijk_Lisp/towers.lisp
;; ;; solution to tower of hanoi problem with variable number of disks ;; (defparameter *peg-rack* '((peg-a ()) (peg-b ()) (peg-c ()))) (defun fill-rack (n) (loop as i from n downto 1 do (push i (cadr (assoc 'peg-a *peg-rack*))))) (defparameter *nm* 0) (defun move-disk (src dst) (setf *nm* (1+ *nm*)) (push (pop (cadr (assoc src *peg-rack*))) (cadr (assoc dst *peg-rack*))) (print-towers)) (defun get-lst (peg) (cadr (assoc peg *peg-rack*))) (defun get-len (peg) (length (get-lst peg))) (defun print-towers () (format t "~20:a ~20:a ~20:a~%" (get-lst 'peg-a) (get-lst 'peg-b) (get-lst 'peg-c))) (defun move-tower (disk src dst aux) (if (equalp disk 1) (move-disk src dst) (progn (move-tower (1- disk) src aux dst) (move-disk src dst) (move-tower (1- disk) aux dst src)))) (defun solve (n) (fill-rack n) (print-towers) (move-tower (get-len 'peg-a) 'peg-a 'peg-c 'peg-b) (format t "~%# of moves: ~D~%" *nm*))
1,068
Common Lisp
.lisp
35
24.942857
74
0.552195
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
79f7d710fb7c36585dc8258bad6532d779c034aa9a64dc5bb67e675fb53ebb32
32,517
[ -1 ]
32,518
lol-adv.lisp
alexdijk_Lisp/lol-adv.lisp
;; Description of the wizards world (defparameter *nodes* '((living-room (you are in the living room. a wizard is snoring loudly on the couch.)) (garden (you are in the garden. there is a well in front of you.)) (field (you are in a beautifull field. there are cows grazing. it is bordered by a fence)) (attic (you are in the attic. there is a giant welding torch in the corner.)))) (defparameter *edges* '((living-room (garden west door) (attic upstairs ladder)) (garden (living-room east door) (field north gate)) (field (garden south gate)) (attic (living-room downstairs ladder)))) (defparameter *objects* '(whiskey bucket frog chain goldbar)) (defparameter *object-locations* '((whiskey living-room) (bucket living-room) (chain garden) (goldbar field) (frog garden))) (defparameter *location* 'living-room) ;; Main game engine and functions (defun describe-location (location nodes) (cadr (assoc location nodes))) (defun describe-path (edge) `(there is a ,(caddr edge) going ,(cadr edge) from here.)) (defun describe-paths (location edges) (apply #'append (mapcar #'describe-path (cdr (assoc location edges))))) (defun objects-at (loc objs obj-locs) (labels ((at-loc-p (obj) (eq (cadr (assoc obj obj-locs)) loc))) (remove-if-not #'at-loc-p objs))) (defun describe-objects (loc objs obj-loc) (labels ((describe-obj (obj) `(you see a ,obj on the floor.))) (apply #'append (mapcar #'describe-obj (objects-at loc objs obj-loc))))) (defun look () (append (describe-location *location* *nodes*) (describe-paths *location* *edges*) (describe-objects *location* *objects* *object-locations*))) (defun walk (direction) (let ((next (find direction (cdr (assoc *location* *edges*)) :key #'cadr))) (if next (progn (setf *location* (car next)) (look)) '(you cannot go there!)))) (defun pickup (object) (cond ((member object (objects-at *location* *objects* *object-locations*)) (push (list object 'body) *object-locations*) `(you are now carrying the ,object)) (t '(you cannot get that.)))) (defun inventory () (cons 'items- (objects-at 'body *objects* *object-locations*))) ;; Frontend REPL (defparameter *allowed-commands* '(look walk pickup inventory)) (defun game-repl () (let ((cmd (game-read))) (unless (eq (car cmd) 'quit) (game-print (game-eval cmd)) (game-repl)))) (defun game-read () (let ((cmd (read-from-string (concatenate 'string "(" (read-line) ")")))) (flet ((quote-it (x) (list 'quote x))) (cons (car cmd) (mapcar #'quote-it (cdr cmd)))))) (defun game-eval (sexp) (if (member (car sexp) *allowed-commands*) (eval sexp) '(i do not know that command))) (defun tweak-text (lst caps lit) (when lst (let ((item (car lst)) (rest (cdr lst))) (cond ((eq item #\space) (cons item (tweak-text rest caps lit))) ((member item '(#\! #\? #\.)) (cons item (tweak-text rest t lit))) ((eq item #\") (tweak-text rest caps (not lit))) (lit (cons item (tweak-text rest nil lit))) ((or caps lit) (cons (char-upcase item) (tweak-text rest nil lit))) (t (cons (char-downcase item) (tweak-text rest nil nil))))))) (defun game-print (lst) (princ (coerce (tweak-text (coerce (string-trim "() " (prin1-to-string lst)) 'list) t nil) 'string)) (fresh-line))
3,911
Common Lisp
.lisp
88
34.659091
108
0.56771
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
bd015fccd860e98cc53be7582c5a7986b1696e38becb36b69876e1960f19dbed
32,518
[ -1 ]
32,519
dotgen.lisp
alexdijk_Lisp/dotgen.lisp
(defun dot-name (exp) (substitute-if #\_ (complement #'alphanumericp) (prin1-to-string exp))) (defparameter *max-label-length* 30) (defun dot-label (exp) (if exp (let ((s (write-to-string exp :pretty nil))) (if (> (length s) *max-label-length*) (concatenate 'string (subseq s 0 (- *max-label-length* 3)) "...") s)) "")) (defun nodes->dot (nodes) (mapc (lambda (node) (fresh-line) (princ (dot-name (car node))) (princ "[label=\"") (princ (dot-label node)) (princ "\"];")) nodes)) (defun edges->dot (edges) (mapc (lambda (node) (mapc (lambda (edge) (fresh-line) (princ (dot-name (car node))) (princ "->") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];")) (cdr node))) edges)) (defun graph->dot (nodes edges) (princ "digraph{") (nodes->dot nodes) (edges->dot edges) (princ "}")) (defun dot->png (fname thunk) (with-open-file (*standard-output* fname :direction :output :if-exists :supersede) (funcall thunk)) ;; sbcl variant ;; (sb-ext:run-program "/usr/bin/dot" `("-Tpng" "-O" ,fname) :search t) ;; clisp variant (ext:shell (concatenate 'string "/usr/bin/dot -Tpng -O " fname)) ) (defun graph->png (fname nodes edges) (dot->png fname (lambda () (graph->dot nodes edges)))) (defun uedges->dot (edges) (maplist (lambda (lst) (mapc (lambda (edge) (unless (assoc (car edge) (cdr lst)) (fresh-line) (princ (dot-name (caar lst))) (princ "--") (princ (dot-name (car edge))) (princ "[label=\"") (princ (dot-label (cdr edge))) (princ "\"];"))) (cdar lst))) edges)) (defun ugraph->dot (nodes edges) (princ "graph{") (nodes->dot nodes) (uedges->dot edges) (princ "}")) (defun ugraph->png (fname nodes edges) (dot->png fname (lambda () (ugraph->dot nodes edges))))
2,326
Common Lisp
.lisp
72
22.583333
77
0.484605
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
cc04271e3980048dd5efebaa58d03f0c2f7bfc231ac9c036d41b1781d34860fb
32,519
[ -1 ]
32,520
exp.lisp
alexdijk_Lisp/exp.lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; A system to calculate the top and x1 and x2 of a ;; quadratic equation ;; (defun axDiscr (a b c) (- (expt b 2) (* 4 a c))) (defun axX1X2 (a b c) (let ((D (axDiscr a b c))) (cond ((< D 0) (print "no solutions")) ((= D 0) (let ((x (/ b (* 2 a)))) (print x))) ((> D 0) (let ((x1 (/ (- (* b -1) (sqrt D)) (* 2 a))) (x2 (/ (+ (* b -1) (sqrt D)) (* 2 a)))) (format t "x1:~,2f, x2:~,2f~%" x1 x2)))))) (defun axX0Y0 (a b c) (let ((zx (/ (* -1 b) (* 2 a)))) (let ((zy (+ (* (expt zx 2) a) (* zx b) c))) (format t "x0, y0: (~,2f,~,2f) " zx zy)))) (defun axQuad (a b c) (axX0Y0 a b c) (axX1X2 a b c))
710
Common Lisp
.lisp
22
28.318182
63
0.408759
alexdijk/Lisp
0
0
0
GPL-3.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
f3eaa8e4169980f8afdc2f11275cf302486c35a34ba91782ff143e8ec9ca3ab3
32,520
[ -1 ]
32,545
2lab.lisp
FreshHead_lisp_labs/2lab.lisp
(defun composition(a b) "b must be integer" (cond ((= b 1) a) (t (+ a (composition a (- b 1) ))) ;(print (+ a (composition a (- b 1) )))) ) ) ;(trace composition) (setq a 83.4) (setq b 72) (setq result (composition a b)) (format t "~%Result of composition ~F and ~D is ~F " a b result) (with-open-file (stream "outdata.txt" :direction :output) (format stream "~F" result) )
386
Common Lisp
.lisp
14
25.714286
77
0.633152
FreshHead/lisp_labs
0
0
0
GPL-2.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
e7f34319940e255c641974d57678fcea4eab39a270c5ff74815e73e5b73c12ec
32,545
[ -1 ]
32,546
1lab.lisp
FreshHead_lisp_labs/1lab.lisp
(defun UF1 (x) "UF1(x) = 2sin(x) + cos(2x)" (+ (sin x) (cos (* 2 x))) ) (defun UF2 (x) "UF2(x) = cos^2(x + π / 4 )" (expt (cos (+ (/ 3.14 4) x)) 2) ) (format t "UF1(x) = ~F~%UF2(x) = ~F" (UF1 10) (UF2 10) ) (setq UFR (list (UF1 10) (UF2 10))) (terpri) (write "The list is ") (write UFR) (setq X1 (reverse UFR)) (terpri) (write "Reversed list is ") (write X1) (setq X2 (length UFR)) (terpri) (write "Length of the list is ") (write X2) (setq X3 (+(car UFR) (car (last UFR)))) (terpri) (write "Summ of elements of the list is ") (write X3)
550
Common Lisp
.lisp
25
20.56
56
0.586873
FreshHead/lisp_labs
0
0
0
GPL-2.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
975482254c568201665377e6f664080e42fdde42bab1f9a270abf51a957048e8
32,546
[ -1 ]
32,547
3lab.lisp
FreshHead_lisp_labs/3lab.lisp
(defun composition(a b) "b must be integer" (setq result 0) (loop for i from 1 to b do (setq result (+ result a)) ) (return-from composition result) ) (defstruct city x y ) (defun get_shortest_distance_between_three(first second third) (cond ( (< (distance_between_two first second) (distance_between_two first third)) (setq sum (+ (distance_between_two first second) (distance_between_two second third)))) (t (setq sum (+ (distance_between_two first third) (distance_between_two second third)))) ) (return-from get_shortest_distance_between_three sum) ) (defun distance_between_two(first second) "this functions uses the Pythagorean theorem" (setq katet1 (abs (- (city-x first) (city-x second)))) (setq katet2 (abs (- (city-y first) (city-y second)))) (sqrt(+ (expt katet1 2) (expt katet2 2))) ) (setq a 105.4) (setq b 9) (setq result (composition a b)) (format t "Result of composition ~F and ~D is ~F " a b result) (setq almet (make-city :x 89 :y 55)) (setq kazan (make-city :x 103 :y 67)) (setq moscov (make-city :x 92 :y 12)) ;test distance_between_two with simple values ;(setq city1 (make-city :x 1 :y 4)) ;(setq city2 (make-city :x 3 :y 2)) ;(print (distance_between_two city1 city2)) (terpri) (write almet) (terpri) (write kazan) (terpri) (write moscov) (terpri) (format t "the shortest distance between the cities is ~F" (get_shortest_distance_between_three almet kazan moscov))
1,419
Common Lisp
.lisp
44
30.568182
116
0.720351
FreshHead/lisp_labs
0
0
0
GPL-2.0
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
fc22f03bc514ae9273777731502dbf84fb4b4faf25156ec1353ad87df7dc05f1
32,547
[ -1 ]
32,566
cl-statistics.lisp
croeder_lisp-stats-hunter/cl-statistics.lisp
;;; Statistical functions in Common Lisp. Version 1.04 Feb 24, 2005 ;;; ;;; This code is copyright (c) 2000, 2001, 2002, 2005 by Larry Hunter ;;; ([email protected]) except where otherwise noted. ;;; Thanks to Paul Cohen for the original CLASP package. Thanks also to bug ;;; reports from Rob St. Amant and Lee Ayres, and several bug fixes from ;;; Robert Goldman. ;;; ;;; 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 of the License, or (at your ;;; option) any later version. ;;; This program is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; General Public License for more details. ;;; You should have received a copy of the GNU 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 ;;; The formulas and methods used are largely taken from Bernard Rosner, ;;; "Fundamentals of Biostatistics," 5th edition. "Rosner x" is a page ;;; number. Some numeric functions were taken from CLASP, a 1994 common ;;; lisp package that implemented some of the statistical functions from ;;; "Numeric recipes in C" For CLASP functions, see copyright notice below. ;;; These abreviations used in function and variable names: ;;; ci = confidence interval ;;; cdf = cumulative density function ;;; ge = greater than or equal to ;;; le = less than or equal to ;;; pdf = probability density function ;;; sd = standard deviation ;;; rxc = rows by columns ;;; sse = sample size estimate ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Functions provided: ;;; ;;; Descriptive statistics ;;; Mean, median, mode, geometric mean, range, percentile, variance, ;;; standard-deviation (sd), coefficient-of-variation, ;;; standard-error-of-the-mean ;;; ;;; Distributional functions ;;; Poisson & Binomial ;;; binomial-probability, binomial-cumulative-probability, ;;; binomial-ge-probability, poisson-probability, ;;; poisson-cumulative-probability, poisson-ge-probability, Normal ;;; normal-pdf, convert-to-standard-normal, phi, z, t-distribution, ;;; chi-square, chi-square-cdf ;;; ;;; Confidence Intervals ;;; binomial-probability-ci, poisson-mu-ci, normal-mean-ci, ;;; normal-mean-ci-on-sequences, normal-variance-ci, ;;; normal-variance-ci-on-sequence, normal-sd-ci ;;; ;;; Hypothesis tests (parametric) ;;; z-test, z-test-on-sequence, t-test-one-sample, ;;; t-test-one-sample-on-sequence, t-test-paired, ;;; t-test-paired-on-sequences, t-test-two-sample, ;;; t-test-two-sample-on-sequences, chi-square-test-one-sample, f-test, ;;; binomial-test-one-sample, binomial-test-two-sample, fisher-exact-test, ;;; mcnemars-test, poisson-test-one-sample ;;; ;;; Hypothesis tests (non-parametric) ;;; sign-test, sign-test-on-sequence, wilcoxon-signed-rank-test, ;;; chi-square-test-rxc, chi-square-test-for-trend ;;; Sample size estimates ;;; t-test-one-sample-sse, t-test-two-sample-sse ;;; t-test-paired-sse, binomial-test-one-sample-sse, ;;; binomial-test-two-sample-sse, ;;; binomial-test-paired-sse, correlation-sse ;;; Correlation and Regression ;;; linear-regression, correlation-coefficient, ;;; correlation-test-two-sample, spearman-rank-correlation ;;; Significance test functions ;;; t-significance, f-significance (chi square significance is calculated ;;; from chi-square-cdf in various ways depending on the problem). ;;; Utilities ;;; random-sample, random-pick, bin-and-count, fishers-z-transform, ;;; mean-sd-n, square, choose, permutations, round-float (declaim (optimize (speed 3) (safety 1) (debug 1))) (defpackage :statistics (:nicknames :stats) (:use :common-lisp) (:export #:mean #:median #:mode #:geometric-mean #:range #:percentile #:variance #:standard-deviation #:sd #:coefficient-of-variation #:standard-error-of-the-mean #:permutations #:choose #:binomial-probability #:binomial-cumulative-probability #:binomial-ge-probability #:poisson-probability #:poisson-cumulative-probability #:poisson-ge-probability #:poisson-cdf #:normal-pdf #:convert-to-standard-normal #:phi #:z #:t-distribution #:chi-square #:chi-square-cdf #:binomial-probability-ci #:poisson-mu-ci #:normal-mean-ci #:normal-mean-ci-on-sequence #:normal-variance-ci #:normal-variance-ci-on-sequence #:normal-sd-ci #:normal-sd-ci-on-sequence #:z-test #:z-test-on-sequence #:t-test-one-sample #:t-test-one-sample-on-sequence #:t-test-paired #:t-test-paired-on-sequences #:t-test-two-sample #:t-test-two-sample-on-sequences #:chi-square-test-one-sample #:f-test #:binomial-test-one-sample #:binomial-test-two-sample #:fisher-exact-test #:mcnemars-test #:poisson-test-one-sample #:sign-test #:sign-test-on-sequences #:wilcoxon-signed-rank-test #:wilcoxon-signed-rank-test-on-sequences #:chi-square-test-rxc #:chi-square-test-for-trend #:t-test-one-sample-sse #:t-test-two-sample-sse #:t-test-paired-sse #:binomial-test-one-sample-sse #:binomial-test-two-sample-sse #:binomial-test-paired-sse #:correlation-sse #:linear-regression #:correlation-coefficient #:correlation-test-two-sample #:correlation-test-two-sample-on-sequences #:spearman-rank-correlation #:t-significance #:f-significance #:random-sample #:random-pick #:test-variables #:bin-and-count #:fisher-z-transform #:mean-sd-n #:square #:round-float #:false-discovery-correction #:random-normal)) (in-package :statistics) ;;;;; Macros ;; This macro makes assertions more readable. There are several special ;; types defined: :probability (:prob), :positive-integer (:posint), ;; :positive-number (:posnum), :number-sequence (:numseq), ;; :positive-integer-sequence (:posintseq), :probability-sequence ;; (:probseq), :nonzero-number-sequence (:nonzero-numseq) and :percentage ;; (:percent). Other assertions are assumed to be internal types. The ;; arguments to test-variables are lists. The first element of the list is ;; a variable name, and the second element is either a special or built-in ;; type. If the variable binding is not of the type specified, and error is ;; signalled indicating the problem. One variable may have multiple type ;; requirements, which are conjunctive. (eval-when (:compile-toplevel :load-toplevel :execute) (defmacro test-variables (&rest args) (let ((assertions nil)) (dolist (arg args (append `(or ,@(nreverse assertions)))) (let* ((name (first arg)) (type (second arg)) (test (case type ((:probability :prob) `(and (numberp ,name) (not (minusp ,name)) (<= ,name 1))) ((:positive-integer :posint) `(and (integerp ,name) (plusp ,name))) ((:positive-number :posnum) `(and (numberp ,name) (plusp ,name))) ((:number-sequence :numseq) `(and (typep ,name 'sequence) (every #'numberp ,name) (not (null ,name)))) ((:nonzero-number-sequence :nonzero-numseq) `(and (typep ,name 'sequence) (not (null ,name)) (every #'(lambda (x) (and (numberp x) (not (= 0 x)))) ,name))) ((:probability-sequence :probseq) `(and (typep ,name 'sequence) (not (null ,name)) (every #'(lambda (x) (and (numberp x) (not (minusp x)) (<= x 1.0))) ,name))) ((:positive-integer-sequence :posintseq) `(and (typep ,name 'sequence) (not (null ,name)) (every #'(lambda (x) (and (typep x 'integer) (plusp x))) ,name))) (:percentage `(and (numberp ,name) (plusp ,name) (<= ,name 100))) (:test (third arg)) (t `(typep ,name ',type)))) (message `(error ,(if (eql type :test) name (format nil "~a = ~~a is not a ~a" name (case type ((:positive-integer :posint) "positive integer") ((:positive-number :posnum) "positive number") ((:probability :prob) "probability") ((:number-sequence :numseq) "sequence of numbers") ((:nonzero-number-sequence :nonzero-numseq) "sequence of non-zero numbers") ((:positive-integer-sequence :posintseq) "sequence of positive integers") ((:probability-sequence :probseq) "sequence of probabilities") ((:percent :percentile) "percent") (t type)))) ,@(unless (eql type :test) `(,name))))) (push `(unless ,test ,message) assertions))))) ;; SQUARE (defmacro square (x) `(* ,x ,x)) (defmacro underflow-goes-to-zero (&body body) "Protects against floating point underflow errors and sets the value to 0.0 instead." `(handler-case (progn ,@body) (floating-point-underflow (condition) (declare (ignore condition)) (values 0.0d0)))) ) ;end eval-when ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Descriptive statistics ;;; ;; MEAN ;; Rosner 10 (defun mean (sequence) (test-variables (sequence :numseq)) (/ (reduce #'+ sequence) (length sequence))) ;; MEDIAN ;; Rosner 12 (and 19) (defun median (sequence) (test-variables (sequence :numseq)) (percentile sequence 50)) ;; MODE ;; Rosner 14 ;; returns two values: a list of the modes and the number of times they ;; occur. Rob St. Amant <[email protected]> suggested using a hash ;; table instead of an alist, and Lee Ayres <[email protected]> noted that ;; my revision failed to handle multiple modes properly. (defun mode (sequence) (test-variables (sequence :numseq)) (let ((count-table (make-hash-table :test #'eql)) (modes nil) (mode-count 0)) (map nil (lambda (elt) (incf (gethash elt count-table 0))) sequence) (maphash (lambda (key value) (cond ((> value mode-count) (setf modes (list key) mode-count value)) ((= value mode-count) (push key modes)))) count-table) (values modes mode-count))) ;; GEOMETRIC-MEAN ;; Rosner 16 (defun geometric-mean (sequence &optional (base 10)) (test-variables (sequence :nonzero-numseq) (base :posnum)) (expt base (mean (map 'list #'(lambda (x) (log x base)) sequence)))) ;; RANGE ;; Rosner 18 (defun range (sequence) (test-variables (sequence :numseq)) (- (reduce #'max sequence) (reduce #'min sequence))) ;; PERCENTILE ;; Rosner 19 ;; NB: Aref is 0 based! (defun percentile (sequence percent) (test-variables (sequence :numseq) (percent :percentage)) (let* ((sorted-vect (coerce (sort (copy-seq sequence) #'<) 'simple-vector)) (n (length sorted-vect)) (k (* n (/ percent 100))) (floor-k (floor k))) (if (= k floor-k) (/ (+ (aref sorted-vect k) (aref sorted-vect (1- k))) 2) (aref sorted-vect floor-k)))) ;; VARIANCE ;; Rosner 21 (defun variance (sequence) (test-variables (sequence :numseq)) (let ((mean (mean sequence)) (n (length sequence))) (/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence)) (1- n)))) ;; STANDARD-DEVIATION (SD) ;; Rosner 21 (defun standard-deviation (sequence) (test-variables (sequence :numseq)) (let ((mean (mean sequence)) (n (length sequence))) (sqrt (/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence)) (1- n))))) (defun sd (sequence) (test-variables (sequence :numseq)) (let ((mean (mean sequence)) (n (length sequence))) (sqrt (/ (reduce #'+ (map 'list #'(lambda (x) (square (- mean x))) sequence)) (1- n))))) ;; COEFFICIENT-OF-VARIATION ;; Rosner 24 (defun coefficient-of-variation (sequence) (* 100 (/ (standard-deviation sequence) (mean sequence)))) ;; STANDARD-ERROR-OF-THE-MEAN ;; Rosner 172 (defun standard-error-of-the-mean (sequence) (/ (standard-deviation sequence) (sqrt (length sequence)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Distributional functions ;;; ;;; ;;; Binomial and Poisson distributions ;;; ;; BIONOMIAL-PROBABILITY ;; exact: Rosner 93, approximate 105 ;; P(X=k) for X a binomial random variable with parameters n & p. ;; Binomial expectations for seeing k events in N trials, each having ;; probability p. Use the Poisson approximation if N>100 and P<0.01. (defun binomial-probability (n k p) (test-variables (n :posint) (p :prob) ("K must be between 0 and N (inclusive)" :test (and (>= k 0) (<= k n)))) (if (and (> n 100) (< p 0.01)) (poisson-probability (* n p) k) (let ((p (coerce p 'double-float))) (* (choose n k) (expt p k) (expt (- 1 p) (- n k)))))) ;; BINOMIAL-CUMULATIVE-PROBABILITY ;; Rosner 94 ;; P(X<k) for X a binomial random variable with parameters n & p. ;; Bionomial expecations for fewer than k events in N trials, each having ;; probability p. (defun binomial-cumulative-probability (n k p) (test-variables (n :posint) (k :posint) (p :prob) ("K must be less than or equal to N" :test (<= k n))) (let ((sum-up-to-k-1 0d0)) (dotimes (i k sum-up-to-k-1) (incf sum-up-to-k-1 (binomial-probability n i p))))) ;; BINOMIAL-GE-PROBABILITY ;; Rosner 94 ;; The probability of k or more occurances in N events, each with ;; probability p. (defun binomial-ge-probability (n k p) (- 1 (binomial-cumulative-probability n k p))) ;; Just for convenience later, binomial-le-probability (defun binomial-le-probability (n k p) (test-variables (n :posint) (k :posint) (p :prob) ("K must be less than or equal to N" :test (<= k n))) (let ((sum-up-to-k 0d0)) (dotimes (i (1+ k) sum-up-to-k) (incf sum-up-to-k (binomial-probability n i p))))) ;; POISSON-PROBABILITY ;; Rosner 100 ;; Probability of seeing k events over a time period when the expected ;; number of events over that time is mu. (defun poisson-probability (mu k) (test-variables (mu :posnum) (k :posint)) (let ((mu (coerce mu 'double-float))) (/ (* (exp (- mu)) (expt mu k)) (factorial k)))) ;; POISSON-CUMULATIVE-PROBABILITY ;; Rosner 197 ;; Probability of seeing fewer than K events over a time period when the ;; expected number events over that time is mu. (defun poisson-cumulative-probability (mu k) (test-variables (mu :posnum) (k :posint)) (if (< k 170) (let ((sum 0d0)) (dotimes (x k sum) (incf sum (poisson-probability mu x)))) (let ((mu (coerce mu 'double-float)) (k (coerce k 'double-float))) (- 1d0 (gamma-incomplete k mu))))) ;; POISSON-GE-PROBABILITY ;; Probability of X or more events when expected is mu. (defun poisson-ge-probability (mu x) (- 1 (poisson-cumulative-probability mu x))) ;;; ;;; Normal distributional functions ;;; ;; NORMAL-PDF ;; The probability density function (PDF) for a normal distribution with ;; mean mu and variance sigma at point x. ;; Rosner 115 (defun Normal-pdf (x mu sigma) (test-variables (x number) (mu number) (sigma :posnum)) (* (/ (* (sqrt (* 2 pi)) sigma)) (exp (* (- (/ (* 2 (square sigma)))) (square (- x mu)))))) ;; CONVERT-TO-STANDARD-NORMAL ;; Rosner 130 ;; Convert X from a Normal distribution with mean mu and variance sigma to ;; standard normal (defun convert-to-standard-normal (x mu sigma) (test-variables (x number) (mu number) (sigma :posnum)) (/ (- x mu) sigma)) ;; PHI ;; the CDF of standard normal distribution ;; Rosner 125 (defun phi (x) "Adopted from CLASP 1.4.3, see copyright notice at http://eksl-www.cs.umass.edu/clasp.html" (test-variables (x number)) (setf x (coerce x 'double-float)) (locally (declare (type double-float x)) (* 0.5d0 (+ 1.0d0 (error-function (/ x (sqrt 2.0d0))))))) ;; Z ;; The inverse normal function, P(X<Zu) = u where X is distributed as the ;; standard normal. Uses binary search. ;; Rosner 128. (defun z (percentile &key (epsilon 1d-15)) (test-variables (percentile :prob)) (let ((target (coerce percentile 'double-float))) (do ((min -9d0 min) (max 9d0 max) (guess 0d0 (+ min (/ (- max min) 2d0)))) ((< (- max min) epsilon) guess) (let ((result (coerce (phi guess) 'double-float))) (if (< result target) (setq min guess) (setq max guess)))))) ;; T-DISTRIBUTION ;; Rosner 178 ;; Returns the point which is the indicated percentile in the T distribution ;; with dof degrees of freedom (defun t-distribution (dof percentile) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (test-variables (dof :posint) (percentile :prob)) (find-critical-value #'(lambda (x) (t-significance x dof :tails :positive)) (- 1 percentile))) ;; CHI-SQUARE ;; Rosner 187 ;; Returns the point which is the indicated percentile in the Chi Square ;; distribution with dof degrees of freedom. (defun chi-square (dof percentile) (test-variables (dof :posint) (percentile :prob)) (find-critical-value #'(lambda (x) (chi-square-cdf x dof)) (- 1 percentile))) ;; Chi-square-cdf computes the left hand tail area under the chi square ;; distribution under dof degrees of freedom up to X. (defun chi-square-cdf (x dof) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (test-variables (x :posnum) (dof :posint)) (multiple-value-bind (cdf ignore) (gamma-incomplete (* 0.5 dof) (* 0.5 x)) (declare (ignore ignore)) cdf)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Confidence intervals ;;; ;; BINOMIAL-PROBABILITY-CI ;; Rosner 193 (approximate) & 194 (exact) ;; Confidence intervals on a binomial probability. If a binomial ;; probability of p has been observed in N trials, what is the 1-alpha ;; confidence interval around p? Approximate (using normal theory ;; approximation) when npq >= 10 unless told otherwise (defun binomial-probability-ci (n p alpha &key exact?) (test-variables (n :posint) (p :prob) (alpha :prob)) (if (and (> (* n p (- 1 p)) 10) (not exact?)) (let ((difference (* (z (- 1 (/ alpha 2))) (sqrt (/ (* p (- 1 p)) n))))) (values (- p difference) (+ p difference))) (values (find-critical-value (lambda (p1) (binomial-cumulative-probability n (floor (* p n)) p1)) (- 1 (/ alpha 2))) (find-critical-value (lambda (p2) (binomial-cumulative-probability n (1+ (floor (* p n))) p2)) (/ alpha 2))))) ;; POISSON-MU-CI ;; Confidence interval for the Poisson parameter mu ;; Rosner 197 ;; ;; Given x observations in a unit of time, what is the 1-alpha confidence ;; interval on the Poisson parameter mu (= lambda*T)? ;; ;; Since find-critical-value assumes that the function is monotonic ;; increasing, adjust the value we are looking for taking advantage of ;; reflectiveness (defun poisson-mu-ci (x alpha) (test-variables (x :posnum) (alpha :prob)) (values (find-critical-value #'(lambda (mu) (poisson-cumulative-probability mu (1- x))) (- 1 (/ alpha 2))) (find-critical-value #'(lambda (mu) (poisson-cumulative-probability mu x)) (/ alpha 2)))) ;; NORMAL-MEAN-CI ;; Confidence interval for the mean of a normal distribution ;; Rosner 180 ;; The 1-alpha percent confidence interval on the mean of a normal ;; distribution with parameters mean, sd & n. (defun normal-mean-ci (mean sd n alpha) (test-variables (mean number) (sd :posnum) (n :posint) (alpha :prob)) (let ((t-value (t-distribution (1- n) (- 1 (/ alpha 2))))) (values (- mean (* t-value (/ sd (sqrt n)))) (+ mean (* t-value (/ sd (sqrt n))))))) ;; NORMAL-MEAN-CI-ON-SEQUENCE ;; ;; The 1-alpha confidence interval on the mean of a sequence of numbers ;; drawn from a Normal distribution. (defun normal-mean-ci-on-sequence (sequence alpha) (test-variables (alpha :prob)) ; sequence tested by mean-sd-n (multiple-value-call #'normal-mean-ci (mean-sd-n sequence) alpha)) ;; NORMAL-VARIANCE-CI ;; Rosner 190 ;; The 1-alpha confidence interval on the variance of a sequence of numbers ;; drawn from a Normal distribution. (defun normal-variance-ci (variance n alpha) (test-variables (variance :posnum) (n :posint) (alpha :prob)) (let ((chi-square-low (chi-square (1- n) (- 1 (/ alpha 2)))) (chi-square-high (chi-square (1- n) (/ alpha 2))) (numerator (* (1- n) variance))) (values (/ numerator chi-square-low) (/ numerator chi-square-high)))) ;; NORMAL-VARIANCE-CI-ON-SEQUENCE (defun normal-variance-ci-on-sequence (sequence alpha) (test-variables (sequence :numseq) (alpha :prob)) (let ((variance (variance sequence)) (n (length sequence))) (normal-variance-ci variance n alpha))) ;; NORMAL-SD-CI ;; Rosner 190 ;; As above, but a confidence inverval for the standard deviation. (defun normal-sd-ci (sd n alpha) (multiple-value-bind (low high) (normal-variance-ci (square sd) n alpha) (values (sqrt low) (sqrt high)))) ;; NORMAL-SD-CI-ON-SEQUENCE (defun normal-sd-ci-on-sequence (sequence alpha) (test-variables (sequence :numseq) (alpha :prob)) (let ((sd (standard-deviation sequence)) (n (length sequence))) (normal-sd-ci sd n alpha))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Hypothesis testing ;;; ;; Z-TEST ;; Rosner 228 ;; The significance of a one sample Z test for the mean of a normal ;; distribution with known variance. mu is the null hypothesis mean, x-bar ;; is the observed mean, sigma is the standard deviation and N is the number ;; of observations. If tails is :both, the significance of a difference ;; between x-bar and mu. If tails is :positive, the significance of x-bar ;; is greater than mu, and if tails is :negative, the significance of x-bar ;; being less than mu. Returns a p value. (defun z-test (x-bar n &key (mu 0) (sigma 1) (tails :both)) (test-variables (x-bar number) (n :posint) (mu number) (sigma :posnum)) (let ((z (/ (- x-bar mu) (/ sigma (sqrt n))))) (ecase tails (:both (if (< z 0) (* 2 (phi z)) (* 2 (- 1 (phi z))))) (:negative (phi z)) (:positive (- 1 (phi z)))))) ;; Z-TEST-ON-SEQUENCE (defun z-test-on-sequence (sequence &key (mu 0) (sigma 1) (tails :both)) (test-variables (sequence :numseq)) ; the rest handled by z-test (let ((x-bar (mean sequence)) (n (length sequence))) (z-test x-bar n :mu mu :sigma sigma :tails tails))) ;; T-TEST-ONE-SAMPLE ;; T-TEST-ONE-SAMPLE-ON-SEQUENCE ;; Rosner 216 ;; The significance of a one sample T test for the mean of a normal ;; distribution with unknown variance. X-bar is the observed mean, sd is ;; the observed standard deviation, N is the number of observations and mu ;; is the test mean. -ON-SAMPLE is the same, but calculates the observed ;; values from a sequence of numbers. (defun t-test-one-sample (x-bar sd n mu &key (tails :both)) (test-variables (x-bar number) (sd :posnum) (n :posint) (mu number)) (t-significance (/ (- x-bar mu) (/ sd (sqrt n))) (1- n) :tails tails)) (defun t-test-one-sample-on-sequence (sequence mu &key (tails :both)) (multiple-value-call #'t-test-one-sample (mean-sd-n sequence) mu :tails tails)) ;; T-TEST-PAIRED ;; Rosner 276 ;; The significance of a paired t test for the means of two normal ;; distributions in a longitudinal study. D-bar is the mean difference, sd ;; is the standard deviation of the differences, N is the number of pairs. (defun t-test-paired (d-bar sd n &key (tails :both)) (test-variables (d-bar number) (sd :posnum) (n :posint)) (t-significance (/ d-bar (/ sd (sqrt n))) (1- n) :tails tails)) ;; T-TEST-PAIRED-ON-SEQUENCES ;; Rosner 276 ;; The significance of a paired t test for means of two normal distributions ;; in a longitudinal study. Before is a sequence of before values, after is ;; the sequence of paired after values (which must be the same length as the ;; before sequence). (defun t-test-paired-on-sequences (before after &key (tails :both)) (test-variables (before :numseq) (after :numseq) ("Before and after sequences must be of equal length" :test (= (length before) (length after)))) (multiple-value-call #'t-test-paired (mean-sd-n (map 'list #'- before after)) :tails tails)) ;; T-TEST-TWO-SAMPLE ;; Rosner 282, 294, 297 ;; The significance of the difference of two means (x-bar1 and x-bar2) with ;; standard deviations sd1 and sd2, and sample sizes n1 and n2 respectively. ;; The form of the two sample t test depends on whether the sample variances ;; are equal or not. If the variable variances-equal? is :test, then we ;; use an F test and the variance-significance-cutoff to determine if they ;; are equal. If the variances are equal, then we use the two sample t test ;; for equal variances. If they are not equal, we use the Satterthwaite ;; method, which has good type I error properties (at the loss of some ;; power). (defun t-test-two-sample (x-bar1 sd1 n1 x-bar2 sd2 n2 &key (variances-equal? :test) (variance-significance-cutoff 0.05) (tails :both)) (test-variables (x-bar1 number) (sd1 :posnum) (n1 :posint) (x-bar2 number) (sd2 :posnum) (n2 :posint)) (let (t-statistic dof) (if (ecase variances-equal? (:test (> (f-test (square sd1) n1 (square sd2) n2 :tails tails) variance-significance-cutoff)) ((t :yes :equal) t) ((nil :no :unequal) nil)) (let ((s (sqrt (/ (+ (* (1- n1) (square sd1)) (* (1- n2) (square sd2))) (+ n1 n2 -2))))) (setq t-statistic (/ (- x-bar1 x-bar2) (* s (sqrt (+ (/ n1) (/ n2))))) dof (+ n1 n2 -2))) (let* ((variance-ratio1 (/ (square sd1) n1)) (variance-ratio2 (/ (square sd2) n2))) (setq t-statistic (/ (- x-bar1 x-bar2) (sqrt (+ variance-ratio1 variance-ratio2))) dof (round (/ (square (+ variance-ratio1 variance-ratio2)) (+ (/ (square variance-ratio1) (1- n1)) (/ (square variance-ratio2) (1- n2)))))))) (t-significance t-statistic dof :tails tails))) ;; T-TEST-TWO-SAMPLE-ON-SEQUENCES ;; Same as above, but providing the sequences rather than the summaries. (defun t-test-two-sample-on-sequences (sequence1 sequence2 &key (variance-significance-cutoff 0.05) (tails :both)) (multiple-value-call #'t-test-two-sample (mean-sd-n sequence1) (mean-sd-n sequence2) :tails tails :variance-significance-cutoff variance-significance-cutoff)) ;; F-TEST ;; Rosner 290 ;; F test for the equality of two variances (defun f-test (variance1 n1 variance2 n2 &key (tails :both)) (test-variables (variance1 :posnum) (n1 :posint) (variance2 :posnum) (n2 :posint)) (let ((significance (f-significance (/ variance1 variance2) (1- n1) (1- n2) (not (eql tails :both))))) (ecase tails (:both significance) (:positive (if (> variance1 variance2) significance (- 1 significance))) (:negative (if (< variance1 variance2) significance (- 1 significance)))))) ;; CHI-SQUARE-TEST-ONE-SAMPLE ;; Rosner 246 ;; The significance of a one sample Chi square test for the variance of a ;; normal distribution. Variance is the observed variance, N is the number ;; of observations, and sigma-squared is the test variance. (defun chi-square-test-one-sample (variance n sigma-squared &key (tails :both)) (test-variables (variance :posnum) (n :posint) (sigma-squared :posnum)) (let ((cdf (chi-square-cdf (/ (* (1- n) variance) sigma-squared) (1- n)))) (ecase tails (:negative cdf) (:positive (- 1 cdf)) (:both (if (<= variance sigma-squared) (* 2 cdf) (* 2 (- 1 cdf))))))) ;; BINOMIAL-TEST-ONE-SAMPLE ;; Rosner 249 ;; The significance of a one sample test for the equality of an observed ;; probability p-hat to an expected probability p under a binomial ;; distribution with N observations. Use the normal theory approximation if ;; n*p*(1-p) > 10 (unless the exact flag is true). (defun binomial-test-one-sample (p-hat n p &key (tails :both) (exact? nil)) (test-variables (p-hat :prob) (n :posint) (p :prob)) (let ((q (- 1 p))) (if (and (> (* n p q) 10) (not exact?)) (let ((z (/ (- p-hat p) (sqrt (/ (* p q) n))))) (ecase tails (:negative (phi z)) (:positive (- 1 (phi z))) (:both (* 2 (if (<= p-hat p) (phi z) (- 1 (phi z))))))) (let* ((observed (round (* p-hat n))) (probability-more-extreme (if (<= p-hat p) (binomial-cumulative-probability n observed p) (binomial-ge-probability n observed p)))) (ecase tails ((:negative :positive) probability-more-extreme) (:both (min (* 2 probability-more-extreme) 1.0))))))) ;; BINOMIAL-TEST-TWO-SAMPLE ;; Rosner 357 ;; Are the observed probabilities of an event (p-hat1 and p-hat2) in N1/N2 ;; trials different? The normal theory method implemented here. The exact ;; test is Fisher's contingency table method, below. (defun binomial-test-two-sample (p-hat1 n1 p-hat2 n2 &key (tails :both) (exact? nil)) (test-variables (p-hat1 :prob) (n1 :posint) (p-hat2 :prob) (n2 :posint)) (let* ((p-hat (/ (+ (* p-hat1 n1) (* p-hat2 n2)) (+ n1 n2))) (q-hat (- 1 p-hat)) (z (/ (- (abs (- p-hat1 p-hat2)) (+ (/ (* 2 n1)) (/ (* 2 n2)))) (sqrt (* p-hat q-hat (+ (/ n1) (/ n2))))))) (if (and (> (* n1 p-hat q-hat) 5) (> (* n2 p-hat q-hat) 5) (not exact?)) (* (- 1 (phi z)) (if (eql tails :both) 2 1)) (let ((contingency-table (make-array '(2 2)))) (setf (aref contingency-table 0 0) (* p-hat1 n1) (aref contingency-table 0 1) (- 1 (* p-hat1 n1)) (aref contingency-table 1 0) (* p-hat2 n2) (aref contingency-table 1 1) (- 1 (* p-hat2 n2))) (fisher-exact-test contingency-table :tails tails))))) ;; FISHER-EXACT-TEST ;; Rosner 371 ;; Fisher's exact test. Gives a p value for a particular 2x2 contingency table (defun fisher-exact-test (contingency-table &key (tails :both)) (flet ((table-probability (a b c d) (let ((n (+ a b c d))) (/ (* (factorial (+ a b)) (factorial (+ c d)) (factorial (+ a c)) (factorial (+ b d))) (* (factorial n) (factorial a) (factorial b) (factorial c) (factorial d)))))) (let ((a (aref contingency-table 0 0)) (b (aref contingency-table 0 1)) (c (aref contingency-table 1 0)) (d (aref contingency-table 1 1))) (test-variables (a number) (b number) (c number) (d number)) (let* ((row-margin1 (+ a b)) (row-margin2 (+ c d)) (column-margin1 (+ a c)) (column-margin2 (+ b d)) (n (+ a b c d)) (table-probabilities (make-array (1+ (min row-margin1 row-margin2 column-margin1 column-margin2))))) ;; rearrange so that the first row and column marginals are ;; smallest. Only need to change first margins and a. (cond ((and (< row-margin2 row-margin1) (< column-margin2 column-margin1)) (psetq a d row-margin1 row-margin2 column-margin1 column-margin2)) ((< row-margin2 row-margin1) (psetq a c row-margin1 row-margin2)) ((< column-margin2 column-margin1) (psetq a b column-margin1 column-margin2))) (dotimes (i (length table-probabilities)) (let* ((test-a i) (test-b (- row-margin1 i)) (test-c (- column-margin1 i)) (test-d (- n (+ test-a test-b test-c)))) (setf (aref table-probabilities i) (table-probability test-a test-b test-c test-d)))) (let ((above (reduce #'+ (subseq table-probabilities 0 (1+ a)))) (below (reduce #'+ (subseq table-probabilities a)))) (float (ecase tails ((:both) (* 2 (min above below))) ((:positive) below) ((:negative) above)) 1d0)))))) ;; MCNEMARS-TEST ;; Rosner 379 and 381 ;; McNemar's test for correlated proportions, used for longitudinal ;; studies. Look only at the number of discordant pairs (one treatment is ;; effective and the other is not). If the two treatments are A and B, ;; a-discordant-count is the number where A worked and B did not, and ;; b-discordant-count is the number where B worked and A did not. (defun mcnemars-test (a-discordant-count b-discordant-count &key (exact? nil)) (test-variables (a-discordant-count :posint) (b-discordant-count :posint)) (let ((n (+ a-discordant-count b-discordant-count))) (if (and (> n 20) (not exact?)) (let ((x2 (/ (square (- (abs (- a-discordant-count b-discordant-count)) 1)) n))) (- 1 (chi-square-cdf x2 1))) (cond ((= a-discordant-count b-discordant-count) 1.0) ((< a-discordant-count b-discordant-count) (* 2 (binomial-le-probability n a-discordant-count 1/2))) (t (* 2 (binomial-ge-probability n a-discordant-count 1/2))))))) ;; POISSON-TEST-ONE-SAMPLE ;; Rosner 256 (approximation on 259) ;; The significance of a one sample test for the equality of an observed ;; number of events (observed) and an expected number mu under the poisson ;; distribution. Normal theory approximation is not that great, so don't ;; use it unless told. (defun poisson-test-one-sample (observed mu &key (tails :both) (approximate? nil)) (test-variables (observed :posnum) (mu :posnum)) (if approximate? (let ((x-square (/ (square (- observed mu)) mu))) (- 1 (chi-square-cdf x-square 1))) (let ((probability-more-extreme (if (< observed mu) (poisson-cumulative-probability mu observed) (poisson-ge-probability mu observed)))) (ecase tails ((:negative :positive) probability-more-extreme) (:both (min (* 2 probability-more-extreme) 1.0)))))) ;;; ;;; Non-parametric hypothesis testing ;;; ;; SIGN-TEST ;; Rosner 335-7. ;; Really just a special case of the binomial one sample test with p = 1/2. ;; The normal theory version has a correction factor to make it a better ;; approximation. (defun sign-test (plus-count minus-count &key (exact? nil) (tails :both)) (test-variables (plus-count :posint) (minus-count :posint)) (let* ((n (+ plus-count minus-count)) (p-hat (/ plus-count n))) (if (or (< n 20) exact?) (binomial-test-one-sample p-hat n 0.5 :tails tails :exact? t) (let ((area (- 1 (phi (/ (1- (abs (- plus-count minus-count))) (sqrt n)))))) (if (eql tails :both) (* 2 area) area))))) ;; SIGN-TEST-ON-SEQUENCE ;; Same as above, but takes two sequences and tests whether the entries in ;; one are different (greater or less) than the other. (defun sign-test-on-sequences (sequence1 sequence2 &key (exact? nil) (tails :both)) (test-variables (sequence1 :numseq) (sequence2 :numseq) ("Sequences must be of equal length" :test (= (length sequence1) (length sequence2)))) (let* ((differences (map 'list #'- sequence1 sequence2)) (plus-count (count #'plusp differences)) (minus-count (count #'minusp differences))) (sign-test plus-count minus-count :exact? exact? :tails tails))) ;; WILCOXON-SIGNED-RANK-TEST ;; Rosner 341 ;; A test on the ranking of positive and negative differences (are the ;; positive differences significantly larger/smaller than the negative ;; ones). Assumes a continuous and symmetric distribution of differences, ;; although not a normal one. This is the normal theory approximation, ;; which is only valid when N > 15. ;; This test is completely equivalent to the Mann-Whitney test. (defun wilcoxon-signed-rank-test (differences &optional (tails :both)) (let* ((nonzero-differences (remove 0 differences :test #'=)) (sorted-list (sort (mapcar #'(lambda (dif) (list (abs dif) (sign dif))) nonzero-differences) #'< :key #'first)) (distinct-values (delete-duplicates (mapcar #'first sorted-list))) (ties nil)) (when (< (length nonzero-differences) 16) (error "This Wilcoxon Signed-Rank Test (normal approximation method) requires nonzero N > 15")) (unless (member tails '(:positive :negative :both)) (error "tails must be one of :positive, :negative or :both, not ~a" tails)) ; add avg-rank to the sorted values (dolist (value distinct-values) (let ((first (position value sorted-list :key #'first)) (last (position value sorted-list :key #'first :from-end t))) (if (= first last) (nconc (find value sorted-list :key #'first) (list (1+ first))) (let ((number-tied (1+ (- last first))) (avg-rank (1+ (/ (+ first last) 2)))) ; +1 since 0 based (push number-tied ties) (dotimes (i number-tied) (nconc (nth (+ first i) sorted-list) (list avg-rank))))))) (setq ties (nreverse ties)) (let* ((direction (if (eq tails :negative) -1 1)) (r1 (reduce #'+ (mapcar #'(lambda (entry) (if (= (second entry) direction) (third entry) 0)) sorted-list))) (n (length nonzero-differences)) (expected-r1 (/ (* n (1+ n)) 4)) (ties-factor (if ties (/ (reduce #'+ (mapcar #'(lambda (ti) (- (* ti ti ti) ti)) ties)) 48) 0)) (var-r1 (- (/ (* n (1+ n) (1+ (* 2 n))) 24) ties-factor)) (T-score (/ (- (abs (- r1 expected-r1)) 1/2) (sqrt var-r1)))) (* (if (eq tails :both) 2 1) (- 1 (phi T-score)))))) (defun wilcoxon-signed-rank-test-on-sequences (sequence1 sequence2 &optional (tails :both)) (test-variables (sequence1 :numseq) (sequence2 :numseq) ("Sequences must be of equal length" :test (= (length sequence1) (length sequence2)))) (wilcoxon-signed-rank-test (map 'list #'- sequence1 sequence2) tails)) ;; CHI-SQUARE-TEST-RXC ;; Rosner 395 ;; Takes contingency-table, an RxC array, and returns the significance of ;; the relationship between the row variable and the column variable. Any ;; difference in proportion will cause this test to be significant -- ;; consider using the test for trend instead if you are looking for a ;; consistent change. (defun chi-square-test-rxc (contingency-table) (let* ((rows (array-dimension contingency-table 0)) (columns (array-dimension contingency-table 1)) (row-marginals (make-array rows :initial-element 0.0)) (column-marginals (make-array columns :initial-element 0.0)) (total 0.0) (expected-lt-5 0) (expected-lt-1 0) (expected-values (make-array (list rows columns) :element-type 'single-float)) (x2 0.0)) (dotimes (i rows) (dotimes (j columns) (let ((cell (aref contingency-table i j))) (incf (svref row-marginals i) cell) (incf (svref column-marginals j) cell) (incf total cell)))) (dotimes (i rows) (dotimes (j columns) (let ((expected (/ (* (aref row-marginals i) (aref column-marginals j)) total))) (when (< expected 1) (incf expected-lt-1)) (when (< expected 5) (incf expected-lt-5)) (setf (aref expected-values i j) expected)))) (when (plusp expected-lt-1) (error "This test cannot be used when an expected value is less than one")) (when (> expected-lt-5 (/ (* rows columns) 5)) (error "This test cannot be used when more than 1/5 of the expected values are less than 5.")) (dotimes (i rows) (dotimes (j columns) (incf x2 (/ (square (- (aref contingency-table i j) (aref expected-values i j))) (aref expected-values i j))))) (- 1 (chi-square-cdf x2 (* (1- rows) (1- columns)))))) ;; CHI-SQUARE-TEST-FOR-TREND ;; Rosner 398 ;; This test works on a 2xk table and assesses if there is an increasing or ;; decreasing trend. Arguments are equal sized lists counts. Optionally, ;; provide a list of scores, which represent some numeric attribute of the ;; group. If not provided, scores are assumed to be 1 to k. (defun chi-square-test-for-trend (row1-counts row2-counts &optional scores) (unless scores (setq scores (dotimes (i (length row1-counts) (nreverse scores)) (push (1+ i) scores)))) (test-variables (row1-counts :posintseq) (row2-counts :posintseq) (scores :numseq) ("Sequences must be of equal length" :test (= (length row1-counts) (length row2-counts)))) (let* ((ns (map 'list #'+ row1-counts row2-counts)) (p-hats (map 'list #'/ row1-counts ns)) (n (reduce #'+ ns)) (p-bar (/ (reduce #'+ row1-counts) n)) (q-bar (- 1 p-bar)) (s-bar (mean scores)) (a (reduce #'+ (mapcar (lambda (p-hat ni s) (* ni (- p-hat p-bar) (- s s-bar))) p-hats ns scores))) (b (* p-bar q-bar (- (reduce #'+ (mapcar (lambda (ni s) (* ni (square s))) ns scores)) (/ (square (reduce #'+ (mapcar (lambda (ni s) (* ni s)) ns scores))) n)))) (x2 (/ (square a) b)) (significance (- 1 (chi-square-cdf (float x2) 1)))) (when (< (* p-bar q-bar n) 5) (error "This test is only applicable when N * p-bar * q-bar >= 5")) (format t "~%The trend is ~a, p = ~f" (if (< a 0) "decreasing" "increasing") significance) significance)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Sample size estimates ;;; ;; T-TEST-ONE-SAMPLE-SSE ;; Rosner 238 ;; Returns the number of subjects needed to test whether the mean of a ;; normally distributed sample mu is different from a null hypothesis mean ;; mu-null and variance variance, with alpha, 1-beta and tails as specified. (defun t-test-one-sample-sse (mu mu-null variance &key (alpha 0.05) (1-beta .95) (tails :both)) (test-variables (mu number) (mu-null number) (variance :posnum) (alpha :prob) (1-beta :prob)) (let ((z-beta (z 1-beta)) (z-alpha (z (- 1 (if (eql tails :both) (/ alpha 2) alpha))))) (round-up (/ (* variance (square (+ z-beta z-alpha))) (square (- mu-null mu)))))) ;; T-TEST-TWO-SAMPLE-SSE ;; Rosner 308 ;; Returns the number of subjects needed to test whether the mean mu1 of a ;; normally distributed sample (with variance variance1) is different from a ;; second sample with mean mu2 and variance variance2, with alpha, 1-beta ;; and tails as specified. It is also possible to set a sample size ratio ;; of sample 1 to sample 2. (defun t-test-two-sample-sse (mu1 variance1 mu2 variance2 &key (sample-ratio 1) (alpha 0.05) (1-beta .95) (tails :both)) (test-variables (mu1 number) (variance1 :posnum) (mu2 number) (variance2 :posnum) (sample-ratio :posnum) (alpha :prob) (1-beta :prob)) (let* ((delta2 (square (- mu1 mu2))) (z-term (square (+ (z 1-beta) (z (- 1 (if (eql tails :both) (/ alpha 2) alpha)))))) (n1 (round-up (/ (* (+ variance1 (/ variance2 sample-ratio)) z-term) delta2)))) (values n1 (round-up (* sample-ratio n1))))) ;; T-TEST-PAIRED-SSE ;; Rosner 311 ;; Returns the number of subjects needed to test whether the differences ;; with mean difference-mu and variance difference-variance, with alpha, ;; 1-beta and tails as specified. (defun t-test-paired-sse (difference-mu difference-variance &key (alpha 0.05) (1-beta 0.95) (tails :both)) (test-variables (difference-mu number) (difference-variance :posnum) (alpha :prob) (1-beta :prob)) (round-up (/ (* 2 difference-variance (square (+ (z 1-beta) (z (- 1 (if (eql tails :both) (/ alpha 2) alpha)))))) (square difference-mu)))) ;; BINOMIAL-TEST-ONE-SAMPLE-SSE ;; Rosner 254 ;; Returns the number of subjects needed to test whether an observed ;; probability is significantly different from a particular binomial null ;; hypothesis with a significance alpha and a power 1-beta. (defun binomial-test-one-sample-sse (p-estimated p-null &key (alpha 0.05) (1-beta 0.95) (tails :both)) (test-variables (p-estimated :prob) (p-null :prob) (alpha :prob) (1-beta :prob)) (let ((q-null (- 1 p-null)) (q-estimated (- 1 p-estimated))) (round-up (/ (* p-null q-null (square (+ (z (- 1 (if (eql tails :both) (/ alpha 2) alpha))) (* (z 1-beta) (sqrt (/ (* p-estimated q-estimated) (* p-null q-null))))))) (square (- p-estimated p-null)))))) ;; BINOMIAL-TEST-TWO-SAMPLE-SSE ;; Rosner 384 ;; The number of subjects needed to test if two binomial probabilities are ;; different at a given significance alpha and power 1-beta. The sample ;; sizes can be unequal; the p2 sample is sample-sse-ratio * the size of ;; the p1 sample. It can be a one tailed or two tailed test. (defun binomial-test-two-sample-sse (p1 p2 &key (alpha 0.05) (sample-ratio 1) (1-beta .95) (tails :both)) (test-variables (p1 :prob) (p2 :prob) (alpha :prob) (1-beta :prob) (sample-ratio :posnum)) (let* ((q1 (- 1 p1)) (q2 (- 1 p2)) (delta (abs (- p1 p2))) (p-bar (/ (+ p1 (* sample-ratio p2)) (1+ sample-ratio))) (q-bar (- 1 p-bar)) (z-alpha (z (- 1 (if (eql tails :both) (/ alpha 2) alpha)))) (z-beta (z 1-beta)) (n1 (round-up (/ (square (+ (* (sqrt (* p-bar q-bar (1+ (/ sample-ratio)))) z-alpha) (* (sqrt (+ (* p1 q1) (/ (* p2 q2) sample-ratio))) z-beta))) (square delta))))) (values n1 (round-up (* sample-ratio n1))))) ;; BINOMIAL-TEST-PAIRED-SSE ;; Rosner 387 ;; Sample size estimate for the McNemar (discordant pairs) test. Pd is the ;; projected proportion of discordant pairs among all pairs, and Pa is the ;; projected proportion of type A pairs among discordant pairs. alpha, ;; 1-beta and tails are as above. Returns the number of individuals ;; necessary; that is twice the number of matched pairs necessary. (defun binomial-test-paired-sse (pd pa &key (alpha 0.05) (1-beta 0.95) (tails :both)) (test-variables (pd :prob) (pa :posnum) (alpha :prob) (1-beta :prob)) (let ((qa (- 1 pa)) (z-alpha (z (- 1 (if (eql tails :both) (/ alpha 2) alpha)))) (z-beta (z 1-beta))) (round-up (/ (square (+ z-alpha (* 2 z-beta (sqrt (* pa qa))))) (* 2 (square (- pa 1/2)) pd))))) ;; CORRELATION-SSE ;; Rosner 463 ;; ;; Returns the size of a sample necessary to find a correlation of expected ;; value rho with significance alpha and power 1-beta. (defun correlation-sse (rho &key (alpha 0.05) (1-beta 0.95)) (test-variables (rho :prob) (alpha :prob) (1-beta :prob)) (round-up (+ 3 (/ (square (+ (z (- 1 alpha)) (z 1-beta))) (square (fisher-z-transform rho)))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Correlation and Regression ;;; ;; LINEAR-REGRESSION ;; Rosner 431, 441 for t-test ;; Computes the regression equation for a least squares fit of a line to a ;; sequence of points (each a list of two numbers, e.g. '((1.0 0.1) (2.0 0.2))) ;; and report the intercept, slope, correlation coefficient r, R^2, and the ;; significance of the difference of the slope from 0. (defun linear-regression (points) (test-variables (points sequence)) (let ((xs (map 'list #'first points)) (ys (map 'list #'second points))) (test-variables (xs :numseq) (ys :numseq)) (let* ((x-bar (mean xs)) (y-bar (mean ys)) (n (length points)) (Lxx (reduce #'+ (mapcar (lambda (xi) (square (- xi x-bar))) xs))) (Lyy (reduce #'+ (mapcar (lambda (yi) (square (- yi y-bar))) ys))) (Lxy (reduce #'+ (mapcar (lambda (xi yi) (* (- xi x-bar) (- yi y-bar))) xs ys))) (b (/ Lxy Lxx)) (a (- y-bar (* b x-bar))) (reg-ss (* b Lxy)) (res-ms (/ (- Lyy reg-ss) (- n 2))) (r (/ Lxy (sqrt (* Lxx Lyy)))) (r2 (/ reg-ss Lyy)) (t-test (/ b (sqrt (/ res-ms Lxx)))) (t-significance (t-significance t-test (- n 2) :tails :both))) (format t "~%Intercept = ~f, slope = ~f, r = ~f, R^2 = ~f, p = ~f" a b r r2 t-significance) (values a b r r2 t-significance)))) ;; CORRELATION-COEFFICIENT ;; just r from above. Also called Pearson Correlation (defun correlation-coefficient (points) (test-variables (points sequence)) (let ((xs (map 'list #'first points)) (ys (map 'list #'second points))) (test-variables (xs :numseq) (ys :numseq)) (let ((x-bar (mean xs)) (y-bar (mean ys))) (/ (reduce #'+ (mapcar #'(lambda (xi yi) (* (- xi x-bar) (- yi y-bar))) xs ys)) (sqrt (* (reduce #'+ (mapcar #'(lambda (xi) (square (- xi x-bar))) xs)) (reduce #'+ (mapcar #'(lambda (yi) (square (- yi y-bar))) ys)))))))) ;; CORRELATION-TEST-TWO-SAMPLE ;; Rosner 464 ;; Test if two correlation coefficients are different. Users Fisher's Z ;; test. (defun correlation-test-two-sample (r1 n1 r2 n2 &key (tails :both)) (test-variables (r1 :prob) (n1 :posint) (r2 :prob) (n2 :posint)) (let* ((z1 (fisher-z-transform r1)) (z2 (fisher-z-transform r2)) (lambda (/ (- z1 z2) (sqrt (+ (/ (- n1 3)) (/ (- n2 3))))))) (ecase tails (:both (* 2 (if (<= lambda 0) (phi lambda) (- 1 (phi lambda))))) (:positive (- 1 (phi lambda))) (:negative (phi lambda))))) (defun correlation-test-two-sample-on-sequences (points1 points2 &key (tails :both)) (test-variables (points1 sequence) (points2 sequence)) (let ((r1 (correlation-coefficient points1)) (n1 (length points1)) (r2 (correlation-coefficient points2)) (n2 (length points2))) (correlation-test-two-sample r1 n1 r2 n2 :tails tails))) ;; SPEARMAN-RANK-CORRELATION ;; Rosner 498 ;; Spearman rank correlation computes the relationship between a pair of ;; variables when one or both are either ordinal or have a distribution that ;; is far from normal. It takes a list of points (same format as ;; linear-regression) and returns the spearman rank correlation coefficient ;; and its significance. (defun spearman-rank-correlation (points) (test-variables (points sequence)) (let ((xis (mapcar #'first points)) (yis (mapcar #'second points))) (test-variables (xis :numseq) (yis :numseq)) (let* ((n (length points)) (sorted-xis (sort (copy-seq xis) #'<)) (sorted-yis (sort (copy-seq yis) #'<)) (average-x-ranks (mapcar (lambda (x) (average-rank x sorted-xis)) xis)) (average-y-ranks (mapcar (lambda (y) (average-rank y sorted-yis)) yis)) (mean-x-rank (mean average-x-ranks)) (mean-y-rank (mean average-y-ranks)) (Lxx (reduce #'+ (mapcar (lambda (xi-rank) (square (- xi-rank mean-x-rank))) average-x-ranks))) (Lyy (reduce #'+ (mapcar (lambda (yi-rank) (square (- yi-rank mean-y-rank))) average-y-ranks))) (Lxy (reduce #'+ (mapcar (lambda (xi-rank yi-rank) (* (- xi-rank mean-x-rank) (- yi-rank mean-y-rank))) average-x-ranks average-y-ranks))) (rs (/ Lxy (sqrt (* Lxx Lyy)))) (ts (/ (* rs (sqrt (- n 2))) (sqrt (- 1 (square rs))))) (p (t-significance ts (- n 2) :tails :both))) (format t "~%Spearman correlation coefficient ~f, p = ~f" rs p) (values rs p)))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Significance functions ;;; ;; T-SIGNIFICANCE ;; Lookup table in Rosner; this is adopted from CLASP/Numeric Recipes (defun t-significance (t-statistic dof &key (tails :both)) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (test-variables (t-statistic number) (dof :posint)) (setf dof (float dof t-statistic)) (let ((a (beta-incomplete (* 0.5 dof) 0.5 (/ dof (+ dof (square t-statistic)))))) ;; A is 2*Integral from (abs t-statistic) to Infinity of t-distribution (ecase tails (:both a) (:positive (if (plusp t-statistic) (* .5 a) (- 1.0 (* .5 a)))) (:negative (if (plusp t-statistic) (- 1.0 (* .5 a)) (* .5 a)))))) ;; F-SIGNIFICANCE ;; From CLASP (defun f-significance (f-statistic numerator-dof denominator-dof &optional one-tailed-p) "Adopted from CLASP, but changed to handle F < 1 correctly in the one-tailed case. The `f-statistic' must be a positive number. The degrees of freedom arguments must be positive integers. The `one-tailed-p' argument is treated as a boolean. This implementation follows Numerical Recipes in C, section 6.3 and the `ftest' function in section 13.4." (setq f-statistic (float f-statistic)) (test-variables (f-statistic :posnum) (numerator-dof :posint) (denominator-dof :posint)) (let ((tail-area (beta-incomplete (* 0.5d0 denominator-dof) (* 0.5d0 numerator-dof) (float (/ denominator-dof (+ denominator-dof (* numerator-dof f-statistic))) 1d0)))) (if one-tailed-p (if (< f-statistic 1) (- 1 tail-area) tail-area) (progn (setf tail-area (* 2.0 tail-area)) (if (> tail-area 1.0) (- 2.0 tail-area) tail-area))))) ;; CHI-SQUARE and NORMAL (Gaussian) significance are calculated from their ;; respective CDF functions. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Utilities of potential external use ;;; ;; RANDOM-SAMPLE ;; Return a random sample of size N from sequence, without replacement. If ;; N is equal to or greater than the length of the sequence, return the ;; entire sequence. (defun random-sample (n sequence) (test-variables (n integer) (sequence sequence)) (cond ((null sequence) nil) ((<= n 0) nil) ((< (length sequence) n) sequence) (t (let ((one (random-pick sequence))) (cons one (random-sample (1- n) (remove one sequence :count 1))))))) ;; RANDOM-PICK ;; Random selection from sequence (defun random-pick (sequence) (test-variables (sequence sequence)) (when sequence (elt sequence (random (length sequence))))) ;; RANDOM-NORMAL ;; returns a random number with mean and standard-distribution as specified. (defun random-normal (&key (mean 0) (sd 1)) (test-variables (mean number) (sd :posnum)) (let ((random-standard (z (random 1d0)))) (+ mean (* sd random-standard)))) ;; BIN-AND-COUNT ;; Make N equal width bins and count the number of elements of sequence that ;; belong in each. (defun bin-and-count (sequence n) (let* ((min (reduce #'min sequence)) (increment (/ (- (reduce #'max sequence) min) n)) (bins (make-array n :initial-element 0))) (dotimes (bin n bins) (setf (aref bins bin) (count-if #'(lambda (x) (and (>= x (+ min (* bin increment))) (< x (+ min (* (1+ bin) increment))))) sequence))))) ;; FISHER-Z-TRANSFORM ;; Rosner 458 ;; Transforms the correlation coefficient to an approximately normal ;; distribution. (defun fisher-z-transform (r) (test-variables (r :prob)) (* 1/2 (log (/ (1+ r) (- 1 r))))) ;; PERMUTATIONS ;; How many ways to take n things taken k at a time, when order matters ;; Rosner 88 (defun permutations (n k) (test-variables (n :posint) (k :posint) ("K must be less than or equal to N" :test (<= k n))) (let ((p 1)) (dotimes (i (1+ k) p) (setq p (* p (- n i)))))) ;; COMBINATIONS ;; How may ways to take n things taken k at a time, when order doesn't matter ;; Rosner 90 (defun choose (n k) (test-variables (n :posint) ("K must be between 0 and N (inclusive)" :test (and (>= k 0) (<= k n)))) (/ (factorial n) (* (factorial k) (factorial (- n k))))) ;; MEAN-SD-N ;; A combined calculation that is often useful. Takes a sequence and ;; returns three values: mean, standard deviation and N. (defun mean-sd-n (sequence) (test-variables (sequence :numseq)) (values (mean sequence) (standard-deviation sequence) (length sequence))) ;; ROUND-FLOAT ;; ;; Rounds a floating point number to a specified number of digits precision. (defun round-float (x &key (precision 5)) (test-variables (x number) (precision :posint)) (/ (round x (expt 10 (- precision))) (expt 10 precision))) ;; FALSE-DISCOVERY-CORRECTION ;; ;; A multiple testing correction that is less conservative than Bonferroni. ;; Takes a list of p-values and a false discovery rate, and returns the ;; number of p-values that are likely to be good enough to reject the null ;; at that rate. Returns a second value which is the p-value cutoff. See ;; ;; Benjamini Y and Hochberg Y. "Controlling the false discovery rate: a ;; practical and powerful approach to multiple testing." J R Stat Soc Ser ;; B 57: 289 300, 1995. (defun false-discovery-correction (p-values &key (rate 0.05)) (let ((number-of-tests (length p-values)) (sorted-p-values (sort p-values #'>))) (do ((p-value (pop sorted-p-values) (pop sorted-p-values)) (tests-to-go number-of-tests (1- tests-to-go))) ((or (null p-value) (<= p-value (* rate (/ tests-to-go number-of-tests)))) (values tests-to-go (* rate (/ tests-to-go number-of-tests))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Internal functions ;;; (defun round-up (x) (multiple-value-bind (rounded ignore) (ceiling x) (declare (ignore ignore)) rounded)) (defun sign (x) (cond ((minusp x) -1) ((plusp x) 1) ((zerop x) 0) (t nil))) (defun factorial (number) (if (not (and (integerp number) (>= number 0))) (error "factorial: ~a is not a positive integer" number) (labels ((fact (num) (if (= 0 num) 1 (* num (fact (1- num)))))) (fact number)))) ;; Average rank calculation for non-parametric tests. Ranks are 1 based, ;; but lisp is 0 based, so add 1! (defun average-rank (value sorted-values) (let ((first (position value sorted-values)) (last (position value sorted-values :from-end t))) (1+ (if (= first last) first (/ (+ first last) 2))))) ;;; CLASP utilities: ;;; Copyright (c) 1990 - 1994 University of Massachusetts ;;; Department of Computer Science ;;; Experimental Knowledge Systems Laboratory ;;; Professor Paul Cohen, Director. ;;; All rights reserved. ;;; Permission to use, copy, modify and distribute this software and its ;;; documentation is hereby granted without fee, provided that the above ;;; copyright notice of EKSL, this paragraph and the one following appear ;;; in all copies and in supporting documentation. ;;; EKSL makes no representation about the suitability of this software for any ;;; purposes. It is provided "AS IS", without express or implied warranties ;;; including (but not limited to) all implied warranties of merchantability ;;; and fitness for a particular purpose, and notwithstanding any other ;;; provision contained herein. In no event shall EKSL be liable for any ;;; special, indirect or consequential damages whatsoever resulting from loss ;;; of use, data or profits, whether in an action of contract, negligence or ;;; other tortuous action, arising out of or in connection with the use or ;;; performance of this software, even if EKSL is advised of the possiblity of ;;; such damages. ;;; For more information write to [email protected] (defun error-function (x) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" ;; per CMUCL type-checker, the results of this function may not be ;; correct, if the input isn't a double-float. For now, I think ;; it's easiest to coerce, but later it would be better to ensure ;; that the callers do the right thing. (let ((erf (gamma-incomplete 0.5d0 (square (coerce x 'double-float))))) (if (>= x 0.0d0) erf (- erf)))) ;; Bug fix from [email protected]. Have to coerce an to a double-float, not a float. (defun gamma-incomplete (a x) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (declare (optimize (safety 3))) (setq a (coerce a 'double-float)) (let ((gln (the double-float (gamma-ln a)))) (when (= x 0.0) (return-from gamma-incomplete (values 0.0d0 gln))) (if (< x (+ a 1.0d0)) ;; Use series representation. The following is the code of what ;; Numerical Recipes in C calls ``GSER' (let* ((itmax 1000) (eps 3.0d-7) (ap a) (sum (/ 1d0 a)) (del sum)) (declare (type double-float ap sum del) (type fixnum itmax)) (dotimes (i itmax) (incf ap 1.0d0) (setf del (* del (/ x ap))) (incf sum del) (if (< (abs del) (* eps (abs sum))) (let ((result (underflow-goes-to-zero (* sum (safe-exp (- (* a (log x)) x gln)))))) (return-from gamma-incomplete (values result gln))))) (error "Series didn't converge:~%~ Either a=~s is too large, or ITMAX=~d is too small." a itmax)) ;; Use the continued fraction representation. The following is the ;; code of what Numerical Recipes in C calls ``GCF.'' Their code ;; computes the complement of the desired result, so we subtract from ;; 1.0 at the end. (let ((itmax 1000) (eps 3.0e-7) (gold 0d0) (g 0d0) (fac 1d0) (b1 1d0) (b0 0d0) (anf 0d0) (ana 0d0) (an 0d0) (a1 x) (a0 1d0)) (declare (type double-float gold g fac b1 b0 anf ana an a1 a0)) (dotimes (i itmax) (setf an (coerce (1+ i) 'double-float) ana (- an a) a0 (* fac (+ a1 (* a0 ana))) b0 (* fac (+ b1 (* b0 ana))) anf (* fac an) a1 (+ (* x a0) (* anf a1)) b1 (+ (* x b0) (* anf b1))) (unless (zerop a1) (setf fac (/ 1.0d0 a1) g (* b1 fac)) (if (< (abs (/ (- g gold) g)) eps) (let ((result (underflow-goes-to-zero (* (safe-exp (- (* a (log x)) x gln)) g)))) (return-from gamma-incomplete (values (- 1.0d0 result) gln))) (setf gold g)))) (error "Continued Fraction didn't converge:~%~ Either a=~s is too large, or ITMAX=~d is too small." a itmax))))) (defun gamma-ln (x) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (cond ((<= x 0) (error "arg to gamma-ln must be positive: ~s" x)) ((> x 1.0d302) (error "Argument too large: ~e" x)) ((= x 0.5d0) ;; special case for this arg, since it is used by the error-function (log (sqrt pi))) ((< x 1) ;; Use reflection formula: Gamma(1-z) = z*pi/(Gamma(1+z)sin(pi*z)) (let ((z (- 1.0d0 x))) (- (+ (log z) (log pi)) (+ (gamma-ln (+ 1.0 z)) (log (sin (* pi z))))))) (t (let* ((xx (- x 1.0d0)) (tmp (+ xx 5.5d0)) (ser 1.0d0)) (declare (type double-float xx tmp ser)) (decf tmp (* (+ xx 0.5d0) (log tmp))) (dolist (coef '(76.18009173d0 -86.50532033d0 24.01409822d0 -1.231739516d0 0.120858003d-2 -0.536382d-5)) (declare (type double-float coef)) (incf xx 1.0d0) (incf ser (/ coef xx))) (- (log (* 2.50662827465d0 ser)) tmp))))) (defun error-function-complement (x) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (let* ((z (abs x)) (y (/ 1d0 (+ 1d0 (* 0.5 z)))) ; instead of t (ans (* y (exp (+ (* (- z) z) -1.26551223 (* y (+ 1.00002368 (* y (+ 0.37409196 (* y (+ 0.09678418 (* y (+ -0.18628806 (* y (+ 0.27886807 (* y (+ -1.13520398 (* y (+ 1.48851587 (* y (+ -0.82215223 (* y 0.17087277)))))))))))))))))))))) (declare (type double-float z y ans)) (if (>= x 0.0) ans (- 2.0 ans)))) (defun find-critical-value (p-function p-value &optional (x-tolerance .00001) (y-tolerance .00001)) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (let* ((x-low 0d0) (fx-low 1d0) (x-high 1d0) (fx-high (coerce (funcall p-function x-high) 'double-float))) ;; double up (declare (type double-float x-low fx-low x-high fx-high)) (do () (nil) ;; for general functions, we'd have to try the other way of bracketing, ;; and probably have another way to terminate if, say, y is not in the ;; range of f. (when (>= fx-low p-value fx-high) (return)) (setf x-low x-high fx-low fx-high x-high (* 2.0 x-high) fx-high (funcall p-function x-high))) ;; binary search (do () (nil) (let* ((x-mid (/ (+ x-low x-high) 2.0)) (fx-mid (funcall p-function x-mid)) (y-diff (abs (- fx-mid p-value))) (x-diff (- x-high x-low))) (when (or (< x-diff x-tolerance) (< y-diff y-tolerance)) (return-from find-critical-value x-mid)) ;; Because significance is monotonically decreasing with x, if the ;; function is above the desired p-value... (if (< p-value fx-mid) ;; then the critical x is in the upper half (setf x-low x-mid fx-low fx-mid) ;; otherwise, it's in the lower half (setf x-high x-mid fx-high fx-mid)))))) (defun beta-incomplete (a b x) "Adopted from CLASP 1.4.3, http://eksl-www.cs.umass.edu/clasp.html" (flet ((betacf (a b x) ;; straight from Numerical Recipes in C, section 6.3 (declare (type double-float a b x)) (let ((ITMAX 1000) (EPS 3.0d-7) (qap 0d0) (qam 0d0) (qab 0d0) (em 0d0) (tem 0d0) (d 0d0) (bz 0d0) (bm 1d0) (bp 0d0) (bpp 0d0) (az 1d0) (am 1d0) (ap 0d0) (app 0d0) (aold 0d0)) (declare (type double-float qap qam qab tem d bz bm bp bpp az am ap app aold em)) (setf qab (+ a b) qap (+ a 1d0) qam (- a 1d0) bz (- 1d0 (/ (* qab x) qap))) (dotimes (m ITMAX) (setf em (coerce (float (1+ m)) 'double-float)) (setf tem (+ em em) d (/ (* em (- b em) x) (* (+ qam tem) (+ a tem))) ap (+ az (* d am)) bp (+ bz (* d bm)) d (/ (* (- (+ a em)) (+ qab em) x) (* (+ qap tem) (+ a tem))) app (+ ap (* d az)) bpp (+ bp (* d bz)) aold az am (/ ap bpp) bm (/ bp bpp) az (/ app bpp) bz 1d0) (if (< (abs (- az aold)) (* EPS (abs az))) (return-from betacf az))) (error "a=~s or b=~s too big, or ITMAX too small in BETACF" a b)))) (declare (notinline betacf)) (setq a (coerce a 'double-float) b (coerce b 'double-float) x (coerce x 'double-float)) (when (or (< x 0d0) (> x 1d0)) (error "x must be between 0d0 and 1d0: ~f" x)) ;; bt is the factors in front of the continued fraction (let ((bt (if (or (= x 0d0) (= x 1d0)) 0d0 (exp (+ (gamma-ln (+ a b)) (- (gamma-ln a)) (- (gamma-ln b)) (* a (log x)) (* b (log (- 1d0 x)))))))) (if (< x (/ (+ a 1d0) (+ a b 2.0))) ;; use continued fraction directly (/ (* bt (betacf a b x)) a) ;; use continued fraction after making the symmetry transformation (- 1d0 (/ (* bt (betacf b a (- 1d0 x))) b)))))) (defun safe-exp (x) "Eliminates floating point underflow for the exponential function. Instead, it just returns 0.0d0" (setf x (coerce x 'double-float)) (if (< x (log least-positive-double-float)) 0.0d0 (exp x))) ;;; </code>
74,178
Common Lisp
.lisp
1,555
38.450804
102
0.573022
croeder/lisp-stats-hunter
0
0
0
LGPL-2.1
9/19/2024, 11:43:03 AM (Europe/Amsterdam)
9d3b10dc9a8b1ad36f2123fb3ab84678d6924e05a9340629cfb77aa55f01a065
32,566
[ 23989, 135861 ]
32,583
hello-world.lisp
vinikira_cl-training/hello-world.lisp
"hello world" (format t "hello world") (defun hello-world () (format t "Hello, World")) (hello-world)
109
Common Lisp
.lisp
5
19.4
30
0.683168
vinikira/cl-training
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
28aa5d1608bab876d686a1e15f9f98a77ebc0a9c03c45de92d3c28ba2ffbf2bb
32,583
[ -1 ]
32,600
package.lisp
mkrauss_lazy-list/package.lisp
(in-package :cl-user) (defpackage :com.matthewkrauss.lazy-list (:nicknames :lazy-list) (:use :common-lisp)) (in-package :com.matthewkrauss.lazy-list) (dolist (package '(:lazy-list/core :lazy-list/sequence)) (do-external-symbols (symbol package) (import symbol) (export symbol)))
315
Common Lisp
.lisp
10
26.9
41
0.68543
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
32779c36dd046396069ef4d5ca559421c77e92dd7c6bc70d31323413ebd7d0ee
32,600
[ -1 ]
32,601
package.lisp
mkrauss_lazy-list/test/package.lisp
(in-package :cl-user) (defpackage :com.matthewkrauss.lazy-list/test (:nicknames :lazy-list/test) (:use :cl :parachute :lazy-list))
136
Common Lisp
.lisp
4
31.75
45
0.732824
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
64866bd61afaa0b089bf3e45f9f9ed36bff82aae44f0b7c40e2343577ce6b1c3
32,601
[ -1 ]
32,602
sequence.lisp
mkrauss_lazy-list/test/sequence.lisp
(in-package :com.matthewkrauss.lazy-list/test) (define-test sequence :serial nil) (define-test series :parent sequence :serial nil (is equal '(1 2 3) (materialize (take 3 (series 1 1)))) (is equal '(3 7 11) (materialize (take 3 (series 3 4)))) (is equal '(0 1 2) (materialize (series-to 3 0 1))) (is equal '(1 2 3) (materialize (series-through 3 1 1))) (is equal '(8 12 16) (materialize (series-to 20 8 4)))) (define-test lmapcar :parent sequence :serial nil (is equal '(2.7182817 7.389056 20.085537) (materialize (lmapcar #'exp (series-to 4 1 1)))) (is equal '(7 5 13 8 19) (materialize (take 5 (lmapcar (lambda (x) (if (oddp x) x (/ x 2))) (series 7 3))))) (is equal '(4 8 12) (materialize (lmapcar #'+ (series-through 10 1 1) (series-through 9 3 3))))) (define-test lfilter :parent sequence :serial nil (is equal '(2 4 6 8) (materialize (take 4 (lfilter #'evenp (series 1 1)))))) (define-test lappend :parent sequence :serial nil (is equal '(1 2 3 10 20 30 100 200 300) (materialize (lappend (series-to 4 1 1) (series-to 40 10 10) (series-to 400 100 100)))) (is equal '(0 1 2) (materialize (lappend (series-to 3 0 1) nil))) (is equal '(0 1 2) (materialize (lappend '(0 1 2) nil))) (is equal '(0 1 2) (materialize (lappend nil (series-to 3 0 1)))) (is equal '(0 1 2) (materialize (lappend nil '(0 1 2)))) (is equal '(1 3 5 7 9 11) (materialize (take 6 (lappend (series 1 2) (series 2 2)))))) (define-test lmappend :parent sequence :serial nil (is equal '(6 120 504) (materialize (lmappend (lambda (x y z) (list (* x y z))) (series-to 8 1 3) (series-to 9 2 3) (series-to 10 3 3)))) (is equal '(2 4 6 8 10) (materialize (take 5 (lmappend (lambda (x y) (list (* x 2) (* y 2))) (series 1 2) (series 2 2)))))) (define-test lcross :parent sequence :serial nil (is equal '((1 . 2) (1 . 4) (1 . 6) (3 . 2) (3 . 4) (3 . 6) (5 . 2) (5 . 4) (5 . 6)) (materialize (lcross #'cons (series-to 7 1 2) (series-to 7 2 2)))) (is equal '((1 . 2) (1 . 4) (1 . 6) (3 . 2) (3 . 4) (3 . 6) (5 . 2) (5 . 4) (5 . 6)) (materialize (take 9 (lcross #'cons (series 1 2) (series-to 7 2 2))))) (is equal '((2 . 1) (2 . 3) (2 . 5) (2 . 7) (2 . 9) (2 . 11) (2 . 13) (2 . 15) (2 . 17)) (materialize (take 9 (lcross #'cons (series-to 7 2 2) (series 1 2))))))
2,999
Common Lisp
.lisp
73
29.479452
74
0.466941
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
b6d2f33ba3eb1546bca72faf07f1368984f4675935339aa42f04f44b9516e284
32,602
[ -1 ]
32,603
core.lisp
mkrauss_lazy-list/test/core.lisp
(in-package :com.matthewkrauss.lazy-list/test) (defun subject () (lcons 1 #'1+)) (define-test core :serial nil) (define-test lcons :parent core :serial nil (of-type lcons (make-instance 'lcons :value 1 :fn #'1+)) (of-type lcons (lcons 1 #'1+)) (of-type lcons (lcons* 1 (lambda (x fn) (lcons* (1+ x) fn))))) (define-test lcar-lcdr :parent core :serial nil (is = 1 (lcar (subject))) (is = 2 (lcar (lcdr (subject)))) (is = 3 (lcar (lcdr (lcdr (subject)))))) (define-test take :parent core :serial nil (false (take 0 (subject))) (false (take 14 nil)) (is equal '(1 2 3) (materialize (take 3 (subject))))) (define-test take-while :parent core :serial nil (is = 300 (car (last (materialize (take-while (lambda (x) (<= x 300)) (subject))))))) (define-test materialize :parent core :serial nil (is equal '(1 2 3) (materialize (list 1 2 3))))
927
Common Lisp
.lisp
29
27.758621
64
0.615991
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
fe481182942753821c5e77690b494a2da16a3973cfb63a36a3e5ffb502672051
32,603
[ -1 ]
32,604
lmapcar.lisp
mkrauss_lazy-list/sequence/lmapcar.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defun lmapcar (fn &rest lists) "Map over a lazy list." (if (some #'null lists) nil (lcons* (apply fn (mapcar #'lcar lists)) (lambda (_x _fn) (apply #'lmapcar fn (mapcar #'lcdr lists))))))
281
Common Lisp
.lisp
7
33.285714
62
0.59707
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
0d15cd73a333d9661943d769c230a5a07eb4635bf7e14ba36603f7987ef62610
32,604
[ -1 ]
32,605
package.lisp
mkrauss_lazy-list/sequence/package.lisp
(in-package :cl-user) (defpackage :com.matthewkrauss.lazy-list/sequence (:nicknames :lazy-list/sequence) (:use :common-lisp :lazy-list/core) (:export series series-to series-through lmapcar lfilter lappend lmappend lcross))
308
Common Lisp
.lisp
12
17.666667
49
0.59322
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
d5b852d6aa819792da03b36c3adac799b7a1126474e65c0724ad0516e1a52b8d
32,605
[ -1 ]
32,606
lfilter.lisp
mkrauss_lazy-list/sequence/lfilter.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defgeneric lfilter (predicate list)) (defmethod lfilter (predicate (list null)) nil) (defmethod lfilter (predicate (list lcons)) (let ((value (lcar list))) (if (funcall predicate value) (lcons* value (lambda (x fn) (lfilter predicate (lcdr list)))) (lfilter predicate (lcdr list)))))
385
Common Lisp
.lisp
9
36.333333
57
0.662198
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
ccd302d799fe2512c7419b7d23b4761953ebdbf7a7b4de12d08bc92b21eeb371
32,606
[ -1 ]
32,607
lcross.lisp
mkrauss_lazy-list/sequence/lcross.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defun lcross (fn &rest lists) "Map over multiple lists, combining each element of each list." (when lists (lcross-impl fn (car lists) (cdr lists)))) (defgeneric lcross-impl (fn list lists)) (defmethod lcross-impl (fn (list null) lists) nil) (defmethod lcross-impl (fn (list lcons) (lists null)) (lmapcar fn list)) (defmethod lcross-impl (fn (list lcons) (lists cons)) (lmappend (lambda (item) (apply #'lcross (lambda (&rest args) (apply fn item args)) lists)) list))
613
Common Lisp
.lisp
15
33.6
65
0.634064
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
dfb1f47524c8f50dc3045394d691548fb7496d493045f459f4da6eb42b20ca26
32,607
[ -1 ]
32,608
lmappend.lisp
mkrauss_lazy-list/sequence/lmappend.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defun lmappend (fn &rest lists) "Map over a lazy list appending results." (if (some #'null lists) nil (let ((first-list-result (apply fn (mapcar #'lcar lists)))) (lcons* (lcar first-list-result) (lambda (_value _self) (funcall #'lappend (lcdr first-list-result) (apply #'lmappend fn (mapcar #'lcdr lists))))))))
471
Common Lisp
.lisp
10
35.4
76
0.558696
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
7c82bad89278d0838a0aba7288cbfc4123204dceae1178a6d0a7a2519a572a07
32,608
[ -1 ]
32,609
series.lisp
mkrauss_lazy-list/sequence/series.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defun series (initial increment) "Return a lazy series from INITIAL, adding INCREMENT, indefinitely." (lcons initial (lambda (x) (+ x increment)))) (defun series-to (limit initial increment) (take-while (lambda (x) (< x limit)) (series initial increment))) (defun series-through (last initial increment) (take-while (lambda (x) (<= x last)) (series initial increment)))
461
Common Lisp
.lisp
10
41.2
70
0.694196
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
aa64b341dece0804d94c8862e2262f9ceaab05f3e0af482c3c218e5ffc12a763
32,609
[ -1 ]
32,610
lappend.lisp
mkrauss_lazy-list/sequence/lappend.lisp
(in-package :com.matthewkrauss.lazy-list/sequence) (defun lappend (&rest lists) "Appending multiple lazy lists." (when lists (apply #'lappend-impl lists))) (defgeneric lappend-impl (list &rest lists)) (defmethod lappend-impl ((list null) &rest lists) (apply #'lappend lists)) (defmethod lappend-impl ((list cons) &rest lists) (lcons* (car list) (lambda (_value _self) (apply #'lappend-impl (cdr list) lists)))) (defmethod lappend-impl ((list lcons) &rest lists) (lcons* (lcar list) (lambda (_value _self) (apply #'lappend-impl (lcdr list) lists))))
608
Common Lisp
.lisp
15
35.6
55
0.668367
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
68404e7b1e9428d32fca89a59bc6a0db55a173138c8808f4608a87e660705285
32,610
[ -1 ]
32,611
package.lisp
mkrauss_lazy-list/core/package.lisp
(in-package :cl-user) (defpackage :com.matthewkrauss.lazy-list/core (:nicknames :lazy-list/core) (:use :common-lisp) (:export lcons lcons* lcar lcdr take take-while materialize))
252
Common Lisp
.lisp
11
15.272727
45
0.5625
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
e18c7626aa34165a297ac901eb9e10ebe7ad1a3c345af0255c4dd2b87d0d36f3
32,611
[ -1 ]
32,612
lcons.lisp
mkrauss_lazy-list/core/lcons.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defclass lcons () ((value :initarg :value) (fn :initarg :fn)) (:documentation "Lazy evaluating list-forming cons cell. LCAR returns a recorded value, while LCDR returns NIL or another LCONS where the recorded value is a function transformation of this one.")) (defun lcons* (value fn) "Advanced convenient creation of an lcons, takes a VALUE for LCAR and a transforming FN. The FN should take the LCAR VALUE and a new FN (usually itself), and is responsible for returning either a new LCONS for the LCDR or NIL to end the list." (make-instance 'lcons :value value :fn fn)) (defun lcons (value transform-fn) "Convenient creation of an lcons, takes a VALUE and a transforming FN." (lcons* value (lambda (x fn) (lcons* (funcall transform-fn x) fn))))
841
Common Lisp
.lisp
19
40.894737
73
0.735043
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
2141fac8a26f556eb3160c65fb67d47b99b7e2758c32b902b6f95ecab32a0bcc
32,612
[ -1 ]
32,613
materialize.lisp
mkrauss_lazy-list/core/materialize.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defgeneric materialize (finite-lazy-item) (:documentation "Return a fully materialized representation of a lazy item. For instance, if FINITE-LAZY-ITEM is a lazy list, fully evaluate the and return an actual list. If FINITE-LAZY-ITEM is not materializable this will throw an error.")) (defmethod materialize (item) item) ;; (defmethod materialize ((cell cons)) ;; (cons (materialize (slot-value cell 'a)) ;; (materialize (slot-value cell 'b)))) (defmethod materialize ((nothing null)) nil) (defmethod materialize ((cell lcons)) (cons (materialize (lcar cell)) (materialize (lcdr cell))))
670
Common Lisp
.lisp
14
45.142857
68
0.736923
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
9c65d4ef75bb0fc8f2378f2bb7cd52cd0fb2c7f3c06c7f54255faa308a29050b
32,613
[ -1 ]
32,614
print-object.lisp
mkrauss_lazy-list/core/print-object.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defmethod print-object ((cell lcons) out) (print-unreadable-object (cell out :type t) (format out "~s" (materialize cell))))
180
Common Lisp
.lisp
4
42.25
46
0.725714
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
c4ec52b310205a7cceb068be844cac4603e2932d3f6a20985b0ee6418d8b9038
32,614
[ -1 ]
32,615
take-while.lisp
mkrauss_lazy-list/core/take-while.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defgeneric take-while (predicate sequence)) (defmethod take-while (predicate (sequence null)) nil) (defmethod take-while (predicate (sequence lcons)) (let ((value (lcar sequence))) (when (funcall predicate value) (lcons* value (lambda (x fn) (take-while predicate (lcdr sequence)))))))
379
Common Lisp
.lisp
9
36.111111
59
0.678474
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
4ece9e75e68861a92b3bb3bb3260973cf61b33647789e77f15a822e0ef00f07f
32,615
[ -1 ]
32,616
lcar.lisp
mkrauss_lazy-list/core/lcar.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defgeneric lcar (lazy-cons) (:documentation "The car of a lazy cons cell.")) (defmethod lcar ((cell lcons)) (slot-value cell 'value)) (defmethod lcar ((cell cons)) (car cell))
233
Common Lisp
.lisp
7
31
50
0.721973
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
6105698ea09a1d30b6dc513dbfaab5ebf220508a6442576567c87f1e25d46c13
32,616
[ -1 ]
32,617
take.lisp
mkrauss_lazy-list/core/take.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defgeneric take (number sequence)) (defmethod take (number (sequence null)) nil) (defmethod take ((number (eql 0)) sequence) nil) (defmethod take (number (sequence lcons)) (lcons* (lcar sequence) (lambda (x fn) (take (1- number) (lcdr sequence)))))
325
Common Lisp
.lisp
8
36.125
49
0.683706
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
736ecacea1b0d9f963401ffe290774085a5cde3b7be03bed84fe31b2ce0e2b01
32,617
[ -1 ]
32,618
lcdr.lisp
mkrauss_lazy-list/core/lcdr.lisp
(in-package :com.matthewkrauss.lazy-list/core) (defgeneric lcdr (lazy-cons) (:documentation "The cdr of a lazy cons cell.")) (defmethod lcdr ((cell lcons)) (with-slots (value fn) cell (funcall fn value fn))) (defmethod lcdr ((cell cons)) (cdr cell))
263
Common Lisp
.lisp
8
30.25
50
0.710317
mkrauss/lazy-list
0
0
0
GPL-3.0
9/19/2024, 11:43:11 AM (Europe/Amsterdam)
31fc4b02186d05714ead785af3da0775a1654b5d5108c1f209ce0b4bdde0633f
32,618
[ -1 ]