id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
listlengths
1
47
6,789
wff-vars.lisp
white-flame_clyc/larkc-cycl/wff-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO - convert this to (var . default) instead? (defvar *wff-properties-table* (make-hash-table :test #'eq) "[Cyc] A dictionary mapping WFF property keywords to a list of the form (<corresponding variable> <default value>). Initialized via DEFPARAMETER-WFF.") (defun* wff-properties-table () (:inline t) *wff-properties-table*) (defun* wff-expansion-formula () (:inline t) *wff-expansion-formula*) (defun* wff-debug? () (:inline t) *wff-debug?*) (defun* wff-violation-data-terse? () (:inline t) *wff-violation-data-terse?*) (defun* wff-original-formula () (:inline t) *wff-original-formula*) (defun* note-wff-property (keyword variable default) (:inline t) (setf (gethash keyword (wff-properties-table)) (list variable default))) (defparameter *wff-properties* nil "[Cyc] Dynamically bound to the user-specified WFF properties.") (defparameter *wff-mode* :strict "[Cyc] The primary way WFF will handle constraints. :STRICT -- WFF rejects sentences if they do not provably meet arg constraints. Colloquially known as 'bitchy gatekeeper' mode. :LENIENT -- WFF rejects sentences if they are disjoint with arg constaints, but does not add the provable consequences to the KB.") (defparameter *wff-debug?* nil "[Cyc] Should WFF print out debugging messages during its computation? Setting or binding this to T can be useful when trying to figure out why WFF is rejecting something and WHY-NOT-WFF is not yielding a useful result.") (defparameter *validate-constants?* t "[Cyc] Require that constants referenced by a formula be valid for the formula to be valid?") (defparameter *recognize-variables?* t "[Cyc] Do not impose arg-type constraints on variables?") (defparameter *reject-sbhl-conflicts?* t "[Cyc] Should asserted GAFs that introduce SBHL conflicts be rejected?") (defparameter *inhibit-skolem-asserts?* t "[Cyc] Restrict assertions involving skolems?") (defparameter *simplify-evaluatable-expressions?* nil "[Cyc] Canonicalize evaluatable expressions to their result when possible?") (defparameter *enforce-evaluatable-satisfiability?* t "[Cyc] Must evaluatable literals be satisfiable to be deemed WFFs?") (defparameter *enforce-only-definitional-gafs-in-vocab-mt?* nil ;; TODO - grammar? "[Cyc] Must predicates of GAFs asserted to vocab MTs must be definitional predicates?") (defparameter *inhibit-cyclic-commutative-in-args?* t "[Cyc] Whether to inhibit asserting semantically dubious #$commutativeInArgs or #$commutativeInArgsAndRest GAFs, based on what is already in the KB, as determined by OKK-WRT-PARTIAL-COMMUTATIVITY?.") (defparameter *accumulating-wff-violations?* nil "[Cyc] Whether we note more than one WFF violation, and continue at WFF checks even after failure.") (defparameter *noting-wff-violations?* nil "[Cyc] Should WFF violations be recorded for presentation?") (defparameter *include-suf-defn-violations?* t "[Cyc] Should sufficient defn violations be included in WFF violations?") (defparameter *enforce-literal-wff-idiosyncrasies?* t "[Cyc] Require WFF literals to pass idiosyncratic constraints?") (defparameter *wff-violation-data-terse?* nil "[Cyc] Is WFF module only gathering terse violation data?") (defparameter nil*permit-keyword-variables?* "[Cyc] Transient state variable; is T during the execution of KWT-WFF?.") (defparameter *permit-generic-arg-variables?* nil ;; TODO - not a very useful comment. "[Cyc] Transient state variable; is T sometimes and NIL other times.") (defparameter *validate-expansions?* nil "[Cyc] Should WFF tests be applied to expansions (in addition to given form)?") (defun check-wff-properties (properties) (do-plist (property value properties) (check-type property 'wff-property-p)) (let ((val (getf properties :wff-mode))) (when val (check-type val 'wff-mode-p)))) (defparameter *within-wff?* nil "[Cyc] Transient state variable; is T during the execution of WFF?.") (deflexical *wff-modes* (list :strict :lenient) "[Cyc] See *wff-mode*") (defun* wff-mode () (:inline t) *wff-mode*) (defun* wff-lenient? () (:inline t) (eq :lenient (wff-mode))) (defparameter *wff-formula* nil "[Cyc] Formula being appraised by WFF module.") (defun* wff-formula () (:inline t) *wff-formula*) (defparameter *wff-original-formula* nil "[Cyc] Original formula being appraised by WFF module.") (defparameter *wff-expansion-formula* nil "[Cyc] Expansion formula being appraised by WFF module.") (defparameter *coherence-violations* nil "[Cyc] Descriptions of how the current argument to WFF? is incoherent.") (defparameter *wff-violations* nil "[Cyc] Descriptions of how the current argument to WFF? is invalid.") (defparameter *arity-violations* nil "[Cyc] Descriptions of how a relational expression is not valid wrt arity constraints.") (defparameter *provide-wff-suggestions?* nil "[Cyc] Suggestions for making a non-WFF formula WFF will be attempted when this is non-NIL.") (defparameter *wff-suggestions* nil "[Cyc] Descriptiosn of how the current invalid argument to WFF? can be fixed.") (defparameter *wff-memoization-state* nil "[Cyc] Transient state variable; contains the current memoization state during execution of WFF?.") (defparameter *validating-expansion?* nil "[Cyc] Within WFF tests applied to expansion (in addition to given form)?") (defun* validating-expansion? () (:inline t) *validating-expansion?*) (defparameter *unexpanded-formula* nil "[Cyc] Original formula whose expansion is being considered?") (defun* unexpanded-formula () (:inline t) *unexpanded-formula*)
7,025
Common Lisp
.lisp
127
52.385827
223
0.76086
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b93aad9590d2f6bde35b71798f92612cad9dbf0916eceba83f1d75ede775d881
6,789
[ -1 ]
6,790
kb-mapping-macros.lisp
white-flame_clyc/larkc-cycl/kb-mapping-macros.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; DESIGN - abstracted the serious repetition and massive symbol names into a large macro. Hopefully this all works. I couldn't tell which macro this came from, so made my own. ;; TODO - this file has DO- macros for each iterator type in here. Implement them. ;; TODO - put warnings or deprecation in incomplete iterator definitions to ensure nobody uses them (defmacro define-kb-final-index-spec-iterator (name lambda-list &key ;; list of (name init-form), with lambda-list values in scope slots singleton-form ;; slots are in scope done-form next-form relevant-keylist quiesce-step) (let* ((all-lambda-list-terms (remove '&optional lambda-list)) (iterator (symbolicate name "-FINAL-INDEX-SPEC-ITERATOR")) (state (symbolicate iterator "-STATE")) (with (symbolicate "WITH-" iterator)) (fn-next (symbolicate iterator "-NEXT")) (fn-initialize (symbolicate "INITIALIZE-" state)) (fn-quiesce (symbolicate iterator "-QUIESCE")) (fn-quiesce-one-step (symbolicate fn-quiesce "-ONE-STEP"))) (alexandria:with-gensyms (result done?) `(progn ;; Define the accessors for the state vector (defstruct (,state (:type vector)) ,@ (mapcar #'first slots)) (defmacro ,with (state &body body) `(with-accessors ,',(mapcar (lambda (slot) (let ((name (car slot))) (list name (symbolicate state "-" name)))) slots) ,state ,@body)) ;; Functions (defun ,(symbolicate "NEW-" name "-FINAL-INDEX-SPEC-ITERATOR") ,lambda-list "[Cyc] Makes an iterator which spits out final-index-specs, each of which is a complete path (i.e. a list of keys) leading down to a final index (a list) of assertions." (if (simple-indexed-term-p ,(first lambda-list)) (new-singleton-iterator ,singleton-form) (let ((state (,fn-initialize ,@all-lambda-list-terms))) (new-iterator state (lambda (state) (,with state ,done-form)) #',fn-next)))) (defun ,fn-initialize ,all-lambda-list-terms (declare (ignorable ,@all-lambda-list-terms)) (vector ,@ (mapcar #'second slots))) (defun* ,fn-quiesce-one-step (state) (:inline t) (,with state ,quiesce-step)) (defun* ,fn-quiesce (state) (:inline t) ;; TODO - there is no <name>-current-keylist as the comments originally referenced "[Cyc] Iterates over the keys in STATE until it ends up with its current keylist being valid and relevant, with validity and relevance being determined by :RELEVANT-KEYLIST. It may not need to iterate over any keys in STATE, in which case STATE is left unchanged. Return 0: The relevant final-index-spec list thus formed, if any. Return 1: Whether quiescence terminated early due to running out of keys." (,with state (let ((,result nil) (,done? nil)) (until (or ,result ,done?) (let ((keylist ,relevant-keylist)) (if keylist ,(when slots `(,with state (setf ,result (list* ,(first lambda-list) ,(make-keyword name) keylist)))) (setf ,done? (,fn-quiesce-one-step state))))) (values ,result ,done?)))) (defun ,fn-next (state) (,with state (multiple-value-bind (final-index-spec done?) (,fn-quiesce state) ,next-form (values final-index-spec done?)))))))) ;; GAF-ARG (define-kb-final-index-spec-iterator gaf-arg (term &optional argnum predicate) :slots (;; [Cyc] The input term. (term term) ;; [Cyc] The input predicate. (predicate predicate) ;; [Cyc] A note containing information about the state of the keys, used to control code flow. (note :argnum-keys-are-fresh) ;; [Cyc] The remaining argnums to iterate over. (argnum-keys (if argnum (list argnum) (key-gaf-arg-index-cached term))) ;; [Cyc] The remaining predicates left to iterate over. (predicate-keys nil) ;; [Cyc] The remaining MTs left to iterate over. (mt-keys nil)) :singleton-form (new-gaf-simple-final-index-spec term (or argnum :any) predicate nil) :done-form (or (not argnum-keys) (and (not note) (length= argnum-keys 1) (length<= predicate-keys 1) (not mt-keys))) :next-form (pop mt-keys) ;; [Cyc] If STATE's current keylist is valid and relevant, returns it. Otherwise returns NIL. ;; Valid means that none of its current keys are null. ;; Relevant means that all of its current keys (mt and predicate) are deemed relevant (relevance is established from outside). :relevant-keylist (when-let ((argnum (first argnum-keys)) (predicate-key (first predicate-keys)) (mt (first mt-keys))) (if (and (not predicate) (not (relevant-pred? predicate-key))) (progn (setf mt-keys nil) (setf note nil)) (and (relevant-mt? mt) (list argnum predicate-key mt)))) ;; [Cyc] STATE is assumed to be invalid or irrelevant. This function fixes one cause of invalidity or irrelevance. ;; Invalidity is caused by having no more pending keys in a slot -- refill them. ;; Irrelevance is caused by having the current mt key be irrelevant -- pop it. ;; Returns whether we failed to quiesce because we ran out of keys. :quiesce-step (or (not argnum-keys) (prog1 nil (cond ((not predicate-keys) (gaf-arg-final-index-spec-iterator-refill-predicate-keys state)) ((not mt-keys) (gaf-arg-final-index-spec-iterator-refill-mt-keys state)) (t (pop mt-keys)))))) (defun* do-gaf-arg-index-key-validator (term argnum predicate) (:inline t) "[Cyc] Return T iff TERM, ARGUM, and PREDICATE are valid keys for DO-GAF-ARG-INDEX." ;; TODO - this is in kb-indexing? move it here (gaf-arg-index-key-validator term argnum predicate)) ;; TODO - abstract all the refill functions (defun gaf-arg-final-index-spec-iterator-refill-predicate-keys (state) "[Cyc] Refill the predicate-keys by popping an argnum but don't actually pop the argnum if it's fresh, just note that it's unfresh now." (with-gaf-arg-final-index-spec-iterator state (if (eq :argnum-keys-are-fresh note) (setf note nil) (pop argnum-keys)) (when-let ((argnum-key (car argnum-keys))) (if predicate (setf predicate-keys (list predicate)) (setf predicate-keys (key-gaf-arg-index-cached term argnum-key))) (setf note :predicate-keys-are-fresh)))) (defun gaf-arg-final-index-spec-iterator-refill-mt-keys (state) "[Cyc] Refill the mt-keys by popping a predicate but don't actually pop the predicate if it's fresh, just note that it's unfresh now." (with-gaf-arg-final-index-spec-iterator state (if (eq :predicate-keys-are-fresh note) (setf note nil) (pop predicate-keys)) (when-let ((predicate-key (car predicate-keys))) (if (only-specified-mt-is-relevant?) (setf mt-keys (list *mt*)) (let ((argnum-key (car argnum-keys))) (setf mt-keys (key-gaf-arg-index-cached term argnum-key predicate-key))))))) ;; PREDICATE-EXTENT (define-kb-final-index-spec-iterator predicate-extent (predicate) :slots (;; [Cyc] The input predicate. (predicate predicate) ;; [Cyc] The remaining MTs left to iterate over. (mt-keys (key-predicate-extent-index predicate))) :singleton-form (new-gaf-simple-final-index-spec predicate nil predicate nil) :done-form (not mt-keys) :next-form (pop mt-keys) ;; [Cyc] If STATE's current keylist is valid and relevant, returns it. Otherwise returns NIL. ;; Valid means that none of its current keys are null. ;; Relevant means that its MT is deemed relevant (relevance is established from outside). :relevant-keylist (when-let ((mt (car mt-keys))) (and (relevant-mt? mt) (list mt)))) (defun* do-predicate-extent-index-key-validator (predicate) (:inline t) "[Cyc] Return T iff PREDICATE is a valid key for DO-PREDICATE-EXTENT-INDEX." (fort-p predicate)) ;; NART-ARG (define-kb-final-index-spec-iterator nart-arg (term &optional argnum function) :slots ((term term) (function function) ;; [Cyc] A note containing information about the state of the keys. (note :argnum-keys-are-fresh) ;; [Cyc] The remaining argnums to iterate over. (argnum-keys (if argnum (list argnum) (key-nart-arg-index term))) ;; [Cyc] The remaining functions left to iterate over. (function-keys nil)) :singleton-form (new-nart-simple-final-index-spec term (or argnum :any) function) :done-form (or (not argnum-keys) (and (not note) (length= argnum-keys 1) (not function-keys))) ;; TODO - this one is missing a lot :next-form (missing-larkc 30408)) (defun do-nart-arg-index-key-validator (term index function) "[Cyc] Return T iff TERM, INDEX, and FUNCTION are valid keys for DO-NART-ARG-INDEX." (and (indexed-term-p term) (or (not index) (positive-integer-p index)) (or (not function) (fort-p function)))) ;; Implementation taken from kb-mapping.lisp/map-nart-arg-index ;; TODO - since the next-form above is missing-larkc, this likely won't run anyway (defmacro do-nart-arg-index ((var term &key index function done) &body body) ;; TODO - keyword param usage might be off, as they seem to be nil in dependent-narts usage (when done (error ":done keyword not yet supported in do-nart-arg-index")) `(when (do-nart-arg-index-key-validator ,term ,index ,function) ;; TODO - extract generic iteration macro in iteration.lisp (let ((iterator-var (new-nart-arg-final-index-spec-iterator ,term ,index ,function)) (done-var nil) ;; This is the 'invalid token' return value for the 'next' calls (token-var nil)) (until done-var (let* ((final-index-spec (iteration-next-without-values-macro-helper iterator-var token-var)) (valid (not (eq token-var final-index-spec)))) (when valid (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (let ((done-var2 nil) (token-var2 nil)) (until done-var2 (let* ((,var (iteration-next-without-values-macro-helper final-index-iterator token-var2)) (valid2 (not (eq token-var2 ,var)))) (when valid2 ,@body) (setf done-var2 (not valid2)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))) (setf done-var (not valid))))))) ;; FUNCTION-EXTENT (defun* do-function-extent-index-key-validator (function) (:inline t) "[Cyc] Return T iff FUNCTION is a valid key for DO-FUNCTION-EXTENT-INDEX." (fort-p function)) (defun function-extent-final-index-spec (function) "[Cyc] Makes the single final-index-spec for FUNCTION. This is the only complete path (i.e. a list of keys) leading down to a final index (a list) of assertions." (if (simple-indexed-term-p function) (new-gaf-simple-final-index-spec function '(2 0) #$termOfUnit *tou-mt*) (list function :function-extent))) ;; From kb-indexing, dependent-narts (defmacro do-function-extent-index ((var function &key done) &body body) ;; TODO - is this the value held in token-var, distinguishing from NIL? (when done (error ":done keyword not yet supported in do-function-extent-index")) ;; This one doesn't have an index spec iterator, just a singular spec `(when (do-function-extent-index-key-validator ,function) (let ((final-index-spec (function-extent-final-index-spec ,function))) ;; TODO - iteration macro, seems to be in a simpler form? (let ((final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec :gaf nil nil)) (let ((done-var nil) (token-var nil)) (until done-var (let* ((,var (iteration-next-without-values-macro-helper final-index-iterator token-var)) (valid (not (eq token-var ,var)))) (when valid ,@body) (setf done-var (not valid)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator))))))) ;; PREDICATE-RULE (define-kb-final-index-spec-iterator predicate-rule (predicate &optional sense direction) :slots (;; [Cyc] The input predicate. (predicate predicate) ;; [Cyc] The input direction (direction direction) ;; [Cyc] A note containing information about the state of the keys, used to control code flow. (note :sense-keys-are-fresh) ;; [Cyc] The remaining senses to iterate over. (sense-keys (if sense (list sense) (key-predicate-rule-index predicate))) ;; [Cyc] The remaining MTs left to iterate over. (mt-keys nil) ;; [Cyc] The remaining directions left to iterate over. (direction-keys nil)) :singleton-form (new-rule-simple-final-index-spec predicate sense #'predicate-rule-index-asent-match-p) :done-form (or (not sense-keys) (and (not note) (length= sense-keys 1) (length<= mt-keys 1) (not direction-keys))) :next-form (pop direction-keys) ;; [Cyc] If STATE's current keylist is valid and relevant, returns it. Otherwise returns NIL. ;; Valid means that none of its current keys are null. ;; Relevant means that its MT is deemed relevant (relevance is established from outside). :relevant-keylist (when-let ((sense (car sense-keys)) (mt (car mt-keys)) (direction (car direction-keys))) (if (relevant-mt? mt) (list sense mt direction) (setf direction-keys nil))) :quiesce-step (or (not sense-keys) (prog1 nil (cond ((not mt-keys) (predicate-rule-final-index-spec-iterator-refill-mt-keys state)) ((not direction-keys) (predicate-rule-final-index-spec-iterator-refill-direction-keys state)) (t (error "PREDICATE-RULE iterator quiescence failed with ~s" state)))))) (defun do-predicate-rule-index-key-validator (predicate sense direction) (and (fort-p predicate) (or (not sense) (sense-p sense)) (or (not direction) (direction-p direction)))) ;; TODO - extract do-predicate-rule-index from kb-mapping map-predicate-rule-index (defun predicate-rule-final-index-spec-iterator-refill-mt-keys (state) "[Cyc] Refill the mt-keys by popping a sense but don't actually pop the sense if it's fresh, just note that it's unfresh now." (with-predicate-rule-final-index-spec-iterator state (if (eq :sense-keys-are-fresh note) (setf note nil) (pop sense-keys)) (let ((sense-key (car sense-keys))) (when sense-key (if (only-specified-mt-is-relevant?) (setf mt-keys (list *mt*)) (setf mt-keys (key-predicate-rule-index predicate sense-key))) (setf note :mt-keys-are-fresh))))) (defun predicate-rule-final-index-spec-iterator-refill-direction-keys (state) "[Cyc] Refill the direction-keys by popping an MT but don't actually pop the MT if it's fresh, just note that it's unfresh now." (with-predicate-rule-final-index-spec-iterator state (if (eq :mt-keys-are-fresh note) (setf note nil) (pop mt-keys)) (let ((mt-key (car mt-keys))) (when mt-key (if direction (setf direction-keys (list direction)) (let ((sense-key (car sense-keys))) (setf direction-keys (key-predicate-rule-index-predicate sense-key mt-key)))))))) ;; DECONTEXTUALIZED-IST (define-kb-final-index-spec-iterator decontextualized-ist (predicate sense direction) :slots (;; [Cyc] The input predicate. (predicate predicate) ;; [Cyc] The input direction. (direction direction) ;; [Cyc] A note containing information about the state of the keys, used to control code flow. (note :sense-keys-are-fresh) ;; [Cyc] The remaining senses to iterate over. (sense-keys (if sense (list sense) (key-decontextualized-ist-predicate-rule-index predicate))) ;; [Cyc] The remaining directions left to iterate over. (direction-keys nil)) :singleton-form (new-rule-simple-final-index-spec predicate sense #'decontextualized-ist-predicate-rule-index-asent-match-p) :done-form (or (not sense-keys) (and (not note) (length= sense-keys 1) (not direction-keys))) :next-form (pop direction-keys) :relevant-keylist (when-let ((sense (car sense-keys)) (direction (car direction-keys))) (list sense direction)) :quiesce-step (or (not sense-keys) (prog1 nil (cond ((not direction-keys) (decontextualized-ist-predicate-rule-final-index-spec-iterator-refill-direction-keys state)) (t (error "IST-PREDICATE-RULE iterator quiescense failed with ~s" state)))))) (defun do-decontextualized-ist-predicate-rule-index-key-validator (predicate sense direction) (and (fort-p predicate) (or (not sense) (sense-p sense)) (or (not direction) (direction-p direction)))) (defun decontextualized-ist-predicate-rule-final-index-spec-iterator-refill-direction-keys (state) "[Cyc] Refill the direction-keys by popping a sense but don't actually pop the sense if it's fresh, just note that it's unfresh now." (with-decontextualized-ist-final-index-spec-iterator state (if (eq :sense-keys-are-fresh note) (setf note nil) ;; TODO - Was missing-larkc, assuming this is it since our macros filled in all the accessors, and the sense-keys writer was missing in the java (pop sense-keys)) (let ((sense-key (car sense-keys))) (when sense-key (if direction (setf direction-keys (list direction)) (setf direction-keys (key-decontextualized-ist-predicate-rule-index predicate sense-key))))))) ;; ISA-RULE - incomplete (define-kb-final-index-spec-iterator isa-rule (collection &optional sense direction) :singleton-form (new-rule-simple-final-index-spec collection sense #'isa-rule-index-asent-match-p)) (defun do-isa-rule-index-key-validator (collection sense direction) (do-pred-arg2-rule-index-key-validator collection sense direction)) ;; QUOTED-ISA-RULE - incomplete (define-kb-final-index-spec-iterator quoted-isa-rule (collection &optional sense direction) :singleton-form (new-rule-simple-final-index-spec collection sense #'quoted-isa-rule-index-asent-match-p)) (defun do-quoted-isa-rule-index-key-validator (collection sense direction) (do-pred-arg2-rule-index-key-validator collection sense direction)) ;; GENLS-RULE - incomplete (define-kb-final-index-spec-iterator genls-rule (collection &optional sense direction) :singleton-form (new-rule-simple-final-index-spec collection sense #'genls-rule-index-asent-match-p)) (defun do-genls-rule-index-key-validator (collection sense direction) (do-pred-arg2-rule-index-key-validator collection sense direction)) ;; GENL-MT-RULE - incomplete (define-kb-final-index-spec-iterator genl-mt-rule (genl-mt &optional sense direction) :singleton-form (new-rule-simple-final-index-spec genl-mt sense #'genl-mt-rule-index-asent-match-p)) (defun do-genl-mt-rule-index-key-validator (genl-mt sense direction) (do-pred-arg2-rule-index-key-validator genl-mt sense direction)) ;; PRED-ARG2-RULE - semi-incomplete? there was no new-* function, guessing at lambda list (define-kb-final-index-spec-iterator pred-arg2-rule (pred top-level-key arg2 sense direction) :slots ( ;; [Cyc] The input arg2. (arg2 arg2) ;; [Cyc] The input direction. (direction direction) ;; [Cyc] A note containing information about the state of the keys, used to control code flow. (note :sense-keys-are-fresh) ;; [Cyc] The remaining senses to iterate over. (sense-keys (if sense (list sense) (key-pred-arg2-rule-index pred arg2))) ;; [Cyc] The remaining MTs left to iterate over. (mt-keys nil) ;; [Cyc] The remaining directions left to iterate over. (direction-keys nil) ;; [Cyc] The input pred. (pred pred) ;; [Cyc] The top-level key to the final index, used for subclassing. (top-level-key top-level-key)) :done-form (or (not sense-keys) (and (not note) (length= sense-keys 1) (length<= mt-keys 1) (not direction-keys))) :next-form (pop direction-keys) ;; [Cyc] If STATE's current keylist is valid and relevant, returns it. Otherwise returns NIL. ;; Valid means that none of its current keys are null. ;; Relevant means that its mt is deemed relevant (relevance is established from outside) :relevant-keylist (when-let ((sense (car sense-keys)) (mt (car mt-keys)) (direction (car direction-keys))) (if (relevant-mt? mt) (list sense mt direction) (setf direction-keys nil))) ;; [Cyc] STATE is assumed to be invalid or irrelevant. ;; This function fixes one cause of invalidity or irrelevance. ;; Invalidity is caused by having no more pending keys in a slot -- refill them. ;; Irrelevance is caused by having the current mt key be irrelevant -- pop it. :quiesce-step (or (not sense-keys) (prog1 nil (cond ((not mt-keys) (pred-arg2-rule-final-index-spec-iterator-refill-mt-keys state)) ((not direction-keys) (pred-arg2-rule-final-index-spec-iterator-refill-direction-keys state)) (t (error "PRED-ARG2-RULE iterator quiescense failed with ~s" state)))))) (defun do-pred-arg2-rule-index-key-validator (arg2 sense direction) (and (fort-p arg2) (or (not sense) (sense-p sense)) (or (not direction) (direction-p direction)))) (defun pred-arg2-rule-final-index-spec-iterator-refill-mt-keys (state) "[Cyc] Refill the mt-keys by popping a sense but don't actually pop the sense if it's fresh, just note that it's unfresh now." (with-pred-arg2-rule-final-index-spec-iterator state (if (eq :sense-keys-are-fresh note) (setf note nil) (pop sense-keys)) (when-let ((sense-key (car sense-keys))) (if (only-specified-mt-is-relevant?) (setf mt-keys (list *mt*)) (setf mt-keys (key-pred-arg2-rule-index pred arg2 sense-key))) (setf note :mt-keys-are-fresh)))) (defun pred-arg2-rule-final-index-spec-iterator-refill-direction-keys (state) "[Cyc] Refill the direction-keys by popping an MT but don't actually pop the MT if it's fresh, just note that it's unfresh now." (with-pred-arg2-rule-final-index-spec-iterator state (if (eq :mt-keys-are-fresh note) (setf note nil) (pop mt-keys)) (when-let ((mt-key (car mt-keys))) (if direction (setf direction-keys (list direction)) (let ((sense-key (car sense-keys))) (setf direction-keys (key-pred-arg2-rule-index pred arg2 sense-key mt-key))))))) (defun key-pred-arg2-rule-index (pred arg2 &optional sense mt) (case pred (#$isa (key-isa-rule-index arg2 sense mt)) (#$quotedIsa (missing-larkc 12753)) (#$genls (key-genls-rule-index arg2 sense mt)) (#$genlMt (key-genl-mt-rule-index arg2 sense mt)) (t (error "Unexpected pred in PREG-ARG2 indexing: ~s" pred)))) ;; FUNCTION-RULE - incomplete? (define-kb-final-index-spec-iterator function-rule (function &optional direction) :slots ((function function) (direction direction) ;; [Cyc] A note containing information about the state of the keys, used to control code flow. (note :mt-keys-are-fresh) ;; [Cyc] The remaining MTs left to iterate over. (mt-keys (if (only-specified-mt-is-relevant?) (list *mt*) (key-function-rule-index function))) ;; [Cyc] The remaining directions left to iterate over. (direction-keys nil)) :singleton-form (new-rule-simple-final-index-spec function :neg #'function-rule-index-asent-match-p) :done-form (or (not mt-keys) (and (not note) (length= mt-keys 1) (not direction-keys))) ) (defun do-function-rule-index-key-validator (function direction) (and (fort-p function) (or (not direction) (direction-p direction)))) ;; EXCEPTION-RULE - incomplete, no INITIALIZE- function to get the slot values from (define-kb-final-index-spec-iterator exception-rule (rule &optional direction) :slots ((rule (missing-larkc 30402)) (direction (missing-larkc 30402))) :singleton-form (new-rule-simple-final-index-spec rule :pos #'exception-rule-index-asent-match-p)) (defun do-exception-rule-index-key-validator (rule direction) (and (rule-assertion-p rule) (or (not direction) (direction-p direction)))) ;; PRAGMA-RULE - incomplete, no INITIALIZE- function to get the slot values from (define-kb-final-index-spec-iterator pragma-rule (rule &optional direction) :slots ((rule (missing-larkc 30403)) (direction (missing-larkc 30403))) :singleton-form (new-rule-simple-final-index-spec rule :pos #'pragma-rule-index-asent-match-p)) (defun do-pragma-rule-index-key-validator (rule direction) (and (rule-assertion? rule) (or (not direction) (direction-p direction)))) ;; MT (defun do-mt-index-key-validator (mt type) (and (fort-p mt) (not (broad-mt? mt)) (or (not type) (missing-larkc 32091)))) (defun mt-final-index-spec (mt) "[Cyc] Makes the single final-index-spec for MT. This is the only complete path (i.e. a list of keys) leading down to a final index (a list) of assertions." (if (simple-indexed-term-p mt) (new-assertion-simple-final-index-spec mt #'mt-index-assertion-match-p) (list mt :ist))) ;; OTHER (defun do-other-index-key-validator (term type) (and (indexed-term-p term) (or (not type) (missing-larkc 32092)))) (defun other-final-index-spec (term) "[Cyc] Makes the single final-index-spec for TERM. This is the only complete path (i.e. a list of keys) leading down to a final index (a list) of assertions." (if (simple-indexed-term-p term) (new-assertion-simple-final-index-spec term #'other-index-assertion-match-p) (list term :other))) (defun* other-simple-final-index-spec-p (object) (:inline t) (and (eq (car object) :simple) ;; TODO - symbol vs function of final-index-spec (eq (fourth object) #'other-index-assertion-match-p))) (defun* other-complex-final-index-spec-p (object) (:inline t) (eq :other (second object))) (defun other-final-index-spec-p (final-index-spec) "[Cyc] The other index is the only one that needs to do post-hoc semantic filtering. It's no tonly redundant for ohter indexes, it's INCORRECT in the case of the mt-index. The mt-index needs to NOT do post-hoc semantic filtering, but the ohter index requires it. Therefore, we need to gate it based on whether these assertions came from the other index." (or (other-simple-final-index-spec-p final-index-spec) (other-complex-final-index-spec-p final-index-spec))) (defun other-index-assertion-match-p (assertion term) (matches-other-index assertion term)) ;; From kb-indexing, dependent-narts (defmacro do-other-index ((var term &key type truth direction done) &body body) ;; Body is after a missing-larkc, so is never entered (declare (ignore body)) (when (or truth direction done) (error "Unhandled keyword parameters in do-other-index: :TRUTH ~s, :DIRECTION ~s, :DONE ~s" truth direction done)) ;; TODO - are we multi-evaluating things like TERM? are these intended to be simple literals/varnames in usage? `(when (do-other-index-key-validator ,term ,type) (let ((final-index-spec (other-final-index-spec ,term)) (final-index-iterator nil)) (unwind-protect (progn (setf final-index-iterator (new-final-index-iterator final-index-spec nil nil nil)) (let ((done-var nil) (token-var nil)) (until done-var (let* ((,var (iteration-next-without-values-macro-helper final-index-iterator token-var)) (valid (not (eq token-var ,var)))) (when valid (missing-larkc 30388) ;;,@body ) (setf done-var (not valid)))))) (when final-index-iterator (destroy-final-index-iterator final-index-iterator)))))) ;; TERM - unique, doesn't use the define- macro, dispatches to the above iterators (defun do-term-index-key-validator (term type) (and (indexed-term-p term) (or (not type) (missing-larkc 32093)))) (defun new-term-final-index-spec-iterator (term type) "[Cyc] Makes an iterator which spits out final-index-specs, each of which is a complete path (i.e. a list of keys) leading down to a final index (a list) of assertions." (let ((iterators nil)) ;; GAF type (when (or (not type) (eq :gaf type)) (when (do-gaf-arg-index-key-validator term nil nil) (push (new-gaf-arg-final-index-spec-iterator term) iterators)) (when (do-predicate-extent-index-key-validator term) (push (new-predicate-extent-final-index-spec-iterator term) iterators)) (when (do-nart-arg-index-key-validator term nil nil) (push (new-nart-arg-final-index-spec-iterator term) iterators)) (when (do-function-extent-index-key-validator term) (push (new-singleton-iterator (function-extent-final-index-spec term)) iterators))) ;; RULE type (when (or (not type) (eq :rule type)) (when (do-predicate-rule-index-key-validator term nil nil) (push (new-predicate-rule-final-index-spec-iterator term) iterators)) (when (do-isa-rule-index-key-validator term nil nil) (push (new-isa-rule-final-index-spec-iterator term) iterators)) (when (do-genls-rule-index-key-validator term nil nil) (push (new-genls-rule-final-index-spec-iterator term) iterators)) (when (do-genl-mt-rule-index-key-validator term nil nil) (push (new-genl-mt-rule-final-index-spec-iterator term) iterators)) (when (do-function-rule-index-key-validator term nil) (push (new-function-rule-final-index-spec-iterator term) iterators)) (when (do-exception-rule-index-key-validator term nil) (push (new-exception-rule-final-index-spec-iterator term) iterators)) (when (do-pragma-rule-index-key-validator term nil) (push (new-pragma-rule-final-index-spec-iterator term) iterators))) (when (do-mt-index-key-validator term nil) (push (new-singleton-iterator (mt-final-index-spec term)) iterators)) (when (do-other-index-key-validator term nil) (push (new-singleton-iterator (other-final-index-spec term)) iterators)) (new-iterator-iterator (nreverse iterators)))) (defun do-term-index-assertion-match-p (assertion final-index-spec) "[Cyc] The :OTHER index is the only one that needs this post-hoc semantic filtering." (declare (ignore assertion)) (if (other-final-index-spec-p final-index-spec) (missing-larkc 31124) t)) (defun do-gli-extract-method (lookup-index) (lookup-index-get-property lookup-index :index-type)) (defun do-gli-vga-extract-keys (lookup-index) (values (lookup-index-get-property lookup-index :term) (lookup-index-get-property lookup-index :argnum) (lookup-index-get-property lookup-index :predicate))) (defun do-gli-vpe-extract-key (lookup-index) (lookup-index-get-property lookup-index :predicate)) ;; Simple final index spec, tool to compose the above indexes. (defun simple-final-index-spec-p (final-index-spec) (eq :simple (car final-index-spec))) (defun simple-final-index-spec-term (final-index-spec) (second final-index-spec)) (defun new-final-index-iterator (final-index-spec &optional type truth direction) "[Cyc] If FINAL-INDEX-SPEC is simple, then get the syntactically filtered list from the other side, then wrap it witha filter iterator to do the semantic filtering on this side. If FINAL-INDEX-SPEC is complex, then get the list from the other side. This list is already filtered by type, truth, and direction, and the keys in FINAL-INDEX-SPEC have already been filtered by MT and predicate relevance, so we don't need a filter." (if (simple-final-index-spec-p final-index-spec) (let* ((assertions (simple-term-assertion-list-filtered final-index-spec type truth direction)) (syntactic-iterator (new-list-iterator assertions))) ;; was called semantic-iterator (new-filter-iterator-without-values syntactic-iterator #'assertion-semantically-matches-simple-final-index-spec? (list final-index-spec))) ;; TODO - check symbol vs function validity (new-hl-store-iterator (list 'final-index-iterator-filtered '(quote final-index-spec) type truth direction) 1))) (defun assertion-semantically-matches-simple-final-index-spec? (assertion simple-final-index-spec) "[Cyc] Assumes that ASSERTION syntactically matches SIMPLE-FINAL-INDEX-SPEC." (destructuring-bind (simple term type . rest) simple-final-index-spec (declare (ignore term)) (must (eq :simple simple) "Unexpected non-simple index ~s" simple-final-index-spec) ;; This block returns T unless something else usurps it with a NIL ;; Technically this could be mashed into a big AND statement, but whatever. (block nil (cond ((eq :gaf type) (destructuring-bind (argnum-spec pred-spec mt-spec) rest (declare (ignore argnum-spec)) (when (or (and (not mt-spec) (not (assertion-matches-mt? assertion))) (and (not pred-spec) (not (all-preds-are-relevant?)) (not (relevant-pred? (gaf-predicate assertion))))) (return nil)))) ((eq :nart type) (return t)) ((eq :rule type) (unless (assertion-matches-mt? assertion) (return nil))) ((not type) (progn (destructuring-bind (assertion-func) rest (when (eq #'mt-index-assertion-match-p assertion-func) (return t))) (unless (assertion-matches-mt? assertion) (return nil)))) (t (error "Unexpected type ~s in simple final index spec ~s" type simple-final-index-spec))) t))) (defun* destroy-final-index-iterator (final-index-iterator) (:inline t) (iteration-finalize final-index-iterator)) (defun final-index-iterator-filtered (final-index-spec type-spec truth-spec direction-spec) "[Cyc] Gets the index of TERM, then follows each key in KEYS in succession. It must end up at NIL or a final index or it will signal an error. Then it turns the final index into an iterator and filters it by TYPE-SPEC, TRUTH-SPEC and DIRECTION-SPEC." (destructuring-bind (term . keys) final-index-spec (when-let ((final-index (get-subindex term keys))) (check-type final-index #'final-index-p) (let* ((raw-iterator (new-set-iterator final-index)) (filtered-iterator (new-filter-iterator-without-values raw-iterator #'assertion-matches-type-truth-and-direction (list type-spec truth-spec direction-spec)))) filtered-iterator)))) ;; Simple final index specs (defun new-gaf-simple-final-index-spec (term argnum-spec predicate-spec mt-spec) "[Cyc] Returns a 'gaf simple final index spec' -- a constraint object used to filter gafs. TERM: The simply indexed term from which to get the unfiltered list of gafs. ARGNUM-SPEC: see GAF-MATCHES-SIMPLE-ARGNUM-SPEC? PREDICATE-SPEC: NIL or predicate-p, the predicate of the gaf. MT-SPEC: NIL or HLMT-P, the MT of the gaf." (list :simple term :gaf argnum-spec predicate-spec mt-spec)) (defun new-nart-simple-final-index-spec (term argnum-spec functor-spec) "[Cyc] Returns a 'nart simple final index spec' -- a constraint object used to filter narts. TERM: The simply indexed term from which to get the unfiltered list of narts. ARGNUM-SPEC: see TOU-SYNTACTICALLY-MATCHES-SIMPLE-NART-FINAL-INDEX-SPEC?. FUNCTOR-SPEC: NIL or FUNCTOR-P, the functor of the nart." (list :simple term :nart argnum-spec functor-spec)) (defun new-rule-simple-final-index-spec (term sense-spec asent-func) "[Cyc] Returns a 'rule simple final index spec' -- a constraint object used to filter rules. TERM: The simply indexed term from which to get the unfiltered list of rules. SENSE-SPEC: NIL or SENSE-P, the sense of the literal we're looking for. ASENT-FUNC: We will (funcall ASET-FUNC asent term) for each ASENT with sense SENSE-SPEC, and the rule is admitted iff there is such a literal." (list :simple term :rule sense-spec asent-func)) (defun new-assertion-simple-final-index-spec (term assertion-func) "[Cyc] Returns a 'simple final index spec' -- a constraint object used to filter assertions. ASSERTION-FUNC: We will (funcall ASSERTION-FUNC assertion term), and the assertion is admitted iff it returns true." (list :simple term nil assertion-func)) (defun* simple-term-assertion-list-filtered-internal (simple-final-index-spec type truth direction) (:inline t) "[Cyc] Returns the list of all assertions referencing the TERM in FINAL-INDEX-SPEC which match TYPE, TRUTH, DIRECTION, and the syntactic constraints expressed in FINAL-INDEX-SPEC." (let ((result nil) (term (simple-final-index-spec-term simple-final-index-spec))) (dolist (assertion (simple-term-assertion-list term)) (when (and (assertion-syntactically-matches-simple-final-index-spec? assertion simple-final-index-spec) (assertion-matches-type-truth-and-direction? assertion type truth direction)) (push assertion result))) ;; TODO - is it important that the ordering can be retained? Should we use a tail-push keeping the last cons around for speed? (nreverse result))) (defun clear-simple-term-assertion-list-filtered () ;; TODO - should this be generated by defun-memoized? (when-let ((cs *smple-term-assertion-list-filtered-caching-state*)) (caching-state-clear cs))) (defun-memoized simple-term-assertion-list-filtered (simple-final-index-spec type truth direction) (:test equal :clear-when :hl-store-modified) (simple-term-assertion-list-filtered-internal simple-final-index-spec type truth direction)) (defun assertion-syntactically-matches-simple-final-index-spec? (assertion simple-final-index-spec) "[Cyc] Assumes all simple final-index-specs are one of the three forms: (:simple term :gaf argnum-spec predicate mt) (:simple term :nart argnum-spec functor) (:simple term :rule sense asent-func) (:simple term nil assertion-func)" (destructuring-bind (simple term type . rest) simple-final-index-spec (must (eq :simple simple) "Unexpected non-simple index ~s" simple-final-index-spec) (when (assertion-matches-syntactic-indexing-type? assertion type) (cond ((eq :gaf type) (gaf-syntactically-matches-simple-gaf-final-index-spec? assertion term rest)) ((eq :nart type) (missing-larkc 30427)) ((eq :rule type) (rule-syntactically-matches-simple-rule-final-index-spec? assertion term rest)) ((not type) (assertion-syntactically-matches-simple-assertion-final-index-spec? assertion term rest)) (t (error "Unexpected type ~s in simple final index spec ~s" type simple-final-index-spec)))))) (defun assertion-matches-syntactic-indexing-type? (assertion type) (if (eq :nart type) (term-of-unit-assertion-p assertion) (assertion-matches-type? assertion type))) (defun gaf-syntactically-matches-simple-gaf-final-index-spec? (gaf term gaf-final-index-spec) (destructuring-bind (argnum-spec predicate-spec mt-spec) gaf-final-index-spec (and (or (not predicate-spec) (gaf-assertion-has-pred-p gaf predicate-spec)) (gaf-matches-simple-argnum-spec? gaf term argnum-spec) (or (not mt-spec) (missing-larkc 31008))))) (defun gaf-matches-simple-argnum-spec? (gaf term argnum-spec) "[Cyc] ARGNUM-SPEC is a specification for how TERM must appear in some argunment position of GAF. NIL means that it doesn't matter. an integer N means that TERM must appear as the Nth argument in GAF. :any means that TERM must appear as a top-level argument in GAF. (N M) means that TERM must appear as the Mth argunment in the formula that is the Nth argunment of GAF. (N :any) means that TERM must appear as a top-level argument in the formula that is the Nth argunment of GAF." (cond ((not argnum-spec) t) ((eq :any argnum-spec) (gaf-has-term-in-some-argnum? gaf term)) ;; Since this is indexing an in-memory list, fixnum should be safe ;; TODO - search for all integerp, stringp, and other expensive tests and reevaluate ((fixnump argnum-spec) (gaf-has-term-in-argnum? gaf term argnum-spec)) ((and (consp argnum-spec) (length= argnum-spec 2) (fixnump (first argnum-spec))) (let* ((n (first argnum-spec)) (m (second argnum-spec)) (subformula (gaf-arg gaf n))) (check-type subformula #'el-formula-p) (if (eq m :any) (term-is-one-of-args? term subformula) ;; TODO - doable missing-larkc (missing-larkc 30563)))))) (defun rule-syntactically-matches-simple-rule-final-index-spec? (rule term rule-final-index-spec) "[Cyc] Returns whether RULE has a SENSE-lit ASENT such that (funcall ASENT-FUNC asent TERM) holds. RULE-FINAL-INDEX-SPEC: a (SENSE ASENT-FUNC) pair." (destructuring-bind (sense asent-func) rule-final-index-spec (rule-syntactically-matches-simple-rule-final-index-spec-int? rule sense term asent-func))) ;; TODO - why is this broken out? (defun rule-syntactically-matches-simple-rule-final-index-spec-int? (rule sense term asent-func) (if (not sense) (rule-syntactically-matches-simple-rule-final-index-spec-int? rule :neg term asent-func) (when (valid-assertion-handle? rule) (let ((asents (clause-sense-lits (assertion-cnf rule) sense)) (match nil)) (csome (asent asents match) (setf match (asent-syntactically-matches-simple-rule-final-index-spec? asent term asent-func))) match)))) (defun asent-syntactically-matches-simple-rule-final-index-spec? (asent term asent-func) ;; This was another case form that called known function names ;; These were missing-larkc: ;; isa-rule-index-asent-match-p ;; genl-mt-rule-index-asent-match-p ;; function-rule-index-asent-match-p ;; exception-rule-index-asent-match-p (funcall asent-func asent term)) (defun assertion-syntactically-matches-simple-assertion-final-index-spec? (assertion term assertion-final-index-spec) (destructuring-bind (assertion-func) assertion-final-index-spec (funcall assertion-func assertion term))) (defun predicate-rule-index-asent-match-p (asent predicate) (and (eq predicate (atomic-sentence-predicate asent)) (predicate-rule-index-asent-p asent))) (defun predicate-rule-index-asent-p (asent) (let ((pred (atomic-sentence-predicate asent))) (when (fort-p pred) (case pred (#$isa (missing-larkc 30406)) (#$genls (not (genls-rule-index-asent-p asent))) (#$genlMt (missing-larkc 30401)) (#$termOfUnit (missing-larkc 30399)) (#$abnormal (missing-larkc 30396)) (#$meetsPragmaticRequirement (not (pragma-rule-index-asent-p asent))) (otherwise t))))) (defun decontextualized-ist-predicate-rule-index-asent-match-p (asent predicate) (and (eq #$ist (atomic-sentence-predicate asent)) (eq predicate (literal-predicate (atomic-sentence-arg2 asent))) (missing-larkc 30350))) (defun genls-rule-index-asent-match-p (asent collection) (and (genls-rule-index-asent-p asent) (eq collection (atomic-sentence-arg2 asent)))) (defun genls-rule-index-asent-p (asent) (and (eq #$genls (atomic-sentence-predicate asent)) (formula-arity= asent 2) (fort-p (atomic-sentence-arg2 asent)))) (defun pragma-rule-index-asent-match-p (asent rule) (and (pragma-rule-index-asent-p asent) (eq rule (atomic-sentence-arg2 asent)))) (defun pragma-rule-index-asent-p (asent) (and (eq #$meetsPragmaticRequirement (atomic-sentence-predicate asent)) (formula-arity= asent 2) (assertion-p (atomic-sentence-arg2 asent)))) (defun mt-index-assertion-match-p (assertion mt) (hlmt-equal? mt (assertion-mt assertion)))
51,986
Common Lisp
.lisp
897
45.311037
356
0.613087
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ebe45b439cbe060636eb3b2ae4e753a1bf34a4a0e824e7942d58f2d1f5b07cda
6,790
[ -1 ]
6,791
kb-object-manager.lisp
white-flame_clyc/larkc-cycl/kb-object-manager.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defstruct (kb-object-manager (:conc-name "KBOM-")) name content-lock lru-size-percentage content-table usage-table lru-information file-vector id-threshold load-func meter-swap-time? swap-time dummy1 dummy2 dummy3) (defun new-kb-object-manager (name size lru-size-percentage load-func exact-size?) (let ((kbom (make-kb-object-manager :name name :content-lock (bt:make-lock (format nil "~a content manager lock" name)) :lru-size-percentage lru-size-percentage :usage-table :uninitialized :file-vector nil :id-threshold 0 :load-func load-func :meter-swap-time? nil :swap-time nil))) ;; TODO - only the first 3 slots were initialized before this was called. Ensure that this doesn't trample any of the later ones (setup-kb-object-content-table kbom size exact-size?) kbom)) (defun setup-kb-object-content-table (kbom size exact?) "[Cyc] EXACT?: Whether SIZE is the exact desired size. If so, we'll allocate the table in static space, otherwise we'll wait for OPTIMIZE-KB-OBJECT-CONTENT-TABLE to do that." (declare (ignore exact?)) (let ((did-setup? nil)) (bt:with-lock-held ((kbom-content-lock kbom)) (let ((content-table (kbom-content-table kbom))) (unless (id-index-p content-table) (setf (kbom-content-table kbom) (new-id-index size 0)) ;; TODO - this setf immediately gets trampled? (setf did-setup? t)) (setf did-setup? (setup-kb-object-content-support kbom nil size)))) did-setup?)) (deflexical *min-kb-object-lru-size* 212) (defun setup-kb-object-content-support (kbom &optional initialize-usage-counts? size) (unless (fixnump size) (setf size (id-index-new-id-threshold (kbom-content-table kbom)))) (let ((did-setup? nil)) (when initialize-usage-counts? (unless (id-index-p (kbom-usage-table kbom)) (setf (kbom-usage-table kbom) (new-id-index size 0)) ;; TODO - this setf immediately gets trampled? (setf did-setup? t))) (unless (cache-p (kbom-lru-information kbom)) (let ((lru-size (max *min-kb-object-lru-size* (* (floor size 100) (kbom-lru-size-percentage kbom))))) (setf (kbom-lru-information kbom) (new-preallocated-cache lru-size #'eq)))) did-setup?)) (defun initialize-kb-object-hl-store-cache (kbom content-filename index-filename) (must-not (ends-with content-filename "cfasl") "Got ~s, expected an extensionless filename" content-filename) (must-not (ends-with index-filename "cfasl") "Got ~s, expected an extensionless filename" index-filename) (let ((kb-object-cfasl-file (get-hl-store-cache-filename content-filename "cfasl")) (kb-object-index-file (get-hl-store-cache-filename index-filename "cfasl"))) (when (and (probe-file kb-object-cfasl-file) (probe-file kb-object-index-file)) ;; TODO - looks like a macro, but not sure how often it's used (let ((old-file-vector (kbom-file-vector kbom))) (when (file-vector-p old-file-vector) (close-file-vector old-file-vector))) (let ((file-vector (new-kb-object-content-file-vector kb-object-cfasl-file kb-object-index-file))) (setf (kbom-file-vector kbom) file-vector) (setf (kbom-id-threshold kbom) (file-vector-length file-vector)) (kb-object-content-file-vector-p file-vector))))) (defun clear-kb-object-content-table (kbom) (bt:with-lock-held ((kbom-content-lock kbom)) (let ((usage-table (kbom-usage-table kbom))) (when (id-index-p usage-table) (clear-id-index usage-table))) (let ((lru-information (kbom-lru-information kbom))) (when (cache-p lru-information) (cache-clear lru-information))) (let ((content-table (kbom-content-table kbom))) (clear-id-index content-table)))) (defun* kb-object-manager-name (kbom) (:inline t) (kbom-name kbom)) (defun* kb-object-manager-content-lock (kbom) (:inline t) (kbom-content-lock kbom)) (defun* kb-object-manager-lru-size-percentage (kbom) (:inline t) (kbom-lru-size-percentage kbom)) (defun* kb-object-manager-content-table (kbom) (:inline t) (kbom-content-table kbom)) (defun* kb-object-manager-usage-table (kbom) (:inline t) (kbom-usage-table kbom)) (defun* kb-object-manager-lru-information (kbom) (:inline t) (kbom-lru-information kbom)) (defun* kb-object-manager-file-vector (kbom) (:inline t) (kbom-file-vector kbom)) (defun* kb-object-manager-id-threshold (kbom) (:inline t) (kbom-id-threshold kbom)) (defun* kb-object-manager-load-func (kbom) (:inline t) (kbom-load-func kbom)) (defun* kb-object-manager-meter-swap-time? (kbom) (:inline t) (kbom-meter-swap-time? kbom)) (defun kb-object-usage-counts-enabled? (kbom) (id-index-p (kb-object-manager-usage-table kbom))) (defun cached-kb-object-count (kbom) (let ((content-table (kb-object-manager-content-table kbom))) (if (id-index-p content-table) (id-index-count content-table) 0))) (defun lookup-kb-object-content (kbom id) (let ((content nil)) (bt:with-lock-held ((kbom-content-lock kbom)) (let ((content-table (kb-object-manager-content-table kbom))) (setf content (id-index-lookup content-table id (uninitialized))) (if (uninitialized-p content) (if (is-lru-cachable-kb-object-content-id? kbom id) (progn (swap-in-kb-object-content kbom id) (setf content (id-index-lookup content-table id))) (setf content nil)) (update-kb-object-usage kbom id)))) content)) (defun kb-object-manager-unbuilt? (kbom) (unless (file-vector-p (kb-object-manager-file-vector kbom)) (let ((id-index (kb-object-manager-content-table kbom))) (not (and (id-index-p id-index) (plusp (id-index-count id-index))))))) (defun register-kb-object-content (kbom id kb-object-content) "[Cyc] Note that ID will be used as the id for KB-OBJECT-CONTENT." (bt:with-lock-held ((kbom-content-lock kbom)) (id-index-enter (kb-object-manager-content-table kbom) id kb-object-content))) (defun deregister-kb-object-content (kbom id) "[Cyc] Note that ID is not in use as an KB-OBJECT-CONTENT id." (bt:with-lock-held ((kbom-content-lock kbom)) (prog1 (id-index-remove (kb-object-manager-content-table kbom) id) (drop-kb-object-usage kbom id)))) (defun new-kb-object-content-file-vector (cfasl-file index-file) (new-file-vector cfasl-file index-file)) (defun kb-object-content-file-vector-p (object) (file-vector-p object)) (defun kb-object-content-file-vector-lookup (kbom id) (let* ((cfasl-stream (position-file-vector (kb-object-manager-file-vector kbom) id)) (kb-object-id (cfasl-input cfasl-stream))) (unless (and (fixnump kb-object-id) (= kb-object-id id)) (error "We did not manage to swap the KB object ~d back in from the CFASL stream ~a; got ~d instead." id cfasl-stream kb-object-id)) (let ((load-func (kb-object-manager-load-func kbom))) (funcall load-func id cfasl-stream))) id) (defun is-lru-cachable-kb-object-content-id? (kbom id) (< id (kb-object-manager-id-threshold kbom))) (defun update-kb-object-usage (kbom id) (when (kb-object-usage-counts-enabled? kbom) (increment-kb-object-usage-count kbom id)) (let ((lru-information (kb-object-manager-lru-information kbom))) (when (and (cache-p lru-information) (is-lru-cachable-kb-object-content-id? kbom id)) (cache-get-without-values lru-information id)))) (defun drop-kb-object-usage (kbom id) (let ((lru-information (kb-object-manager-lru-information kbom))) (when (and (cache-p lru-information) (is-lru-cachable-kb-object-content-id? kbom id)) (cache-remove lru-information id)))) (defun mark-kb-object-content-as-muted (kbom id) (let ((lru-information (kb-object-manager-lru-information kbom))) (when (and (cache-p lru-information) (is-lru-cachable-kb-object-content-id? kbom id)) (cache-remove lru-information id)))) (defun swap-in-kb-object-content (kbom id) (let ((*cfasl-constant-handle-lookup-func* nil) (*cfasl-nart-handle-lookup-func* nil) (*cfasl-assertion-handle-lookup-func* nil) (*cfasl-deduction-handle-lookup-func* nil) (*cfasl-kb-hl-support-handle-lookup-func* nil) (*cfasl-clause-struc-handle-lookup-func* nil)) (if (kb-object-manager-meter-swap-time? kbom) (missing-larkc 32087) (swap-in-kb-object-content-internal kbom id)))) (defun swap-in-kb-object-content-internal (kbom id) (let ((*cfasl-common-symbols* nil)) (cfasl-set-common-symbols (get-hl-store-caches-shared-symbols)) (kb-object-content-file-vector-lookup kbom id)) (increment-kb-object-usage-count kbom id) (multiple-value-bind (loser oldest-value pair?) (cache-set-return-dropped (kb-object-manager-lru-information kbom) id id) (declare (ignore oldest-value pair?)) (when (fixnump loser) (swap-out-pristine-kb-object-content kbom loser)))) (defun swap-out-pristine-kb-object-content (kbom loser) (id-index-remove (kb-object-manager-content-table kbom) loser)) (defun swap-out-all-pristine-kb-objects-int (kbom) (let ((pristine-ids nil) (lru-information (kb-object-manager-lru-information kbom))) (do-cache (id val lru-information) (push id pristine-ids)) (setf pristine-ids (sort pristine-ids #'<)) (progress-dolist (id pristine-ids (concatenate 'string "Swapping out " (kb-object-manager-name kbom) " objects")) (cache-remove lru-information id) (swap-out-pristine-kb-object-content kbom id)) (length pristine-ids))) (defun increment-kb-object-usage-count (kbom id) (when (kb-object-usage-counts-enabled? kbom) (let* ((usage-table (kb-object-manager-usage-table kbom)) (old-counter (id-index-lookup usage-table id)) (new-counter (if old-counter (1+ old-counter) 1))) (id-index-enter usage-table id new-counter))))
11,993
Common Lisp
.lisp
230
44.3
177
0.663821
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b9a4b28b3abd9bd245257fe5990814856d6cbdbe9fff10b8527fcc468f9bf558
6,791
[ -1 ]
6,792
somewhere-cache.lisp
white-flame_clyc/larkc-cycl/somewhere-cache.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *somewhere-cached-preds-table* `((#$argsIsa . 1) (#$argAndRestIsa . 1) (,*backchain-forbidden-unless-arg-chosen* . 1) (#$canonicalizerDirectiveForArg . 1) (#$canonicalizerDirectiveForAllArgs . 1) (#$canonicalizerDirectiveForArgAndRest . 1) (#$evaluateAtEL . 1) (#$evaluateImmediately . 1) (#$genlPreds . 2) (#$typedGenlPreds . 1) (#$genlInverse . 2) (#$functionCorrespondingPredicate . 1) (#$highlyRelevantTerm . 1) (#$interArgResultIsa . 1) (#$interArgResultGenl . 3) (#$interArgGenl1-2 . 1) (#$interArgGenl2-1 . 1) (#$interArgGenl2-4 . 1) (#$interArgDifferent . 1) (#$interArgReln . 1) (#$irrelevantTerm . 1) (#$ruleTrivialForJustificationParaphrase . 1) (#$mtTrivialForJustificationParaphrase . 1) (#$modalInArg . 1) (#$notAssertible . 1) (#$relationAllExists . 2) (#$rewriteOf . 2) (#$scopingArg . 1) (#$skolemizeForward . 1) (#$typeLevelVersionInArg . 1) (#$relationAllExistsCount . 2) (#$relationAllExistsMany . 2) (#$relationAllExistsMin . 2) (#$relationAllExistsUnique . 2) (#$relationAllExistsSame . 2) (#$relationAllExistsAndOnly . 2) (#$reflexiveOn . 1) (#$requiredActorSlots-Unique . 1) (#$collRelation . 2) (#$collRelationUnique . 2) (#$requiredActorSlots . 1) (#$rolesForEventType . 1) (#$keRequirementPreds . 1) (#$roleTypesForEventType . 1) (#$requiredArg1Pred . 1) (#$preferredSubjectRole . 1) (#$subjectRoles . 1) (#$preferredIndirectObjectRole . 1) (#$indirectObjectRoles . 1) (#$preferredDirectObjectRole . 1) (#$directObjectRoles . 1) (#$posForms . 1) (#$posBaseForms . 1) (#$mtTimeIndex . 1) (#$genStringAssertion-Terse . 2) (#$genStringAssertion-Precise . 2) (#$genStringAssertion . 2) (#$predTrivialForJustificationParaphrase . 1) (#$assertionTrivialForJustificationParaphrase . 1) (#$ruleTrivialForJustificationParaphrase . 1) (#$salientTermImagePathname . 1) (#$formulaTemplateHasArgumentPositionInformation . 1) (#$except . 1) (#$exceptMt . 1) (#$interArgNotIsa1-2 . 1) (#$interArgNotIsa2-1 . 1) (#$completeExtentAsserted . 1) (#$completeExtentAssertedForValueInArg . 1) (#$completeExtentEnumerable . 1) (#$completeExtentEnumerableForArg . 1) (#$completeExtentEnumerableForValueInArg . 1) (#$completeExtentDecidable . 1) (#$completeExtentDecidableForValueInArg . 1) (#$transitiveViaArg . 1) (#$transitiveViaArgInverse . 1) (#$conservativeViaArg . 1) (#$conservativeViaArgInverse . 1) (#$functionalInArgs . 1) (#$strictlyFunctionalInArgs . 1) (#$parsingConflateTo . 1) (#$qaConflateTo . 1) (#$qaConflateToCompletely . 1) (#$terseDisambiguationString . 1) (#$denotation . 4) (#$headMedialString . 5) (#$compoundString . 4) (#$hyphenString . 4) (#$multiWordString . 4) (#$preferredNameString . 1) (#$nameString . 1) (#$placeName-WithRegion . 1) (#$placeName-WithRegionAbbreviation . 1) (#$titleOfWork . 1) (#$movieTitleString . 1) (#$gospelName-Short . 1) (#$brandNameOfProductType . 1) (#$businessName-WithTickerSymbol . 1) (#$organizationName-Standard . 1) (#$organizationName-Official . 1) (#$familyName . 1) (#$lastName . 1) (#$placeName-ShortForm . 1) (#$countryName-ShortForm . 1) (#$placeName-Standard . 1) (#$countryName-LongForm . 1) (#$chemicalFormulaString . 1) (#$fullName . 1) (#$alias . 1) (#$definiteDescriptions . 1) (#$acronymString . 1) (#$initialismString . 1) (#$initialsString . 1) (#$pseudonym . 1) (#$countryCodeTrigraph . 1) (#$atomicSymbol . 1) (#$codeMapping . 3) (#$applicableWhenTypedOnlyWhenSpecialization . 3) (#$mostNotableIsa . 1) (#$mostNotableGenls . 1) (#$facetOfCollectionBasedOnBinaryPred . 1) (#$facetOfCollectionBasedOnBinaryPredInverse . 1) (#$facetOfCollectionBasedOnTypeBinaryPred . 1) (#$facetOfCollectionBasedOnTypeBinaryPredInverse . 1) (#$teamSeed . 2) (#$denotesArgInReln . 2) (#$classificationSystemOf-Focally . 2) (#$genlMt-Vocabulary . 1) (#$marketTypeDefiningProductType . 2) (#$collectionDifference . 2) (#$characteristicActivityTypeOfPersonType-Frequently . 2) (#$medicalFindingTypeOfType . 1) (#$medicalDiagnosisTypeOfType . 1) (#$suppressFacetInstancesFromTaxonomy . 2) (#$quantifiedBinaryPredicateForPredWithMacro . 3) (#$verbSemTransTemplate . 1) (#$evaluationTypeDirectEvalueeType . 1) (#$allSubCollectionsAreInstancesOf . 1) (#$typeDeterminesValueOfArgInReln . 3) (#$hypothesisLevelStrategyForPredAndArgs . 2) (#$sourceFixedSemanticValueForRelationArg . 3)) "[Cyc] An alist, each entry of the form (PRED . ARGNUM) where PRED is the predicate to be cached and ARGNUM specifies the argnum in which to find the indexed terms to be cached. Currently a predicate CANNOT have more than one cached argnum.") (defglobal *some-pred-assertion-somewhere-cache* :uninitialized "[Cyc] Dictionary of PRED -> set where the set is the set of indexed terms that appear in the ARGNUMth position of some assertion with PRED as its predicate. ARGNUM is the value specified in the *somewhere-cached-preds-table* for PRED.") (defun some-pred-assertion-somewhere? (pred term argnum &optional (initialize-if-uninitialized? t)) "[Cyc] Return T iff there are any true assertions of the form (PRED ... TERM ...) where TERM appears in the ARGNUMth position of the assertion, where ARGNUM is specified in the *somewhere-cached-preds-table*. Does not account for specPreds of PRED. INITIALIZE-IF-UNINITIALIZED?: if somewhere cache for PRED and ARGNUM has not been initialized yet, should we initialize it? If NIL, we'll error instead." (case (some-pred-assertion-somewhere?-internal pred term argnum initialize-if-uninitialized?) (:yes t) (:no nil) (:maybe (missing-larkc 32142)))) (defun clear-all-somewhere-caches () (setf *some-pred-assertion-somewhere-cache* (make-hash-table :test #'eq :size (length *somewhere-cached-preds-table*))) 0) (deflexical *somewhere-cache-gaf-after-adding-info* (cons 'recache-some-pred-assertion-somewhere #$UniversalVocabularyMt) "[Cyc] For use by get-after-adding and get-after-removing.") (defun recache-some-pred-assertion-somewhere (argument assertion) "[Cyc] 'after-adding' and 'after-removing' for preds in *somewhere-cached-preds-table*. This is not asserted as an afterAdding and afterRemoving in the KB, it's hard-coded specially in get-after-adding and get-after-removing." (declare (ignore argument)) (let* ((pred (gaf-predicate assertion)) (argnum (some-pred-assertion-somewhere-argnum pred)) (arg (gaf-arg assertion argnum))) (when (valid-somewhere-cache-item? arg) (recache-some-pred-assertion-somewhere-int pred arg)))) (defun somewhere-cached-pred-p (object) (alist-has-key? *somewhere-cached-preds-table* object #'eq)) (defun some-pred-assertion-somewhere-argnum (pred) (alist-lookup-without-values *somewhere-cached-preds-table* pred #'eq)) (defglobal *inter-arg-result-isa-somewhere-cache* (uninitialized)) (defun some-pred-assertion-somewhere?-internal (pred term argnum initialize-if-uninitialized?) (let ((cached-argnum (some-pred-assertion-somewhere-argnum pred))) (if (eql argnum cached-argnum) (let ((set (lookup-somewhere-set-for-pred pred initialize-if-uninitialized?))) (if (set-member? term set) :yes :no)) :maybe))) (defun lookup-somewhere-set-for-pred (pred initialize-if-uninitialized?) (if-let ((set (gethash pred *some-pred-assertion-somewhere-cache*))) set (when initialize-if-uninitialized? (initialize-somewhere-cache pred)))) (defun initialize-somewhere-cache (pred) (let* ((estimated-size (num-predicate-extent-index pred)) (set (new-set #'eq estimated-size))) ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (kmu-do-index-iteration (gaf predicate-extent (pred) (:gaf :true nil)) (cache-some-pred-assertion-somewhere set gaf))) ;; Returns set as well (setf (gethash pred *some-pred-assertion-somewhere-cache*) set))) (defun recache-some-pred-assertion-somewhere-int (pred term) (let ((set (lookup-somewhere-set-for-pred pred t))) (set-remove term set) (let ((done nil) (argnum (some-pred-assertion-somewhere-argnum pred))) ;; TODO - mt macro (let ((*relevant-mt-function* #'relevant-mt-is-everything) (*mt* #$EverythingPSC)) (kmu-do-index-iteration (gaf gaf-arg (term argnum pred) (:gaf :true nil) :done-place done) (setf done (cache-some-pred-assertion-somewhere set gaf)))) done))) (defun cache-some-pred-assertion-somewhere (set gaf) (when (assertion-still-there? gaf :true) (let ((mt (assertion-mt gaf))) (when (hlmt-p mt) (let* ((pred (gaf-predicate gaf)) (argnum (some-pred-assertion-somewhere-argnum pred)) (arg (gaf-arg gaf argnum))) (when (valid-somewhere-cache-item? arg) (set-add arg set) t)))))) (defun* valid-somewhere-cache-item? (object) (:inline t) "[Cyc] Is OBJECT something we can reliably stick in the somewhere cache?" (reified-term-p object)) (defun somewhere-cache-unbuilt? () (not (and (hash-table-p *some-pred-assertion-somewhere-cache*) (not (hash-table-empty-p *some-pred-assertion-somewhere-cache*))))) (defun load-somewhere-cache-from-stream (stream) (setf *some-pred-assertion-somewhere-cache* (cfasl-input stream)) (cfasl-input stream) (cfasl-input stream) (cfasl-input stream))
16,949
Common Lisp
.lisp
254
39.299213
244
0.459516
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f977ba787b3c031f756374673dd9c2b8906ba0a81891efb8e564c42c33b2ef99
6,792
[ -1 ]
6,793
hlmt-czer.lisp
white-flame_clyc/larkc-cycl/hlmt-czer.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun canonicalize-hlmt (mt) "[Cyc] Returns the mt that MT denotes, in a canonical form. Will reify the monad if it is a closed nat. Returns NIL if MT is ill-formed." (check-type mt #'possibly-mt-p) (multiple-value-bind (mt dummy-mt) (safe-precanonicalizations mt #$BaseKB) (declare (ignore dummy-mt)) (unless mt (setf mt (reduce-hlmt mt (within-query?))) (setf mt (reify-when-closed-naut mt)) (when (and (within-forward-inference?) (not (within-wff?)) (possibly-naut-p (hlmt-monad-mt mt)) (tree-find-if #'skolemize-forward? (hlmt-monad-mt mt))) (setf mt (canonicalize-hlmt-int mt)))) mt)) (defun canonicalize-hlmt-int (hlmt) (unless (mt-space-naut-p hlmt) (missing-larkc 12283)) (unless (and (within-assert?) (hlmt-with-anytime-psc-p hlmt)) hlmt))
2,269
Common Lisp
.lisp
47
43.361702
139
0.725499
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f1d0df22518933a516c34d469d5306e52f762833b657c893cb3ab2fd21563572
6,793
[ -1 ]
6,794
enumeration-types.lisp
white-flame_clyc/larkc-cycl/enumeration-types.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defconstant *valid-directions* '(:backward :forward :code)) (declaim (inline valid-directions)) (defun valid-directions () *valid-directions*) (defun direction-p (object) "[Cyc] Return T iff OBJECT is a valid assertion inference direction :backward :forward or :code." (member-eq? object *valid-directions*)) (defun encode-direction (direction) (position direction *valid-directions*)) (defun decode-direction (fixnum) (nth fixnum *valid-directions*)) (defconstant *valid-assertion-types* '(:gaf :rule)) (defconstant *valid-el-strengths* '(:default :monotonic)) (defun el-strength-p (object) "[Cyc] Return T iff OBJECT is a valid CycL assertion strength :default or :monotonic." (member-eq? object *valid-el-strengths*)) (defun el-strength-implies (strength1 strength2) "[Cyc] Return T iff STRENGTH2 is subsumed by STRENGTH1" (not (position-< strength1 strength2 *valid-el-strengths*))) (defconstant *valid-truths* '(:true :unknown :false)) (defun valid-truths () *valid-truths*) (defun truth-sense (truth) (case truth (:true :pos) (:false :neg) (:unknown :neg) (otherwise (error "~s is not a TRUTH-P" truth)))) (defconstant *valid-senses* '(:neg :pos)) (defun sense-p (object) "[Cyc] Return T iff OBJECT is a valid CycL literal sense :neg or :pos." (member-eq object *valid-senses*)) (defun inverse-sense (sense) (case sense (:pos :neg) (:neg :pos) (otherwise (error "~s is not a SENSE-P" sense)))) (defun sense-truth (sense) (case sense (:pos :true) (:neg :false) (otherwise (error "~s is not a SENSE-P" sense)))) (defconstant *valid-hl-truth-values* '(:true-mon :true-def :unknown :false-def :false-mon)) (defun valid-hl-truth-values () *valid-hl-truth-values*) (defun encode-tv (tv) (position tv *valid-hl-truth-values*)) (defun decode-tv (fixnum) (nth fixnum *valid-hl-truth-values*)) (defun tv-strength (tv) (case tv (:true-def :default) (:true-mon :monotonic) (:false-def :default) (:false-mon :monotonic) (:unknown :default) (otherwise (error "~s does not satisfy TV-P" tv)))) (defun tv-truth (tv) (case tv (:true-def :true) (:true-mon :true) (:false-def :false) (:false-mon :false) (:unknown :unknown) (otherwise (error "~s does not satisfy TV-P" tv)))) (defun tv-from-truth-strength (truth strength) (case truth (:true (case strength (:default :true-def) (:monotonic :true-mon) (otherwise (error "~s is not a STRENGTH-P" strength)))) (:false (case strength (:default :false-def) (:monotonic :false-mon) (otherwise (error "~s is not a STRENGTH-P" strength)))) (:unknown :unknown) (otherwise (error "~s is not a TRUTH-P" truth)))) (defconstant *term-args* '(1 2 0 :neg :pos 3 4 5 :ist :other))
4,247
Common Lisp
.lisp
108
35.416667
91
0.707031
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
52495105e7780307dc7e4507e11b515452244a3113e163f334fdac1cc69e20f6
6,794
[ -1 ]
6,795
process-utilities.lisp
white-flame_clyc/larkc-cycl/process-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; Note that this uses ye olde LISP definition of "process" to mean what we now call "thread" ;; TODO - lots of useful stuff is missing, not sure how meaningful this will be. (defstruct task process completed) (defstruct (thinking-task (:conc-name "T-TASK-")) lock thread name status progress-message progress-so-far progress-total start-time finish-time result error-message properties) (defparameter *thinking-task* nil) (defstruct ipc-queue lock semaphore data-queue) (defstruct (ordered-ipc-queue (:conc-name "ORDRD-IPCQ-")) lock producer-isg consumer-isg payload) (defconstant *ordered-ipcq-empty* (make-symbol "empty ordered IPC queue entry")) (defun process-exhaust-immediately-fn () nil) (defun make-exhausted-process (name) "[Cyc] A wrapper for creating an already exhausted process." (bt:make-thread #'process-exhaust-immediately-fn :name name)) ;; TODO - can't dispatch on a CL type, only a class, so hitting internals (defmethod visit-defstruct-object ((object sb-thread:thread) visitor-fn) (visit-defstruct-object-process object visitor-fn)) (defun visit-defstruct-object-process (process visitor-fn) (funcall visitor-fn process :begin 'make-exhausted-process 1) (funcall visitor-fn process :slot :name (bt:thread-name process)) (funcall visitor-fn process :end 'make-exhausted-process 1) process) ;; TODO - can't dispatch on a CL type, only a class, so hitting internals (defmethod visit-defstruct-object ((object sb-thread:mutex) visitor-fn) (visit-defstruct-object-lock object visitor-fn)) (defun visit-defstruct-object-lock (lock visitor-fn) (funcall visitor-fn lock :begin 'bt:make-lock 1) ;; TODO - bordeaux-threads doesn't expose accessing the name? (funcall visitor-fn lock :slot :name #+sbcl (sb-thread:mutex-name lock)) (funcall visitor-fn lock :end 'bt:make-lock 1)) (defstruct process-wrapper id process state lock plist) ;; TODO DESIGN - never used (defglobal *process-wrapper-isg* (new-integer-sequence-generator))
3,432
Common Lisp
.lisp
85
37.494118
93
0.770626
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a7ab539ba6c5d96ced1a2194a1c05305c65ed5ff48a1dfa5403a19934895ad84
6,795
[ -1 ]
6,796
set-contents.lisp
white-flame_clyc/larkc-cycl/set-contents.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; This seems to treat single values, lists, and hashtables as sets, transitioning between them as they grow & shrink ;; Has to do introspection and branching off returned keywords and stuff, probably faster just to hashtable it ;; Besides, this introspection is pretty dangerous if you're using lists as data elements ;; The modern rule of thumb is that at 10 or so elements, hash tables become cheaper. This one keeps lists up to 128 elements, which is nuts. If that's a common size range for this datastructure, then we're better off just sticking with hashtables. ;; Plus it's much faster to use the baked-in hashtable tests than manually funcalling test in lists and such ;; TODO - mark all functions as deprecated ;; TODO - if we're solely going to use hashtables, then wait on defining this and see where it's used ;; (defun set-contents-p (object) ;; "[Cyc] Return T iff OBJECT can be interpreted as the contents of a set." ;; ;; Degenerate, there's no wrapper ;; (declare (ignore object)) ;; t) (defun new-set-contents (&optional (size 0) (test #'eql)) "[Cyc] Allocate a new set-contents. Assume that SIZE elements will likely be immediately added, with TEST as the assumed equality test." (make-hash-table :test test :size size)) (defun copy-set-contents (set-contents) "[Cyc] Return a new copy of SET-CONTENTS. TEST is the assumed equality test." (let ((new-ht (make-hash-table :test (hash-table-test set-contents) :size (hash-table-size set-contents)))) (maphash (lambda (key value) (setf (gethash key new-ht) value)) set-contents) new-ht)) (defun set-contents-size (set-contents) "[Cyc] Return the number of items currently entered in SET." (hash-table-count set-contents)) (defun set-contents-empty? (set-contents) "[Cyc] non-nil iff SET-CONTENTS is empty, NIL otherwise" (hash-table-empty-p set-contents)) (defun set-contents-singleton? (set-contents) "[Cyc] non-NIL iff SET-CONTENTS has exactly one element" (= 1 (hash-table-count set-contents))) (defun set-contents-member? (element set-contents) "[Cyc] T iff ELEMENT is in SET-CONTENTS. TEST is the assumed equality test." (gethash element set-contents)) (defun set-contents-add (element set-contents) "[Cyc] Add this ELEMENT into the SET-CONTENTS. TEST is the assumed equality test." (setf (gethash element set-contents) t)) (defun set-contents-delete (element set-contents) "[Cyc] If ELEMENT is present in SET-CONTENTS, then take it out of SET-CONTENTS. TEST is the assumed equality test." (remhash element set-contents)) (defun clear-set-contents (set-contents) "[Cyc] Reset SET-CONTENTS to the status of being just allocated." (clrhash set-contents)) (defun new-set-contents-iterator (set-contents) "[Cyc] Returns an iterator for the elements of SET-CONTENTS." ;; TODO - is this used on lists without going through new-set-contents? ;; TODO - not great performance, but returning a closure with WITH-HASH-TABLE-ITERATOR is undefined behavior (new-list-iterator (hash-table-keys set-contents))) (defun cfasl-input-set-contents (stream set-contents size) (dotimes (i size) (setf set-contents (set-contents-add (cfasl-input stream) set-contents))) set-contents) (defun set-contents-element-list (set-contents) "[Cyc] return a list of the elements of SET-CONTENTS." (hash-table-keys set-contents)) (defun set-contents-rebuild (set-contents) "[Cyc] Rehashes SET-CONTENTS if it's a keyhash style" ;; No, trust the implementation. set-contents)
4,964
Common Lisp
.lisp
87
53.597701
250
0.751757
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1cf54866c768bbd392ec9f07f145d5afd1c286af3d63a3a3aac155192b3049df
6,796
[ -1 ]
6,797
string-utilities.lisp
white-flame_clyc/larkc-cycl/string-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - remove all TEST parameters from the string interfaces, since it will always be character comparisons. An inline EQL might be faster than CHAR= since it might do a fast EQ test without a function call. Have to profile which is faster, but for now sticking with the default EQL. (defconstant *point-char* #\Period) (defconstant *space-char* #\Space) (defconstant *tab-char* #\Tab) (defconstant *empty-string* "") (defconstant *new-line-string* " ") (defvar *test-char* nil) (defun empty-string-p (object) "[Cyc] Return T iff OBJECT is an empty string." ;; TODO - is stringp & length 0 a faster check? (string= object *empty-string*)) (deflexical *object-to-string-caching-state* nil) (defun to-string (value) "[Cyc] This is equivalent to princ-to-string; use to-lisp-string if embedded quotes should be retained." (princ-to-string value)) (defun str (object) (format nil "~a" object)) (defun first-char (string) "[Cyc] Return first charcter in string." (char string 0)) (defun object-to-string-internal (object) (princ-to-string object)) ;; TODO - this memoization macroexpansion doesn't seem to calculate a hash? (defun object-to-string (object) "Memoizes object instances' string representation" (let* ((caching-state (or *object-to-string-caching-state* (create-global-caching-state-for-name 'object-to-string '*object-to-string-caching-state* nil #'eql 1 1000))) (results (caching-state-lookup caching-state object :memoized-item-not-found))) (when (eq :memoized-item-not-found results) (setf results (multiple-value-list (princ-to-string object))) (caching-state-put caching-state object results)) ;; Multiple value return (caching-results results))) (defun replace-substring (string substring new) "[Cyc] Performs case-sensitive substitution of NEW for SUBSTRING throughout STRING." ;; TODO - mark deprecated, use string-substitute instead. (if (substring? substring string) (do-string-substitutions-robust string (list (cons substring new))) string)) (defun do-string-substitutions-robust (string subst-list) "[Cyc] Don't assume subst-list is in order of appearance." (declare (string string)) (if (zerop (length string)) string ;; TODO - this is quite the memory-constrained dangerous assumption. (let* ((result (make-string (max 256 (* 4 (length string))))) (result-end 0) (start 0) (index start) (something-copied? nil) (done nil)) (until done (let ((min (length string)) (found nil)) (dolist (sub subst-list) (let ((position (search (car sub) string :start2 index))) (when (and position (< position min)) (setf min position) (setf found sub)))) (if found (progn (setf something-copied? t) ;; Pre-match contents (setf result (replace result string :start1 result-end :start2 start :end2 min)) (incf result-end (- min start)) ;; Match (setf result (replace result (cdr found) :start1 result-end)) (incf result-end (length (cdr found))) ;; Jump forward (setf start (+ min (length (car found)))) (setf index start)) ;; TODO DESIGN - this is slow and dumb. If there's no match found, we should be done with the search. We don't have to iterate forward. ;; Not found (incf index)) (setf done (>= index (length string))))) (if something-copied? (progn ;; Add final unmatched tail (replace result string :start1 result-end :start2 start :end2 index) (incf result-end (- index start)) (subseq result 0 result-end)) ;; No substitutions found string)))) (symbol-mapping substring subseq) (defun ends-with (w ending) (and (greater-or-same-length-p w ending) (substring-match? w ending (- (length w) (length ending))))) (defun starts-with (w starting) (and (greater-or-same-length-p w starting) (substring-match? w starting 0))) (defun* char-position (char string &optional (n 0)) (:inline t) "[Cyc] Return the number of the position of the first occurrence of CHAR in STRING, starting from position N in STRING." (declare (string string) (character char) (fixnum n)) (position char string :start n)) (defun string-upto (string &optional (char #\Space)) (declare (string string) (character char)) (alexandria:if-let ((pos (char-position char string))) (subseq string 0 pos) string)) (defun strcat (string-list) "[Cyc] Like cconcatenate, but takes a list of strings as its argument." ;; TODO DESIGN - shouldn't this return "" when nil? (when string-list (apply #'concatenate 'string string-list))) (defun stringify-terms (terms &optional (separator " ") (last-separator separator)) (stringify-items terms #'fort-print-name separator last-separator)) (defun str-by-type (object) (cond ((stringp object) object) ((constant-p object) (constant-name object)) (t (str object)))) (defparameter *char-set* nil "[Cyc] Dynamic variable used only by CHAR-SET-POSITION.") (defun* char-type-position (char-type string &optional (start 0) (end (length string))) (:inline t) "[Cyc] Return the position of the first charcter satisfying the CHAR-TYPE in STRING. THe positions to start looking in STRING are delimited by START and END." (position-if char-type string :start start :end end)) (defun not-digit-char-p (thing) (not (digit-char-p thing))) (defun set-nth-char (n string new-char &optional (safe? t)) "[Cyc] Set the Nth character of STRING to NEW-CHAR. SAFE?: should we make sure args are legit?" (declare (string string) ((and fixnum (integer 0)) n) (character new-char)) (when (or (not safe?) (length> string n)) (set-char string n new-char)) string) (defun substring? (little big &optional test (start-index 0) end-index) "[Cyc] Is LITTLE a substring of BIG starting at or after START-INDEX, and ending before END-INDEX (if non-NIL)?" (declare (ignore test)) (when (and (stringp little) (stringp big)) (if (length= little 1) (find (first-char little) big :start start-index :end end-index) (search little big :start2 start-index :end2 end-index)))) (defun substring-match? (big little start) "[Cyc] Returns true if, after moving forward START characters from the beginning of the string BIG, the next few characters match (STRING=) the string SMALL." (let ((end (+ start (length little)))) (and (length>= big end) (substring? little big nil start end)))) ;; DESIGN - base64 tools elided in preference to external libraries (defun upper-case-alphanumeric-p (object) (and (characterp object) (or (upper-case-p object) (digit-char-p object)))) ;; TODO - what's with the duplicate here, and it getting removed in the next var? (deflexical *raw-whitespace-chars* '(#\Space #\Tab #\Return #\Newline #\Newline) "All symbolic names that LISP provides for different types of whitespace.") (deflexical *whitespace-chars* (delete-duplicates *raw-whitespace-chars* :test #'char-equal) "[Cyc] The actual set of white space characters in this LISP implementation.") (defun whitespace-chars () (copy-list *whitespace-chars*)) (deflexical *grammatical-punctuation-chars* '(#\, #\? #\! #\& #\\ #\/ #\" #\; #\: #\( #\)) "[Cyc] The list of chars that are syntactic punctuation only (not used inside words). Note -- does not include periods because they can occur inside number expressions.") (defun whitespacep (char) (and (characterp char) (find char *whitespace-chars*))) (defun non-whitespace-p (char) (not (whitespacep char))) (defun break-words (string &optional (non-break-char-test #'valid-constant-name-char-p) leave-embedded-strings?) "[Cyc] Takes a string (such as an English phrase or sentence). Returns a list of words, based on the break points implied by the function NON-BREAK-CHAR-TEST (characters that fail the test are break points), and whether or not embedded strings should be left alone." (let ((ans nil)) (loop with len = (length string) with p1 = 0 with p2 = 1 with inside-dq? = nil until (> p2 len) do (let* ((px (1- p2)) (c1 (char string p1)) (c2 (if (< p2 len) (char string p2) nil)) (cx (char string px)) (c1-is-break? (and (characterp c1) (or (not leave-embedded-strings?) (char/= c1 #\")) (not (funcall non-break-char-test c1)))) (c2-is-break? (and (characterp c2) (or (not leave-embedded-strings?) (char/= c2 #\")) (not (funcall non-break-char-test c2))))) (when (and (char= c1 #\") leave-embedded-strings?) (if inside-dq? (when (and (char= cx #\") (/= p1 px)) (setf inside-dq? nil)) (setf inside-dq? t))) (cond ((and (= p2 len) (not c1-is-break?)) (push (subseq string p1 p2) ans) (incf p2)) (c1-is-break? (incf p1) (setf p2 (1+ p1))) ((not (or c1-is-break? c2-is-break?)) (incf p2)) ((and (not c1-is-break?) (not inside-dq?) c2-is-break?) (push (subseq string p1 p2) ans) (setf p1 (1+ p2)) (setf p2 (1+ p1))) ((and (not c1-is-break?) inside-dq? c2-is-break?) (incf p2))))) (nreverse ans))) (defun char-list-to-string (chars) "Coerce a list of characters to a string." (coerce chars 'string)) (defparameter *target-characters* nil) (defun make-valid-constant-name (in-string &optional (upcase-initial-letter? t)) "[Cyc] Make a fake constant name (a string) by capitalizing words after whitespace (and symbols) then eliminating invalid constant characters, including spaces. Example: (make-valid-constant-name \"this is sa fake constant! 200 #$\" returns \"ThisIsAFakeConstant200\". Note: We *could* use STRING-PROPER and (STRING-SUBST \"\" \" \" ...), but we're mad at those functions and don't want to call them." (let ((cur-string-list nil) (should-we-upcase? upcase-initial-letter?)) (map nil (lambda (this-character) (declare (character this-character)) (if (valid-constant-name-char-p this-character) (if (alphanumericp this-character) (if should-we-upcase? (progn (push (string (char-upcase this-character)) cur-string-list) (setf should-we-upcase? nil)) (push (string this-character) cur-string-list)) (progn (push (string this-character) cur-string-list) (setf should-we-upcase? t))) (setf should-we-upcase? t))) in-string) (strcat (nreverse cur-string-list)))) (defun string-tokenize (in-string &optional (break-list *whitespace-chars*) embed-list include-stops? ignore-empty-strings? quote-chars break-list-to-return) (string-tokenize-int in-string break-list break-list-to-return embed-list include-stops? ignore-empty-strings? quote-chars)) (defun string-tokenize-int (in-string &optional (break-list *whitespace-chars*) break-list-to-return embed-list include-stops? ignore-empty-strings? quote-chars) "[Cyc] Breaks IN-STRING on any string sequence in BREAK-LIST. Returns a list of strings. EMBED-LIST should be a list of pairs of strings specifying start and end characters between which we ignore breaks. If INCLUDE-STOPS? is T then the break elements will be included in the resulting list. If IGNORE-EMPTY-STRING is T then there will be no empty strings in the result list. QUOTE-CHARS should be a list of characters (characters, not strings) which mean that the next character should be treated literally, not as a break or embed-char (a common example is backslash in UN*X. The priority of the breaks is specified in BREAK-LIST (i.e. initial entries will be broken first)." (when (eq :default break-list) (setf break-list *whitespace-chars*)) (let ((in-length (length in-string)) (out-string-list nil) (cur-string *empty-string*) (cur-char-list nil) (break-satisfied? nil) (this-quoted? nil) (complete-break-list (append break-list-to-return break-list))) ;; Can't use dovector to iterate the string. ;; setf pos-now changes the iteration location, so that needs to be the basis. (loop for pos-now from 0 below in-length for this-character = (char in-string pos-now) do (cond (this-quoted? (progn (setf this-quoted? nil) (push this-character cur-char-list))) ((member this-character quote-chars) (progn (setf this-quoted? t) (push this-character cur-char-list))) (t (dolist (this-embed embed-list) (let ((this-embed-start (first-char (first this-embed))) (this-embed-end (last-char (second this-embed)))) (when (char= this-character this-embed-start) (do ((pos-find (1+ pos-now) (1+ pos-find)) (quoted? nil) (done? nil)) ;; Termination test only, no return body ((or done? (eq in-length pos-now))) ;; Iteration body (push this-character cur-char-list) (setf pos-now pos-find) (setf this-character (char in-string pos-now)) (cond (quoted? (setf quoted? nil)) ((char= this-character this-embed-end) (setf done? t)) ((member this-character quote-chars) (setf quoted? t))))))) (let ((found-a-break? nil)) (csome (this-break complete-break-list found-a-break?) (let* ((this-break-length (string-tokenize-break-length this-break)) (post-break-pos (+ pos-now this-break-length))) (when (and (plusp this-break-length) (length>= in-string post-break-pos) (string-tokenize-break-match? in-string this-break pos-now)) (setf found-a-break? t) (setf cur-string (char-list-to-string (nreverse cur-char-list))) (unless (and ignore-empty-strings? (empty-string-p cur-string)) (push cur-string out-string-list)) (setf cur-char-list nil) (when (or include-stops? (member this-break break-list-to-return)) (push (format nil "~a" this-break) out-string-list)) (setf pos-now (1- post-break-pos)) (setf this-character (char in-string pos-now)) (setf break-satisfied? t))))) (if break-satisfied? (setf break-satisfied? nil) (push this-character cur-char-list))))) (setf cur-string (char-list-to-string (nreverse cur-char-list))) (unless (and ignore-empty-strings? (empty-string-p cur-string)) (push cur-string out-string-list)) (unless (or out-string-list ignore-empty-strings?) (setf out-string-list (list *empty-string*))) (nreverse out-string-list))) (defun string-tokenize-break-length (break) (if (characterp break) 1 (length break))) (defun string-tokenize-break-match? (in-string break pos) "[Cyc] Does IN-STRING match BREAK at position POS?" (if (characterp break) (char= (char in-string pos) break) (substring-match? in-string break pos))) (defparameter *trigraph-metric* 0.8 "[Cyc] Metric used for STRING-TRIGRAPH-MATCH-P, which is defined below.") (defparameter *trigraph-tables* nil "[Cyc] A list of one or more utility hash tables, used by STRING-TRIGRAPH-MATCH-P, which is defined below.") ;; These are strings, not cycl constants, in the original java (defvar *cyclify-string-expand-subl-fn-strings* (list "#$ExpandSubLFn" "ExpandSubLFn")) (defvar *cyclify-string-subl-quote-fn-strings* (list "#$SubLQuoteFn" "SubLQuoteFn")) (defvar *cyclify-string-quote-chars* '(#\\)) (defstruct cyclify-status out-string-list references-added inside-quote? inside-el-var-name? already-cyclified? escape? inside-subl-quote-fn? inside-expand-subl-fn? inside-expand-subl-fn-arg1? inside-expand-subl-fn-arg2? immediately-following-paren? paren-count) (defparameter *string-read-buffer-size* 1024) (defparameter *string-read-buffer* (make-vector *string-read-buffer-size* #\Space))
19,558
Common Lisp
.lisp
376
41.098404
679
0.609094
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
27b61824f261f341fc3f5774b825ad76fd06bc595b6173c2dd9097e6a32804ed
6,797
[ -1 ]
6,798
assertions-high.lisp
white-flame_clyc/larkc-cycl/assertions-high.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defmacro define-valid-assertion-func (name &body (docstring &optional (internal-func (symbolicate "KB-" name)))) `(defun ,name (assertion) ,docstring (and (assertion-valid? assertion) (,internal-func assertion)))) (define-valid-assertion-func assertion-cnf "[Cyc] Return the cnf of ASSERTION. Note: If you know the assertion is a gaf, consider using gaf-formula instead, if you do not explicitly need a CNF.") (define-valid-assertion-func possibly-assertion-cnf "[Cyc] Return the CNF of ASSERTION, or NIL if none can be found.") (define-valid-assertion-func assertion-mt "[Cyc] Return the MT of ASSERTION.") (define-valid-assertion-func assertion-gaf-hl-formula nil) (define-valid-assertion-func assertion-cons "[Cyc] Return a cons list representing ASSERTION's formula in some form, maybe a CNF, maybe a GAF formula, or NIL if it's invalid. Note: Result is not destructible.") (define-valid-assertion-func gaf-assertion? "[Cyc] Return T iff ASSERTION is a ground atomic formula (gaf).") (define-valid-assertion-func assertion-direction "[Cyc] Return the direction of ASSERTION (either :backward, :forward, or :code).") (define-valid-assertion-func assertion-truth "[Cyc] Return the current truth of ASSERTION -- either :true :false or :unknown.") (define-valid-assertion-func assertion-strength "[Cyc] Return the current argumentation strength of ASSERTION -- either :monotic, :default, or :unknown.") (define-valid-assertion-func assertion-variable-names "[Cyc] Return the variable names for ASSERTION.") ;; TODO - names that don't fit the pattern (define-valid-assertion-func asserted-by "[Cyc] Returns the cyclist who asserted ASSERTION." kb-assertion-asserted-by) (define-valid-assertion-func asserted-when "[Cyc] Returns teh day when ASSERTION was asserted." kb-assertion-asserted-when) (define-valid-assertion-func asserted-why "[Cyc] Returns the reason why ASSERTION was asserted." kb-assertion-asserted-why) (define-valid-assertion-func asserted-second "[Cyc] Returns the second of the day when ASSERTION was asserted." kb-assertion-asserted-second) (define-valid-assertion-func assertion-arguments "[Cyc] Return a list of the arguments for ASSERTION.") (define-valid-assertion-func assertion-dependents "[Cyc] Return a list of the dependents of ASSERTION.") (defun cyc-assertion-tv (assertion) "[Cyc] Cyc has its own notion of tv (truth + strength) as a legacy of when the Cyc and HL sides were entangled." (tv-from-truth-strength (assertion-truth assertion) (assertion-strength assertion))) (defun assertion-formula (assertion) "[Cyc] Return a formula for ASSERTION." (if (gaf-assertion? assertion) (gaf-el-formula assertion) (when-let ((cnf (assertion-cnf assertion))) (and (cnf-p cnf) (cnf-formula cnf (assertion-truth assertion)))))) (defun rule-assertion? (assertion) "[Cyc] Return T iff ASSERTION is a rule, i.e. not a ground atomic formula (gaf)." (and (assertion-p assertion) (not (gaf-assertion? assertion)))) (defun forward-rule? (assertion) (and (rule-assertion? assertion) (forward-assertion? assertion))) (defun* assertion-type (assertion) (:inline t) "[Cyc] Return the current type of ASSERTION -- either :GAF or :RULE." (if (gaf-assertion? assertion) :gaf :rule)) (defun* assertion-has-type? (assertion type) (:inline t) "[Cyc] Return T iff ASSERTION's current type is TYPE." (eq type (assertion-type assertion))) (defun* gaf-formula (assertion) (:inline t) "[Cyc] Return the formula for ASSERTION, which must be a gaf. Does not put a #$not around negated gafs." (gaf-hl-formula assertion)) (defun* gaf-hl-formula (assertion) (:inline t) "[Cyc] Return the formula for ASSERTION, which must be a gaf. Does not put a #$not around negated gafs." (assertion-gaf-hl-formula assertion)) (defun* gaf-el-formula (assertion) (:inline t) "[Cyc] Return the formula for ASSERTION, which must be a gaf. Puts a #$not around negated gafs. Does not do any uncanonicalization or conversion of HL terms in args to EL." (assertion-gaf-el-formula assertion)) (defun assertion-gaf-el-formula (assertion) "[Cyc] Returns the EL formula of ASSERTION if it's a gaf, otherwise returns NIL. This will return (#$not <blah>) for negated gafs." (when-let ((formula (assertion-gaf-hl-formula assertion))) (if (eq :false (assertion-truth assertion)) (negate formula) formula))) (defun gaf-args (assertion) "[Cyc] Returnargs of the gaf ASSERTION." (formula-args (gaf-formula assertion))) (defun* gaf-arg (assertion n) (:inline t) "[Cyc] Return arg N of the gaf ASSERTION." (nth n (gaf-formula assertion))) (defun* gaf-predicate (assertion) (:inline t) "[Cyc] Return the predicate of gaf ASSERTION." (formula-arg0 (gaf-hl-formula assertion))) (defun* gaf-arg1 (assertion) (:inline t) "[Cyc] Return arg 1 of the gaf ASSERTION." (gaf-arg assertion 1)) (defun* gaf-arg2 (assertion) (:inline t) "[Cyc] Return arg 2 of the gaf ASSERTION." (gaf-arg assertion 2)) (defun* gaf-arg3 (assertion) (:inline t) "[Cyc] Return arg 3 of the gaf ASSERTION." (gaf-arg assertion 3)) (defun* assertion-has-direction? (assertion direction) (:inline t) "[Cyc] Return T iff ASSERTION has DIRECTION as its direction." (eq direction (assertion-direction assertion))) ;; TODO - deprecate (defun* assertion-has-direction (assertion direction) (:inline t) (assertion-has-direction? assertion direction)) (defun forward-assertion? (assertion) "[Cyc] Predicate returns T iff ASSERTION's direction is :FORWARD." (and (assertion-p assertion) (eq :forward (assertion-direction assertion)))) (defun* assertion-has-truth? (assertion truth) (:inline t) "[Cyc] Return T iff ASSERTION's current truth is TRUTH." (eq (assertion-truth assertion) truth)) ;; TODO - deprecate (defun* assertion-has-truth (assertion truth) (:inline t) (assertion-has-truth? assertion truth)) (defun* assertion-el-variables (assertion) (:inline t) "[Cyc] Return a list of the EL variables, for ASSERTION." (mapcar #'intern-el-var (assertion-variable-names assertion))) (defun timestamp-asserted-assertion (assertion &optional who when why second) (when *recording-hl-transcript-operations?* (missing-larkc 32158)) (timestamp-asserted-assertion-int assertion who when why second)) (defglobal *tl-assertion-lookaside-table* nil "[Cyc] A lookaside cache for efficiency of tl-timestamp-asserted-assertion. TL assertion -> HL assertion.") (deflexical *tl-assertion-capacity* 5) (defun timestamp-asserted-assertion-int (assertion &optional who when why second) (when (asserted-assertion? assertion) (kb-set-assertion-asserted-by assertion who) (kb-set-assertion-asserted-when assertion when) (kb-set-assertion-asserted-why assertion why) (kb-set-assertion-asserted-second assertion second))) (defun invalid-assertion? (assertion &optional robust?) (declare (ignore robust?)) (and (assertion-p assertion) (not (valid-assertion? assertion)))) ;; TODO - deprecate (defun* valid-assertion (assertion &optional robust?) (:inline t) (declare (ignore robust?)) (valid-assertion? assertion)) (defun* create-assertion (cnf mt &optional var-names (direction :backward)) (:inline t) "[Cyc] Create a new assertion with CNF in MT." (create-assertion-int cnf mt var-names direction)) (defun find-or-create-assertion (cnf mt &optional var-names (direction :backward)) "[Cyc] Return assertion in MT with CNF, if it exists -- else create it." (or (find-assertion cnf mt) (create-assertion cnf mt var-names direction))) (defun create-assertion-int (cnf mt &optional var-names (direction :backward)) (let ((assertion (kb-create-assertion cnf mt))) (when assertion (kb-set-assertion-variable-names assertion var-names) (kb-set-assertion-direction assertion direction)) assertion)) (defun* remove-assertion (assertion) (:inline t) "[Cyc] Remove ASSERTION." (kb-remove-assertion assertion)) (defun only-argment-of-assertion-p (assertion argument) "[Cyc] Returns T if ARGUMENT is the sole argument for ASSERTION; NIL if there are other, different arguments." (not (member? argument (assertion-arguments assertion) :test #'not-eq))) (defun asserted-assertion? (assertion) "[Cyc] Return non-NIL iff ASSERTION has an asserted argument." (find-if #'asserted-argument-p (assertion-arguments assertion))) (defun get-asserted-argument (assertion) "[Cyc] Return the asserted argument for ASSERTION, or NIL if none present." (find-if #'asserted-argument-p (assertion-arguments assertion))) (defun assertion-dependent-count (assertion) "[Cyc] Return the number of arguments depending on ASSERTION." (length (assertion-dependents assertion))) (defparameter *assertion-dump-id-table* nil) (defun* find-assertion-by-dump-id (dump-id) (:inline t) "[Cyc] Return the assertion with DUMP-ID during a KB load." (find-assertion-by-id dump-id))
10,443
Common Lisp
.lisp
208
46.894231
134
0.74658
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8ca5a2d53a6fea993c00378ae219e1a6774b54b5c1c3df560fee739d3054f24a
6,798
[ -1 ]
6,799
subl-macros.lisp
white-flame_clyc/larkc-cycl/subl-macros.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *ignore-assert-types?* t "[Cyc] When non-NIL, ASSERT-TYPE and ASSERT-MUST statements are ignored. Otherwise, they expand into CHECK-TYPE and MUST statements, respectively.") (defun rplacd-last (non-empty-list new-last-cdr) (rplacd (last non-empty-list) new-last-cdr))
1,684
Common Lisp
.lisp
31
50.935484
150
0.780578
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b581788e84101dfbd48364794f327500f9c7d6269c30d65080850928a883b274
6,799
[ -1 ]
6,800
graph-utilities.lisp
white-flame_clyc/larkc-cycl/graph-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun categorize-nodes-via-links (nodes links &optional (test #'eql)) "[Cyc] Given a list of NODES, and a list of LINKS which relate these nodes, categorize the nodes into island-groups, where each group consists of a list of connected nodes, and a list of links involving these nodes. Returns 3 values: CONNECTED-GROUPS -- list of island groups with multiple nodes. ISOLATED-GROUPS -- list of island groups with single nodes and some links. NAKED-GROUPS -- list of island groups with single nodes and no links." (let ((all-island-groups nil)) (dolist (node nodes) (push (list (list node) nil) all-island-groups)) (dolist (link links) (let* ((link-nodes (extract-link-nodes link nodes test)) (island-groups (extract-island-groups link-nodes all-island-groups test)) (island-group nil)) (if (singleton? island-groups) (setf island-group (car island-groups)) (let ((merged-island-group island-groups)) (setf all-island-groups (set-difference all-island-groups island-groups)) (push merged-island-group all-island-groups) (setf island-group merged-island-group))) (destructuring-bind (group-nodes group-links) island-group (declare (ignore group-nodes)) (setf (nth 1 island-group) (cons link group-links))))) (let ((connected-groups nil) (isolated-groups nil) (naked-groups nil)) (dolist (island-group all-island-groups) (destructuring-bind (group-nodes group-links) island-group (if (singleton? group-nodes) (if group-links (push island-group isolated-groups) (push island-group naked-groups)) (push island-group connected-groups)))) (when (singleton? nodes) (setf connected-groups isolated-groups) (setf isolated-groups nil)) (setf connected-groups (sort-connected-groups connected-groups nodes links test)) (setf isolated-groups (sort-isolated-groups isolated-groups nodes links test)) (setf naked-groups (sort-naked-groups naked-groups nodes test)) (values connected-groups isolated-groups naked-groups)))) ;; TODO - I don't think SubL has inline lambda closures, so it uses toplevel functions and these sorts of private variable bindings, which is kinda terrible. Refactor this pattern wherever it occurs. (defparameter *extract-link-nodes-nodes* nil) (defparameter *extract-link-nodes-test* nil) (defun extract-link-nodes (link candidate-nodes &optional (test #'eql)) "[Cyc] Extract a subset of CANDIDATE-NODES mentioned in LINK." (let ((*extract-link-nodes-nodes* candidate-nodes) (*extract-link-nodes-test* test)) (tree-gather link #'extract-link-nodes-int test))) (defun extract-link-nodes-int (object) (member? object *extract-link-nodes-nodes* :test *extract-link-nodes-test*)) (defun extract-island-groups (nodes candidate-island-groups &optional (test #'eql)) "[Cyc] Extract a subset of CANDIDATE-ISLAND-GROUPS whose nodes intersect NODES." (let ((island-groups nil)) (dolist (node nodes island-groups) (pushnew (island-group-for-node node candidate-island-groups test) island-groups)))) (defun island-group-for-node (node island-groups &optional (test #'eql)) "[Cyc] Return the associated island-group for NODE from ISLAND-GROUPS." (dolist (island-group island-groups) (multiple-value-bind (nodes links) island-group (declare (ignore links)) (when (member? node nodes :test test) (return island-group))))) (defun merge-island-groups (island-groups) "[Cyc] Merge every island-group in ISLAND-GROUPS into a single resulting group." (let ((merged-group-nodes nil) (merged-group-links nil)) (dolist (island-group island-groups (list merged-group-nodes merged-group-links)) (destructuring-bind (group-nodes group-links) island-group (dolist (node group-nodes) (push node merged-group-nodes)) (dolist (link group-links) (push link merged-group-links)))))) (defun sort-connected-groups (connected-groups all-nodes all-links &optional (test #'eql)) (dolist (island-group connected-groups ;; Exit form (stable-sort (sort-via-position connected-groups all-nodes test #'caar) #'< :key #'length-first)) (destructuring-bind (nodes links) island-group (setf (nth 0 island-group) (sort-via-position nodes all-nodes #'eql)) (setf (nth 1 island-group) (sort-via-position links all-links #'eql))))) (defun* length-first (object) (:inline t) (length (first object))) (defun sort-isolated-groups (isolated-groups all-nodes all-links &optional (test #'eql)) "[Cyc] Sort ISOLATED-GROUPS based on ALL-NODES and ALL-LINKS." (dolist (island-group isolated-groups) (destructuring-bind (nodes links) island-group (declare (ignore nodes)) (setf (nth 1 island-group) (sort-via-position links all-links #'eql)))) (sort-via-position isolated-groups all-nodes test #'caar)) (defun sort-naked-groups (naked-groups all-nodes &optional (test #'eql)) (sort-via-position naked-groups all-nodes test #'caar))
6,630
Common Lisp
.lisp
118
50.008475
217
0.712566
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8ffccee47b1ec1a903d21f1a4fc119df2a10c604f08f27c18dd84238e8455203
6,800
[ -1 ]
6,801
system-version.lisp
white-flame_clyc/larkc-cycl/system-version.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *cyc-raw-revision-string* "$Revision: 128948 $") (defparameter *cyc-major-version-number* 10) (defparameter *cyc-revision-numbers* (extract-cyc-revision-numbers (extract-cyc-revision-string *cyc-raw-revision-string*))) (defparameter *cyc-revision-string* (construct-cyc-revision-string-from-numbers *cyc-revision-numbers*)) (defparameter *cycl-common-revision* "1.269") (defparameter *cycl-crtl-revision* "1.555") (defparameter *cycl-translator-revision* "1.69") (defparameter *cycl-opencyc-revision* "1.391") (defparameter *cycl-framework-revision* "1.1767") (defparameter *cycl-sublisp-revision* "1.319") (defparameter *cycl-tests-revision* "1.907") (defparameter *cycl-mysentient-revision* "1.437") (defparameter *cycl-butler-revision* "1.277") (defparameter *cycl-tool-revision* "1.652") (defparameter *cycl-=======-revision* "") (toplevel (create-system "cycl") (dolist (name '("cyc-cvs-id" "meta-macros" "access-macros" "subl-macro-promotions" "subl-promotions" "subl-macros" "format-nil" "modules" "cyc-revision-extraction" "system-parameters" "system-version" "system-info" "utilities-macros" "timing" "cyc-file-dependencies" "cycml-macros" "control-vars" "sunit-macros" "sunit-external" "cfasl" "sxhash-external" "red-implementation" "red-api" "cyc-testing-initialization" "cyc-testing" "generic-testing" "hash-table-utilities" "keyhash" "set-contents" "reader-writer-locks" "memoization-state" "list-utilities" "transform-list-utilities" "vector-utilities" "string-utilities" "unicode-strings" "unicode-subsets" "unicode-support" "unicode-streams" "defstruct-sequence" "visitation-utilities" "mail-utilities" "mail-message" "number-utilities" "fraction-utilities" "matrix-utilities" "numeric-date-utilities" "iteration" "binary-tree" "stacks" "queues" "deck" "integer-sequence-generator" "semaphores" "process-utilities" "os-process-utilities" "tcp-server-utilities" "pattern-match" "tries" "shelfs" "id-index" "dictionary-contents" "dictionary" "cfasl-compression" "cfasl-utilities" "bijection" "glob" "keyhash-utilities" "set" "set-utilities" "dictionary-utilities" "map-utilities" "bag" "accumulation" "red-infrastructure" "red-infrastructure-macros" "red-utilities" "file-utilities" "stream-buffer" "hierarchical-visitor" "strie" "finite-state-transducer" "cache" "cache-utilities" "special-variable-state" "simple-lru-cache-strategy" "file-hash-table" "file-hash-table-utilities" "file-vector" "file-vector-utilities" "generic-table-utilities" "sdbc-macros" "sdbc" "graph-utilities" "sparse-vector" "sparse-matrix" "remote-image" "cyc-testing-utilities" "heap" "decision-tree" "misc-utilities" "web-utilities" "timing-by-category" "api-control-vars" "eval-in-api" "eval-in-api-registrations" "api-kernel" "cfasl-kernel" "guardian" "hl-interface-infrastructure" "kb-macros" "constant-completion-low" "constant-completion-interface" "constant-completion-high" "constant-completion" "constant-handles" "constant-reader" "enumeration-types" "kb-control-vars" "mt-vars" "graphl-search-vars" "ghl-search-vars" "sbhl-iteration" "sbhl-paranoia" "sbhl-module-vars" "sbhl-link-vars" "sbhl-marking-vars" "sbhl-search-datastructures" "sbhl-search-vars" "sbhl-time-vars" "sbhl-link-iterators" "at-vars" "gt-vars" "czer-vars" "mt-relevance-macros" "pred-relevance-macros" "at-macros" "czer-macros" "wff-macros" "wff-vars" "gt-macros" "hl-macros" "obsolete" "obsolete-macros" "kb-mapping-macros" "kb-access-metering" "kb-object-manager" "hlmt" "hlmt-czer" "constants-interface" "constant-index-manager" "constants-low" "constants-high" "nart-handles" "narts-interface" "nart-index-manager" "nart-hl-formula-manager" "narts-low" "narts-high" "forts" "assertion-handles" "assertions-interface" "assertion-manager" "assertions-low" "assertions-high" "kb-hl-support-manager" "kb-hl-supports" "deduction-handles" "deductions-interface" "deduction-manager" "deductions-low" "deductions-high" "unrepresented-term-index-manager" "unrepresented-terms" "arguments" "clause-strucs" "variables" "format-cycl-expression" "hl-storage-modules" "hl-modifiers" "sxhash-external-kb" "el-macros" "sbhl-macros" "cycl-variables" "el-utilities" "clause-utilities" "cycl-utilities" "cycl-grammar" "el-grammar" "unicode-nauts" "term" "kb-indexing-datastructures" "kb-utilities" "simple-indexing" "kb-indexing-declarations" "kb-indexing-macros" "kb-indexing" "virtual-indexing" "kb-mapping" "kb-mapping-utilities" "kb-gp-mapping" "somewhere-cache" "auxiliary-indexing" "inferred-indexing" "arity" "kb-accessors" "kb-iterators" "function-terms" "relation-evaluation" "assertion-utilities" "parameter-specification-utilities" "clauses" "bindings" "unification" "unification-utilities" "file-backed-cache" "graphl-graph-utilities" "ghl-graph-utilities" "ghl-link-iterators" "ghl-marking-utilities" "ghl-search-utilities" "sbhl-graphs" "sbhl-caching-policies" "sbhl-module-utilities" "sbhl-links" "sbhl-nat-utilities" "sbhl-link-utilities" "sbhl-link-methods" "sbhl-marking-utilities" "sbhl-search-utilities" "sbhl-marking-methods" "sbhl-search-methods" "sbhl-search-what-mts" "sbhl-search-implied-relations" "sbhl-module-declarations" "genls" "disjoint-with" "sdc" "isa" "genl-predicates" "negation-predicate" "genl-mts" "mt-relevance-cache" "predicate-relevance-cache" "negation-mt" "ghl-search-methods" "sbhl-cache" "fort-types-interface" "czer-trampolines" "wff-utilities" "wff-module-datastructures" "wff-modules" "wff" "wff-suggest" "simplifier" "tersifier" "verbosifier" "czer-utilities" "precanonicalizer" "postcanonicalizer" "clausifier" "prop-sentence-clausifier" "czer-graph" "czer-main" "rule-macros" "skolems" "czer-meta" "uncanonicalizer" "canon-tl" "at-routines" "at-utilities" "at-admitted" "at-defns" "defns" "at-var-types" "at-cache" "arg-type" "applicable-relations" "sksi-macros" "janus-macros" "gt-utilities" "gt-search" "gt-methods" "transitivity" "transfers-through" "tva-utilities" "tva-tactic" "tva-strategy" "tva-inference" "tva-cache" "equality-store" "equals" "rewrite-of-propagation" "hl-supports" "conflicts" "ebl" "preserves-genls-in-arg" "formula-pattern-match" "cfasl-kb-methods" "inference-macros" "inference-modules" "search" "tms" "after-adding" "rule-after-adding" "after-adding-modules" "argumentation" "backward" "psc" "inference-trampolines" "inference-completeness-utilities" "backward-utilities" "backward-results" "transformation-heuristics" "inference-pad-data" "preference-modules" "preference-module-declarations" "inference-datastructures-enumerated-types" "inference-datastructures-problem-store" "inference-datastructures-problem-query" "inference-datastructures-problem" "inference-datastructures-problem-link" "inference-datastructures-tactic" "inference-datastructures-proof" "inference-datastructures-strategy" "inference-datastructures-forward-propagate" "inference-datastructures-inference" "inference-czer" "inference-proof-spec" "inference-proof-spec-store" "inference-worker" "inference-worker-answer" "inference-worker-restriction" "inference-worker-removal" "inference-worker-transformation" "inference-worker-residual-transformation" "inference-worker-rewrite" "inference-worker-split" "inference-worker-join-ordered" "inference-worker-join" "inference-worker-union" "inference-tactician-strategic-uninterestingness" "inference-lookahead-productivity" "inference-min-transformation-depth" "inference-tactician" "inference-tactician-utilities" "inference-strategic-heuristics" "inference-balanced-tactician-datastructures" "inference-balanced-tactician-strategic-uninterestingness" "inference-balanced-tactician-motivation" "inference-balanced-tactician-execution" "inference-heuristic-balanced-tactician" "balancing-tactician" "removal-tactician-datastructures" "removal-tactician-uninterestingness" "removal-tactician-motivation" "removal-tactician-execution" "removal-tactician" "transformation-tactician-datastructures" "transformation-tactician-uninterestingness" "transformation-tactician-motivation" "transformation-tactician-execution" "transformation-tactician" "new-root-tactician-datastructures" "new-root-tactician-motivation" "new-root-tactician-execution" "new-root-tactician" "neural-net" "inference-strategist" "inference-kernel" "inference-trivial" "inference-utilities" "inference-parameters" "inference-metrics" "inference-analysis" "inference-serialization" "inference-unit-tests" "removal-module-tests" "transformation-module-tests" "evaluatable-relation-tests" "inference-testing-helpers" "inference-testing" "removal-module-cost-tests" "kb-query" "kbq-query-run" "arete" "janus" "leviathan" "deep-inference-generator" "lilliput" "lilliput-caches" "ask-utilities" "removal-module-utilities" "removal-modules-lookup" "removal-modules-minimization" "removal-modules-evaluation" "removal-modules-symmetry" "removal-modules-transitivity" "removal-modules-reflexivity" "removal-modules-reflexive-on" "removal-modules-genlpreds-lookup" "removal-modules-relation-all" "removal-modules-relation-all-instance" "removal-modules-relation-all-exists" "removal-modules-relation-instance-exists" "removal-modules-term-external-id-string" "removal-modules-backchain-required" "removal-modules-abduction" "meta-removal-modules" "removal-modules-non-wff" "removal-modules-isa" "removal-modules-genls" "removal-modules-denotes" "removal-modules-classification" "removal-modules-subset-of" "removal-modules-nearest-isa" "removal-modules-disjointwith" "removal-modules-termofunit" "removal-modules-natfunction" "removal-modules-formula-arg-n" "removal-modules-equals" "removal-modules-evaluate" "removal-modules-different" "removal-modules-genlmt" "removal-modules-genlpreds" "removal-modules-genlinverse" "removal-modules-negationpreds" "removal-modules-negationinverse" "removal-modules-ist" "removal-modules-consistent" "removal-modules-admitted-formula" "removal-modules-asserted-formula" "removal-modules-asserted-arg1-binary-preds" "removal-modules-function-corresponding-predicate" "removal-modules-start-offset" "removal-modules-true-sentence" "removal-modules-formula-implies" "removal-modules-asserted-more-specifically" "removal-modules-isomorphic-sentences" "removal-modules-conceptually-related" "removal-modules-integer-between" "removal-modules-indexical-referent" "removal-modules-constant-name" "removal-modules-assertion-mt" "removal-modules-term-strings" "removal-modules-perform-subl" "removal-modules-term-chosen" "removal-modules-tva-lookup" "removal-modules-bookkeeping" "removal-modules-rtv" "removal-modules-member-of-list" "removal-modules-assertion-arguments" "removal-modules-deduction-supports" "removal-modules-assertion-deductions" "removal-modules-assertion-hl-asserted-argument-keyword" "removal-modules-inference-reflection" "removal-modules-known-antecedent-rule" "removal-modules-distance-between" "removal-modules-lat-long" "removal-modules-country-of-city" "removal-modules-kappa" "removal-modules-interval-range" "removal-modules-ke-useless-precision-value" "removal-modules-kb-indexing" "removal-modules-concatenate-strings" "removal-modules-query-answers" "removal-modules-set-of-list-with-same-member-in-pos" "removal-modules-conjunctive-pruning" "removal-modules-kb-sentence" "removal-modules-source-sentence" "transformation-modules" "simplification-modules" "rewrite-modules" "forward" "forward-modules" "forward-propagate-assertions" "abnormal" "hl-prototypes" "collection-intersection" "inference-abduction-utilities" "abduction" "fi" "cyc-bookkeeping" "cyc-kernel" "prove" "inference-iterators" "ke" "api-remote-objects" "batch-ke" "inference-viewer" "plot-generation" "cardinality-estimates" "relationship-generality-estimates" "evaluation-defns" "collection-defns" "ke-utilities" "ke-text" "kb-ontology-utilities" "ontology-layers" "system-benchmarks" "object-similarity" "partitions" "convert-partitions" "core" "kbs-utilities" "kbs-identification" "kbs-add-redundant" "kbs-partition" "kbs-cleanup" "kbs-compare" "kb-cleanup" "genls-hierarchy-problems" "encapsulation" "transcript-utilities" "transcript-server" "operation-communication" "operation-queues" "remote-operation-filters" "user-actions" "formula-template-vars" "xml-vars" "xml-macros" "agenda" "subl-identifier" "query-utilities" "kb-compare" "kb-paths" "ke-coherence" "ke-tools" "kb-filtering" "xml-utilities" "misc-kb-utilities" "scientific-numbers" "scientific-number-utilities" "extended-numbers" "arithmetic" "hl-storage-module-declarations" "bookkeeping-store" "dumper" "builder-utilities" "gt-modules" "task-processor" "java-api-kernel" "connection-guarding" "open-cyc-simple-inference-api" "term-classification-tree" "ctest-macros" "ctest-utils" "kct-variables" "kct-utils" "kct-cyc-testing" "kct-thinking" "cycl-query-specification" "new-cycl-query-specification" "formula-templates" "graphic-library-format" "value-tables" "script-instance-editor-api" "similarity" "constrained-term-finder" "constraint-filters" "test-query-suite" "nl-api-datastructures" "morphology" "file-backed-cache-setup" "standard-tokenization" "interval-span" "removal-modules-relevant-similar-queries" "removal-modules-semantically-related" "folification" "thcl" "cycml" "cycml-generator" "concept-filter" "lucene-session" "quirk-trampolines" "nlp-tests" "properties" "webcache" "xref-database" "secure-translation" "form-translation" "file-translation" "system-translation" "common-optimization" "c-name-translation" "c-backend" "optimized-funcall-declarations" "java-name-translation" "java-backend" "translator-utilities")) (create-module name "cycl")))
14,945
Common Lisp
.lisp
47
314.574468
12,592
0.784471
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9f15dd5b7e24e697c6511b2b66996fa6c5db749eacafe96d6884c999273e503b
6,801
[ -1 ]
6,802
misc-utilities.lisp
white-flame_clyc/larkc-cycl/misc-utilities.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - it makes more sense for loaded code to register its initializers, than to have to bake in all these calls here. ;; Apparently this is a reference boilerplate notice that Cycorp ;; might apply to various KBs it distributes. It is not referenced ;; anywhere in the LarKC source code or KB files, and is not applied ;; as a notice to anything in LarKC. Even if it were, LarKC does ;; have a "specific license agreement" with Cycorp to distribute ;; this version of Cyc under the Apache License 2.0, which has been ;; publicly distributed. (defconstant *kb-content-copyright-notice* ";; Copyright (c) 1998-2009 Cycorp, Inc., All Rights Reserved ;; This file and its contents are products of Cycorp, Inc. They are ;; released only under specific license agreement with Cycorp, and ;; must be treated as Cycorp Confidential Information, as per that ;; license agreement, including translation into another langauge ;; (including but not limited to Conceptual Graphs, KIF, Ontolingua, ;; GFP, LOOM, PowerLOOM, CycL, C, C++, IDL, predicate logic, and ;; English) and any logically equivalent rearrangement or renaming of ;; assertion components, terms, or variables. This paragraph shall ;; not be altered or removed. This file is provided \"AS IS\", without ;; any warranty; the cumulative liability of Cycorp for all claims ;; relating to this file shall not exceed the amount of one dollar. ;; Cycorp, 7718 Wood Hollow Drive, Suite 250, Austin, TX 78731, USA ;; Website: www.cyc.com, Tel: (512) 342-4000.") (defglobal *system-code-initializations-marker* (get-process-id)) (defun system-code-initializations (&optional (perform-app-specific-initializations? t)) "[Cyc] Initializations which should be run every time the system code is initialized." (initialize-cyc-product) (system-code-image-initializations) (system-code-hl-initializations) (system-code-inference-initializations) (system-code-api-initializations) (when (perform-app-specific-initializations?) (system-code-application-initializations)) (if (positive-integer-p (kb-loaded)) (system-kb-initializations) ;; This was commented out in the original, but seems sensible (warn "No KB is loaded. System KB initializatiosn will not be run.")) (setf *system-code-initializations-marker* (get-process-id)) t) (defun system-code-image-initializations () "[Cyc] System code initializations that have to do with distinguishing the current image from the image that saved out the world being used." (seed-random) (reset-cycl-start-time) (set-cyc-image-id) (clear-machine-bogomips) (validate-all-tcp-servers) (clear-active-os-processes) t) (defun system-code-hl-initializations () "[Cyc] System code initializations that have to do with HL level reasoning." (disable-hlmts) (initialize-sbhl-modules) t) (defun system-code-inference-initializations () "[Cyc] System code initializations that have to do with inference." (reclassify-removal-modules) (reclassify-hl-storage-modules) (destroy-all-problem-stores) (initialize-pad-table "hack!") t) (defun system-code-api-initializations () "[Cyc] System code initializations that have to do with the Cyc API." ;; TODO - pretty sure we don't have a Java API here in Clyc (reset-java-api-kernel) t) (defun system-code-application-initializations () "[Cyc] System code initializations for application code built into Cyc. To be called only by SYSTEM-CODE-INITIALIZATIONS." (clear-asked-query-queue) t) (defun system-kb-initializations () "[Cyc] Initializations which should be run every time the system is initialized, if there is a KB present." (initialize-hl-store-caches) (set-the-cyclist *default-cyclist-name*) (initialize-transcript-handling) (initialize-agenda) (initialize-global-locks) (perform-cyc-testing-initializations) (initialize-kct) (bt:make-thread #'initialize-all-file-backed-caches :name "file-backed cache initializer") (sleep 0.5) t) (defglobal *hl-store-caches-directory* nil "[Cyc] @HACK Currently, dump directory from which this KB was built; soon a published KB product subdirectory.") (defglobal *hl-store-caches-shared-symbols* nil "[Cyc] The symbols all KB products share.") (defun get-hl-store-caches-shared-symbols () *hl-store-caches-shared-symbols*) (defun initialize-hl-store-caches () (unless (hl-store-content-completely-cached?) (initialize-hl-store-caches-from-directory (hl-store-caches-directory)))) (defun initialize-hl-store-caches-from-directory (dirname &optional symbols) (if (initialize-hl-store-cache-directory-and-shared-symbols dirname symbols) (progn (initialize-deduction-hl-store-cache) (initialize-assertion-hl-store-cache) (initialize-constant-index-hl-store-cache) (initialize-nart-index-hl-store-cache) (initialize-unrepresented-term-index-hl-store-cache) (initialize-kb-hl-support-hl-store-cache) (initialize-sbhl-graph-caches) (reconnect-tva-cache-registry dirname (get-hl-store-caches-shared-symbols))) (warn "Cannot initialize HL KB object caches.")) t) (defun initialize-hl-store-cache-directory-and-shared-symbols (dirname &optional symbols) (if (directory-p dirname) (set-hl-store-caches-directory dirname) (warn "Do not have a valid location for the HL store caches; ~a is not accessible" dirname)) (if (directory-p (hl-store-caches-directory)) (progn (initialize-hl-store-cache-shared-symbols symbols) t) (warn "Could not initialize HL store caches from ~a." dirname)) nil) (defun initialize-hl-store-cache-shared-symbols (symbols) (unless symbols (on-error (setf symbols (load-kb-product-shared-symbols (hl-store-caches-directory))) (warn "Could not initialize shared symbols from ~a." (hl-store-caches-directory)))) (when symbols (setf *hl-store-caches-shared-symbols* symbols))) (defun hl-store-content-completely-cached? () (and (deduction-content-completely-cached?) (missing-larkc 32188))) (defun get-hl-store-cache-filename (filename extension) (concatenate 'string *hl-store-caches-directory* filename "." extension)) (defun set-hl-store-caches-directory (directory) (when (absolute-path? directory) (warn "HL Store directory being set to absolute directory ~a. Saved worlds will depend on this directory and may have problems running on other machines." directory)) (setf *hl-store-caches-directory* directory)) (defun hl-store-caches-directory () (or *hl-store-caches-directory* (and (not (force-monolithic-kb-assumption?)) (missing-larkc 30777)) *hl-store-caches-directory*)) (defun other-binary-arg (arg) ;; TODO - can be really optimized, but not sure this is used in any inner loops (case arg (1 2) (2 1))) (deflexical *hostname-caching-state* nil) (deflexical *machine-bogomips* :uninitialized) (defun machine-bogomips () "[Cyc] Return the processor speed of this machine in bogomips, or NIL if this can't be determined." (when (eq :uninitialized *machine-bogomips*) (setf *machine-bogomips* (compute-machine-bogomips))) *machine-bogomips*) (defun clear-machine-bogomips () (setf *machine-bogomips* :uninitialized)) (defun compute-machine-bogomips () (ignore-errors (with-open-file (stream "/proc/cpuinfo" :direction :input) ;; TODO - infinite loop if "bogomips" not found (loop for line = (read-line stream) when (search "bogomips" line) return (read-from-string (subseq line (1+ (search ":" line)))))))) (defun scale-by-bogomips (numbers bogomips) "[Cyc] Multiplies each number in NUMBERS by BOGOMIPS/(machine-bogomips). If this machine is faster than BOGOMIPS, NUMBERS will get smaller. If this amchine is slower than BOGOMIPS, NUMBERS will get bigger. If (machine-bogomips) is unknown, return NUMBERS unscaled." (let ((local-bogomips (machine-bogomips))) (if (or (null local-bogomips) (= local-bogomips bogomips)) numbers (let ((scaling-factor (/ bogomips local-bogomips))) (mapcar (lambda (number) (* scaling-factor number)) numbers))))) (defun* uninitialized () (:inline t) :uninitialized) (defun* uninitialized-p (object) (:inline t) (eq object (uninitialized))) (defun* initialized-p (object) (:inline t) (not (uninitialized-p object)))
9,792
Common Lisp
.lisp
198
45.79798
171
0.748166
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
711077ed4f3a6733566d9fa14e2ad09e348fb629742b5881408affb160c1c475
6,802
[ -1 ]
6,803
sbhl-link-vars.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-link-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (deflexical *sbhl-directions* '(:predicate :inverse :link) "[Cyc] Valid SBHL link directions.") (deflexical *sbhl-directed-directions* '(:predicate :inverse) "[Cyc] Valid SBHL link directions for SBHL directed links.") (deflexical *sbhl-forward-directed-direction* :predicate "[Cyc] Valid SBHL link direction for forward direction of sbhl-directed-links.") (deflexical *sbhl-forward-directed-direction-as-list* '(:predicate) "[Cyc] Valid SBHL link direction for forward direction of sbhl-directed-links as a list.") (deflexical *sbhl-backward-directed-direction* :inverse "[Cyc] Valid SBHL link direction for backward direction of sbhl-directed-links.") (deflexical *sbhl-backward-directed-direction-as-list* '(:inverse) "[Cyc] Valid SBHL link direction for backward direction of sbhl-directed-links as a list.") (deflexical *sbhl-undirected-direction* :link "[Cyc] Valid SBHL link direction for undirected links.") (deflexical *sbhl-undirected-direction-as-list* '(:link) "[Cyc] Valid SBHL link direction for undirected links in list form.") (defun sbhl-directed-direction-p (direction) "[Cyc] Is DIRECTION a member of *SBHL-DIRECTED-DIRECTIONS*?" (or (eq direction *sbhl-forward-directed-direction*) (eq direction *sbhl-backward-directed-direction*))) (defun* get-sbhl-directed-directions () (:inline t) "[Cyc] *sbhl-directed-directions*" *sbhl-directed-directions*) (defun* get-sbhl-forward-directed-direction () (:inline t) "[Cyc] The keyword for the forward direction of *SBHL-DIRECTED-DIRECTIONS*." *sbhl-forward-directed-direction*) (defun* sbhl-forward-directed-direction-p (direction) (:inline t) "[Cyc] Whether DIRECTION is the GET-SBHL-FORWARD-DIRECTED-DIRECTION." (eq direction (get-sbhl-forward-directed-direction))) (defun* get-sbhl-backward-directed-direction () (:inline t) "[Cyc] The keyword for the backward direction of *SBHL-DIRECTED-DIRECTIONS*." *sbhl-backward-directed-direction*) (defun* get-sbhl-undirected-direction () (:inline t) *sbhl-undirected-direction*) (defun* get-sbhl-undirected-direction-as-list () (:inline t) *sbhl-undirected-direction-as-list*) (defparameter *sbhl-link-direction* nil "[Cyc] Used to specify SBHL-LINK-DIRECTION.") (defun* get-sbhl-link-direction () (:inline t) *sbhl-link-direction*) (defun get-sbhl-opposite-link-direction () "[Cyc] Return the opposite direction for directed links. Undirected links still return undirected direction." (let ((direction (get-sbhl-link-direction))) (cond ((eq direction (get-sbhl-forward-directed-direction)) (get-sbhl-backward-directed-direction)) ((eq direction (get-sbhl-backward-directed-direction)) (get-sbhl-forward-directed-direction)) ((eq direction (get-sbhl-undirected-direction)) (get-sbhl-undirected-direction)) (t (when (sbhl-object-type-checking-p) (missing-larkc 2482)))))) (deflexical *sbhl-link-truth-values* (list #$MonotonicallyTrue #$DefaultTrue #$MonotonicallyFalse #$DefaultFalse) "[Cyc] Valid SBHL link truth values.") (deflexical *sbhl-true-link-truth-values* (list #$MonotonicallyTrue #$DefaultTrue)) (defun truth-strength-to-sbhl-tv (truth strength) "[Cyc] The #$HLTruthValue corresponding to TRUTH and STRENGTH." (cond ((and (eq truth :true) (eq strength :monotonic)) #$MonotonicallyTrue) ((and (eq truth :true) (eq strength :default)) #$DefaultTrue) ((and (eq truth :false) (eq strength :monotonic)) #$MonotonicallyFalse) ((and (eq truth :false) (eq strength :default)) #$DefaultFalse) ((eq truth :unknown) :unknown) (t (sbhl-error 1 "Could not compute an SBHL tv from ~s and ~s" truth strength)))) (defun support-tv-to-sbhl-tv (support-tv) "[Cyc] The #$HLTruthValue corresponding to SUPPORT-TV." (let ((truth (tv-truth support-tv)) (strength (tv-strength support-tv))) (truth-strength-to-sbhl-tv truth strength))) (defun sbhl-link-truth-value-p (truth) "[Cyc] Whether TRUTH is a member of *SBHL-LINK-TRUTH-VALUES*." (member? truth *sbhl-link-truth-values*)) (defun* sbhl-node-object-p (object) (:inline t) "[Cyc] Whether OBJECT has valid structure to be an SBHL node." (fort-p object)) (defun* sbhl-mt-object-p (object) (:inline t) "[Cyc] Whether OBJECT has valid structure to be an SBHL MT." (chlmt-p object)) (defparameter *sbhl-randomize-lists-p* nil "[Cyc] Determines whether to iterate over SBHL links in random order.") (defun* sbhl-randomize-lists-p () (:inline t) *sbhl-randomize-lists-p*) (defparameter *sbhl-link-mt* nil "[Cyc] Parameter for link MT, rebound during link iteration.") (defun* get-sbhl-link-mt () (:inline t) *sbhl-link-mt*) (defparameter *sbhl-link-tv* nil "[Cyc] Parameter for link tv, rebound during link iteration.") (defun* get-sbhl-link-tv () (:inline t) *sbhl-link-tv*) (defparameter *sbhl-link-generator* nil "[Cyc] Parameter for the saving the information for which function which was used to create the current link-node.") (deflexical *sbhl-rw-lock* (new-rw-lock "SBHL")) (defparameter *added-assertion* nil "obsolete") (defparameter *added-source* nil "obsolete")
6,859
Common Lisp
.lisp
135
45.296296
118
0.710625
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
528775e6ee10d79409153507828eb396f35392c2effdac99cd803ee2335c34ec
6,803
[ -1 ]
6,804
sbhl-marking-vars.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-marking-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *debug-sbhl-marking-spaces?* nil) (defun* average-genl-cardinality (&optional module) (:inline t) (declare (ignore module)) 100) (defun* average-spec-cardinality (&optional module) (:inline t) (declare (ignore module)) 3000) (defun get-sbhl-marking-space () (if (resourcing-sbhl-marking-spaces-p) (get-sbhl-resourced-marking-space) (instantiate-sbhl-marking-space))) (defun free-sbhl-marking-space (space) (when (resourcing-sbhl-marking-spaces-p) (update-sbhl-resourced-spaces space))) (defun instantiate-sbhl-marking-space () "[Cyc] Creates an SBHL-SPACE-P." (cond ((sbhl-forward-search-p) (make-hash-table :size (average-genl-cardinality) :test #'equal)) ((sbhl-backward-search-p) (make-hash-table :size (average-spec-cardinality) :test #'equal)) (t (make-hash-table :size (average-genl-cardinality) :test #'equal)))) (defparameter *resourcing-sbhl-marking-spaces-p* nil "[Cyc] Flag parameter to determine whether to resource SBHL spaces.") (defparameter *resourced-sbhl-marking-space-limit* nil "[Cyc] The maximal number of spaces to resource.") (defparameter *resourced-sbhl-marking-spaces* nil "[Cyc] The store of spaces that are being resourced.") (deflexical *default-resourced-sbhl-space-limit* 4 "[Cyc] The default number of spaces to resource.") (defun* resourcing-sbhl-marking-spaces-p () (:inline t) "[Cyc] Determines whether to resource SBHL marking spaces." *resourcing-sbhl-marking-spaces-p*) (defun* possibly-new-marking-resource (resourcing-p) (:inline t) (and resourcing-p *resourced-sbhl-marking-spaces*)) (defparameter *within-new-sbhl-marking-space-resource* nil) (defun new-sbhl-marking-space-resource (&optional num) "[Cyc] Returns a resource of SBHL marking spaces." (let ((default-num (or num 0)) (result nil)) (let ((*within-new-sbhl-marking-space-resource* t)) (dotimes (i default-num) (push (instantiate-sbhl-marking-space) result))) (nreverse result))) (defun determine-marking-space-limit (marking-resource) (let ((length (length marking-resource))) (if (eq length 0) *default-resourced-sbhl-space-limit* length))) (defun get-sbhl-resourced-marking-space () "[Cyc] Gets an available resourced SBHL-MARKING-SPACE, if one exists. If not, it creates one." (let ((result (first *resourced-sbhl-marking-spaces*))) (if result (progn (when *debug-sbhl-marking-spaces?* (unless (hash-table-empty-p result) (warn "Dirty resourced marking space being reused ~a!" result))) (pop *resourced-sbhl-marking-spaces*)) (setf result (instantiate-sbhl-marking-space))) result)) (defun update-sbhl-resourced-spaces (space) "[Cyc] Modifier. Pushes SPACE onto resourced spaces, unless they are over the limit." (if (length>= *resourced-sbhl-marking-spaces* *resourced-sbhl-marking-space-limit*) (when *debug-sbhl-marking-spaces?* (warn "Need more than the limit of ~a marking spaces." *resourced-sbhl-marking-space-limit*)) (progn (clear-sbhl-space space) (push space *resourced-sbhl-marking-spaces*)))) (defparameter *sbhl-space* nil "[Cyc] The current context for marking.") (defparameter *sbhl-gather-space* nil "[Cyc] The context used for gathering valid results in 3 part searches.") (defparameter *sbhl-disjoins-space* nil "[Cyc] A context name used for marking disjoins.") (defparameter *sbhl-space-0* nil "[Cyc] A variable to use for SBHL spaces.") (defparameter *sbhl-space-1* nil "[Cyc] A variable to use for SBHL spaces.") (defparameter *sbhl-space-2* nil "[Cyc] A variable to use for SBHL spaces.") (defparameter *sbhl-space-3* nil "[Cyc] A variable to use for SBHL spaces.") (defparameter *sbhl-space-4* nil "[Cyc] A variable to use for SBHL spaces.") (defparameter *sbhl-space-5* nil "[Cyc] A variable to use for SBHL spaces.") (defun sbhl-new-space-source () "[Cyc] Determine whether and where to get new spaces from." (cond ((sbhl-suspend-new-spaces?) :old) ((resourcing-sbhl-marking-spaces-p) :resource) (t :new))) (defun sbhl-get-new-space (source) "[Cyc] Get a new SBHL marking space from SOURCE." (case source (:resource (get-sbhl-resourced-marking-space)) (otherwise (instantiate-sbhl-marking-space)))) (defparameter *sbhl-suspend-new-spaces?* nil "[CYc] Toggle variable to suspend creation of new spaces during search.") (defun* sbhl-suspend-new-spaces? () (:inline t) "[Cyc] Whether to suspend creation of new spaces during search." *sbhl-suspend-new-spaces?*) (defparameter *sbhl-goal-space* nil "[Cyc] The space var used when goal nodes are premarked.") (defun* get-sbhl-goal-space () (:inline t) *sbhl-goal-space*) (defparameter *sbhl-target-space* nil "[Cyc] The space used when we want independent searches to make cross references.") (defparameter *sbhl-target-gather-space* nil "[CYc] The space used when we want independent searches to make cross references.") (defparameter *sbhl-terminating-marking-space* nil "[Cyc] The space var used to indicate where the marking of result nodes occurs.") (defparameter *sbhl-apply-marking-space* nil) (deflexical *sbhl-genl-preds-marking* (list #$genlPreds) "[Cyc] The marking for nodes only accessed in predicate mode during search.") (deflexical *sbhl-genl-inverse-marking* (list #$genlInverse) "[Cyc] The marking for nodes only accessed in argument-flipped mode during search.") (deflexical *sbhl-genl-preds-and-genl-inverse-marking* (list #$genlPreds #$genlInverse) "[Cyc] The marking for nodes accessed in both predicate argument-flipped modes and during search.") (deflexical *sbhl-genl-inverse-and-genl-preds-marking* (list #$genlInverse #$genlPreds) "[Cyc] The marking for nodes accessed in both predicate argument-flipped modes and during search.") (defun* genl-preds-marking-p (marking) (:inline t) "[Cyc] Whether MARKING indicates access only in predicate mode." (eq marking *sbhl-genl-preds-marking*)) (defun* genl-inverse-marking-p (marking) (:inline t) "[Cyc] Whether MARKING indicates access only in argument-flipped mode." (eq marking *sbhl-genl-inverse-marking*)) (defun* genl-preds-and-genl-inverse-marking-p (marking) (:inline t) "[Cyc] Whether MARKING indicates access in both predicate and argument-flipped mode." (or (eq marking *sbhl-genl-preds-and-genl-inverse-marking*) (eq marking *sbhl-genl-inverse-and-genl-preds-marking*))) (defparameter *sbhl-marking-generation* nil "[Cyc] The current marking generation.") (defparameter *sbhl-suspend-new-spaces-during-mapping?* nil "[Cyc] Toggle parameter for whether to suspend the creation of new search spaces during mapping.") (defun sbhl-suspend-new-spaces-during-mapping? () "[Cyc] Whether to suspend the creation of new search spaces during mapping." *sbhl-suspend-new-spaces-during-mapping?*) (defparameter *sbhl-mapping-marking-space* nil "[Cyc] Space nameholder for marking during mapping.") (defparameter *sbhl-mapping-gather-marking-space* nil "[Cyc] Space nameholder for marking during mapping.") (defparameter *sbhl-temporality-search-checks-nodes-in-target-space-p* nil "[Cyc] Parameter determining whether a time search checks markings in target space (for searching marked nodes).") ;; TODO - this value string from the java probably was a docstring in the lisp. Setting it to NIL here instead, and moving the string value to the docstring position. (defparameter *sbhl-table* nil "[Cyc] Table used for public marking interface.") (defparameter *sbhl-goal-table* nil "[Cyc] The table var used when goal nodes are premarked.")
9,286
Common Lisp
.lisp
183
46.202186
166
0.727222
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bad8d97690a1a7f5974c632d0bce55a5f9d365b3a87948bab63a64540ef2212a
6,804
[ -1 ]
6,805
sbhl-paranoia.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-paranoia.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# ;; A bunch of checking, debug reporting, & error handling stuff for the sbhl layer (in-package :clyc) (defparameter *sbhl-object-type-checking-p* t "[Cyc] Parameter that governs whether we perform work within SBHL-CHECK-TYPE.") (defun* sbhl-object-type-checking-p () (:inline t) ;; TODO - the cyc comments use "accessor" when they mean "reader" which goes against the CLHS definition. "[Cyc] The boolean value of *SBHL-OBJECT-TYPE-CHECKING-P*." (or *sbhl-object-type-checking-p* (not (suspend-sbhl-type-checking?)))) (defparameter *sbhl-type-error-action* :error "[Cyc] Parameter that guides error behavior.") (defparameter *sbhl-trace-level* 1 "[Cyc] Controls extent of tracing, warnings, etc., for the sbhl modules [0 .. 5].") (defun sbhl-error (level format-str &rest args) "[Cyc] If *SBHL-TRACE_LEVEL* si greater than or equal to LEVEL, signal a cerror with FORMAT-STR. If *SBHL-TRACE_LEVEL* is within 2 of LEVEL, warn with FORMAT-STR." (cond ((>= *sbhl-trace-level* level) (apply #'cerror "Continue anyway" args)) ((>= (+ 2 *sbhl-trace-level*) level) (apply #'warn format-str args)))) (defun sbhl-cerror (level continue-str format-str &rest args) "[Cyc] If *SBHL-TRACE-LEVEL* is greater than or equal to LEVEL, signal a cerror with CONTINUE-STR and FORMAT-STR. If *SBHL-TRACE-LEVEL* is within 2 of LEVEL, warn with FORMAT-STR." (cond ((>= *sbhl-trace-level* level) (apply #'cerror continue-str format-str args)) ((>= (+ 2 *sbhl-trace-level*) level) (apply #'warn format-str args)))) (defun sbhl-warn (level format-str &rest args) "[Cyc] If *SBHL-TRACE-LEVEL* is greater than or equal to LEVEL, warn with FORMAT-STR." (when (>= *sbhl-trace-level* level) (apply #'warn format-str args))) (defun suspend-sbhl-type-checking? () (or *suspend-type-checking?* *suspend-sbhl-type-checking?* (some-fort-being-removed?) *within-unassert*)) (defparameter *sbhl-test-level* 3 "[Cyc] Controls extent of integrity testing for teh sbhl modules [0 .. 5].") (defparameter *sbhl-test-max?* nil "[Cyc] Controls very expensive sbhl testing.") (defparameter *sbhl-trace-max?* nil "[Cyc] Controls very expensive sbhl tracing.") (defparameter *suppress-sbhl-recaching?* nil "[Cyc] Suppress retyping of forts iff this is non-NIL.") (defparameter *suspend-sbhl-cache-use?* nil "[Cyc] Suppress use of fort types, and call the SBHL instead. This should be set to NIL during for types initialization.") (defun check-sbhl-caches? () (and *suspend-sbhl-cache-use?* (sbhl-caches-initialized-p))) ;; TODO DESIGN - maybe an option to disable typechecking at compilation time, too ;; Expansion taken from multiple instances in sbhl-module-vars ;; This macro used to contain the following function body inside it. ;; To me, that's a waste of instruction cache, so we'll just macro the check, and call when it's enabled. ;; Disablable error handling doesn't need to be fast anyway, as long as the inline portion of the check is small. (defmacro sbhl-check-type (object type-test &optional (level 1)) `(when (and (sbhl-object-type-checking-p) (,type-test ,object)) (sbhl-handle-type-check-failure ,object ',type-test ,level))) (defun sbhl-handle-type-check-failure (object type-test level) ;; TODO - this is kind of dumb. Can't we register a function instead of a keyword? (case *sbhl-type-error-action* (:error (sbhl-error level "~a is not a ~a." object type-test)) ;; TODO - is this supposed to be sbhl-cerror? it does exist (:cerror (missing-larkc 2198)) (:warn (warn "~a is not a ~a." object type-test)) (otherwise (warn "~a is not a valid *SBHL-TYPE-ERROR-ACTION* value." *sbhl-type-error-action*) (cerror "Continue anyway" "~a is not a ~a." object type-test))))
5,201
Common Lisp
.lisp
95
51.084211
182
0.726305
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
deaf2a8f11c9430c4c89fda46fcf43c77665de59d401ee873778e382d8cdccbd
6,805
[ -1 ]
6,806
sbhl-module-vars.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-module-vars.lisp
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; TODO DESIGN - it seems like modules used to be dictionaries in the past, as comments make reference to that. Since the get/set property functions cherry pick those slots listed in the struct, and defer the rest to a hashtable, the whole thing was probably in a hashtable and the comments are out of date. However, should still verify that there are no hashtable-based functions around. (defstruct (sbhl-module (:conc-name "SBHL-MOD-")) link-pred accessible-link-preds graph link-style index-arg module-type type-test path-terminating-mark-fn marking-fn unmarking-fn var-bindings misc-properties) (defun new-sbhl-module (pred) (let ((module (make-sbhl-module))) (setf (sbhl-mod-link-pred module) pred) (setf (sbhl-mod-misc-properties module) (make-hash-table :test #'eq)))) (defun set-sbhl-module-property (module property value) (sbhl-check-type property sbhl-module-property-p) (sbhl-check-type module sbhl-module-p) (case property (:link-pred (setf (sbhl-mod-link-pred module) value)) (:accessible-link-preds (setf (sbhl-mod-accessible-link-preds module) value)) (:graph (setf (sbhl-mod-graph module) value)) (:link-style (setf (sbhl-mod-link-style module) value)) (:index-arg (setf (sbhl-mod-index-arg module) value)) (:module-type (setf (sbhl-mod-module-type module) value)) (:type-test (setf (sbhl-mod-type-test module) value)) ;; TODO DESIGN - the question mark here is inconsistent with the slot name, but is present throughout the keyword slot name interface. Change this to the same name as the slot. (:path-terminating-mark?-fn (setf (sbhl-mod-path-terminating-mark-fn module) value)) (:marking-fn (setf (sbhl-mod-marking-fn module) value)) (:unmarking-fn (setf (sbhl-mod-unmarking-fn module) value)) (otherwise (setf (gethash property (sbhl-mod-misc-properties module)) value)))) (defun get-sbhl-module-property (module property) (sbhl-check-type module sbhl-module-p) (case property (:link-pred (sbhl-mod-link-pred module)) (:accessible-link-preds (sbhl-mod-accessible-link-preds module)) (:graph (sbhl-mod-graph module)) (:link-style (sbhl-mod-link-style module)) (:index-arg (sbhl-mod-index-arg module)) (:module-type (sbhl-mod-module-type module)) (:type-test (sbhl-mod-type-test module)) (:path-terminating-mark?-fn (sbhl-mod-path-terminating-mark-fn module)) (:marking-fn (sbhl-mod-marking-fn module)) (:unmarking-fn (sbhl-mod-unmarking-fn module)) (otherwise (gethash property (sbhl-mod-misc-properties module))))) ;; TODO - the java had broken comments that failed to describe the actual slots (symbol-mapping get-sbhl-module-link-pred sbhl-mod-link-pred get-sbhl-module-accessible-link-preds sbhl-mod-accessible-link-preds get-sbhl-module-graph sbhl-mod-graph get-sbhl-module-link-style sbhl-mod-link-style get-sbhl-module-index-arg sbhl-mod-index-arg get-sbhl-module-module-type sbhl-mod-module-type get-sbhl-module-type-test sbhl-mod-type-test ;; TODO - this is a slight inconsistency in naming get-sbhl-module-terminating-mark sbhl-mod-terminating-mark-fn get-sbhl-module-marking-fn sbhl-mod-marking-fn get-sbhl-madule-unmarking-fn sbhl-mod-unmarking-fn) (defconstant *sbhl-module-key-test* #'eq) (defglobal *sbhl-modules* (make-hash-table :test *sbhl-module-key-test*) "[Cyc] Dictionary of SBHL modules, built up by module declaration.") (defun* sbhl-module-object-p (object) (:inline t) "[Cyc] Whether OBJECT is a DICTIONARY-P." ;; TODO - hashtable comment (sbhl-module-p object)) (defun reset-sbhl-modules () (setf *sbhl-modules* (make-hash-table :test *sbhl-module-key-test*))) (defun* get-sbhl-modules () (:inline t) "[Cyc] Return a hashtable of the defined SBHL modules, which each correspond directly to a link table." *sbhl-modules*) (defun add-sbhl-module (predicate module) "[Cyc] Enters MODULE into *SBHL-MODULES*. Assumes *SBHL-MODULES* is a hashtable. Checks that MODULE-KEY is a fort-p, and MODULE_DATA is a hashtable-p." ;; TODO - hashtable comment (sbhl-check-type predicate sbhl-predicate-object-p) (sbhl-check-type module sbhl-module-object-p) (setf (gethash predicate *sbhl-modules*) module)) (defun* get-sbhl-predicates-int () (:inline t) "[Cyc] Returns a list of the defined sbhl predicates." (hash-table-keys (get-sbhl-modules))) (defun* get-sbhl-module-list () (:inline t) "[Cyc] Return what the SBHL module structures that the predicates point to." ;; TODO - bad comment grammar (hash-table-values (get-sbhl-modules))) (defun* sbhl-predicate-object-p (object) (:inline t) "[Cyc] Type test for candidate sbhl-predicates." (fort-p object)) (deflexical *sbhl-module-types* '(:simple-reflexive :simple-non-reflexive :transfers-through :disjoins :time) "[Cyc] Roles that SBHL modules play in the grand SBHL scheme.") (defun* sbhl-simple-reflexive-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is of the simple transitive and reflexive variety." (eq module-type :simple-reflexive)) (defun* sbhl-simple-non-reflexive-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is of the simple transitive but irreflexive variety." (eq module-type :simple-non-reflexive)) (defun* sbhl-transfers-through-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is the keyword for transfers-through sbhl modules." (eq module-type :transfers-through)) (defun* sbhl-disjoins-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is the keyword for disjoins sbhl modules." (eq module-type :disjoines)) (defun* sbhl-time-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is the keyword for sbhl time modules." (eq module-type :time)) (defun* sbhl-transitive-module-type-p (module-type) (:inline t) "[Cyc] Returns whether MODULE-TYPE is the keyword for simple sbhl modules, or for sbhl time modules." (case module-type ((:simple-reflexive :simple-non-reflexive :time) t))) (defglobal *sbhl-module-properties* (make-hash-table :test #'eq) "[Cyc] The list of properties available for each of the *SBHL-MODULES*. Each key is a keyword. Each value field should be a functionp, corresponding for the test function for the sbhl module property associated with the key.") (defun init-sbhl-module-properties (property-list) "[Cyc] Modifier. Used to store initial values fo rthe *SBHL-MODULE-PROPERTIES*." ;; TODO DESIGN - this is a ((key val) (key val) ..) list, not a plist (dolist (property-test-pair property-list) (setf (gethash (first property-test-pair) *sbhl-module-properties*) (second property-test-pair)))) (defun sbhl-module-property-p (property) "[Cyc] Returns whether PROPERTY is a member of *SBHL-MODULE-PROPERTIES*." (gethash property *sbhl-module-properties*)) (deflexical *sbhl-module-required-properties* (list :link-pred :link-style :module-type ;; TODO DESIGN - another question mark :path-terminating-mark?-fn :marking-fn :unmarking-fn :index-arg :graph) "[Cyc] The list of required properties for each of the *SBHL-MODULES*.") (defparameter *sbhl-module* nil "[Cyc] The current sbhl-module in use for link traversal.") (defun get-sbhl-module (&optional predicate) "[Cyc] Return the SBHL module for PREDICATE. Defaults to *SBHL-MODULE*." (cond ((not predicate) *sbhl-module*) ((and (sbhl-module-p *sbhl-module*) (eq predicate (get-sbhl-link-pred *sbhl-module*))) *sbhl-module*) (t (let ((module (gethash predicate (get-sbhl-modules)))) (or module (sbhl-warn 0 "~a is not a valid SBHL-PREDICATE-P" predicate)))))) (defvar *sbhl-module-vars* nil "[Cyc] The parameters bound with each SBHL module.") (deflexical *fort-denoting-sbhl-directed-graph* #$DirectedMultigraph "[Cyc] The fort which is used to determine whether a predicate has directed links.") (deflexical *fort-denoting-sbhl-undirected-graph* #$Multigraph "[Cyc] The fort which is used to determine whether a predicate has undirected links.") (defun fort-denotes-sbhl-directed-graph-p (fort) (cond ((eq fort *fort-denoting-sbhl-directed-graph*) t) ((eq fort *fort-denoting-sbhl-undirected-graph*) nil) ;; The original had a weird usage where the error was in the test field (t (sbhl-error 1 "Term, ~a, is not used to specify directed nor undirected graphs.")))) (defparameter *assume-sbhl-extensions-nonempty* t "[Cyc] Assumption made for a collection, predicate, etc. that has no known extent. The two possible values are T (assume nonempty) and NIL (assume nothing).") (defun clean-sbhl-modules () (dohash (key module (get-sbhl-modules)) (let ((predicate (get-sbhl-link-pred module))) (unless (valid-fort? predicate) (missing-larkc 2755))))) ;; Elided all the dictionary optimization stuff, as we don't use alists anymore
11,008
Common Lisp
.lisp
194
49.876289
389
0.695773
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ab1e2d83ee7b457e5656a7e1497e932f6d67eb7c5d5bc4b75b6bbbf18f7b73eb
6,806
[ -1 ]
6,807
sbhl-macros.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-macros.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defun do-sbhl-non-fort-links? (node module) (and (eq module (get-sbhl-module #$isa)) (collection-supports-non-fort-instances? node))) (defun* collection-supports-non-fort-instances? (col) (:inline t) t) (defun get-sbhl-accessible-modules (module) "[Cyc] Returns the list of SBHL modules allowed by MODULE for following links." (if-let ((preds (get-sbhl-accessible-link-preds module))) (mapcar #'get-sbhl-module preds) (list module)))
1,857
Common Lisp
.lisp
37
46.837838
81
0.767222
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b28d3514084d691d5c0d3fdf3aa96eb16f25cbc7f2be468f52007a29e0718ec3
6,807
[ -1 ]
6,808
sbhl-search-vars.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-search-vars.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) (defparameter *sbhl-search-types* (list :closure :boolean :what-mts) "[Cyc] Different types of search, leading to different behaviors.") (defparameter *sbhl-search-type* nil "[Cyc] The current type of search. Governs how each search node is used during search.") (defun* get-sbhl-search-type () (:inline t) *sbhl-search-type*) (defun* sbhl-boolean-search-p () (:inline t) "[Cyc] Whether search type indicates boolean search." (eq (get-sbhl-search-type) :boolean)) (defparameter *sbhl-justification-search-p* nil "[Cyc] Does the current boolean search show the path that allowed success to be concluded?") (defun* sbhl-justification-search-p () (:inline t) "[Cyc] Whether current search is one that gathers justifications." *sbhl-justification-search-p*) (defparameter *sbhl-search-behavior* nil "[Cyc] The current search's entry function.") (defun* get-sbhl-search-behavior () (:inline t) *sbhl-search-behavior*) (defparameter *sbhl-justification-behavior* :old "[Cyc] The current behavior used for assembling sbhl-justifications, and determining how their returns will appear.") (defun* get-sbhl-just-behavior () (:inline t) *sbhl-justification-behavior*) (defparameter *sbhl-justification-defaulted-old* nil "[Cyc] Parameter used to indicate when justification was coerced and requires old justification behavior.") (defparameter *sbhl-justification-assembled-p* nil "[Cyc] Has the justification path already been assembled?") (defun* sbhl-justification-assembled-p () (:inline t) *sbhl-justification-assembled-p*) (defparameter *sbhl-unmarking-search-p* nil "[Cyc] Is current search an unmarking search?") (defun* sbhl-unmarking-search-p () (:inline t) *sbhl-unmarking-search-p*) (defparameter *sbhl-search-module* nil "[Cyc] The module initiating the current search.") (defun* get-sbhl-search-module () (:inline t) (let ((val *sbhl-search-module*)) (unless val (warn "GET-SBHL-SEARCH-MODULE: *SBHL-SEARCH-MODULE* is unexpectedly null.")) val)) (defparameter *sbhl-search-module-type* nil "[Cyc] The module type of the current search module.") (defun* get-sbhl-search-module-type () (:inline t) *sbhl-search-module-type*) (defparameter *sbhl-add-node-to-result-test* nil "[Cyc] The function used to govern adding nodes to the result during search.") (defun* get-sbhl-search-add-node-test () (:inline t) "[Cyc] The function applied to a node's marking before pushing correctly marked nodes onto result. Determined by current *SBHL-SEARCH-MODULE*." *sbhl-add-node-to-result-test*) (defparameter *sbhl-add-unmarked-node-to-result-test* nil "[Cyc] The function used to govern adding nodes to the result of an unmarking search.") (defun* get-sbhl-search-add-unmarked-node-test () (:inline t) "[Cyc] The function applied to a node's marking before pushing unmarked nodes onto result. Determined by current *SBHL-SEARCH-MODULE*." *sbhl-add-unmarked-node-to-result-test*) (defparameter *genl-inverse-mode-p* nil "[Cyc] Whether current search state has argument order flipped from search's initial order.") (defun* genl-inverse-mode-p () (:inline t) *genl-inverse-mode-p*) (defun* not-genl-inverse-mode-p () (:inline t) "[Cyc] Opposite of *sbhl-genl-inverse-mode-p*" (not *genl-inverse-mode-p*)) (defun sbhl-module-flips-inverse-mode-p (&optional (sbhl-module (get-sbhl-module))) (let ((pred (get-sbhl-link-pred sbhl-module))) (or (eq pred #$genlInverse) (eq pred #$negationInverse)))) (defun flip-genl-inverse-mode? (&optional (sbhl-module (get-sbhl-module)) (sbhl-search-module (get-sbhl-search-module))) (and (sbhl-module-indicates-predicate-search-p sbhl-search-module) (sbhl-module-flips-inverse-mode-p sbhl-module))) ;; TODO - not defconstant? (deflexical *sbhl-forward-search-direction* :forward "[Cyc] The keyword specifying forward search") (defun* sbhl-forward-search-direction-p (direction) (:inline t) "[Cyc] Whether SBHL search direction is forward" (eq direction *sbhl-forward-search-direction*)) (defun* get-sbhl-forward-search-direction () (:inline t) *sbhl-forward-search-direction*) ;; TODO - not defconstant? (deflexical *sbhl-backward-search-direction* :backward "[Cyc] The keyword specifying backward search.") (defun* sbhl-backward-search-direction-p (direction) (:inline t) "[Cyc] Whether SBHL search direction is backward" (eq direction *sbhl-backward-search-direction*)) (defun* get-sbhl-backward-search-direction () (:inline t) *sbhl-backward-search-direction*) (defparameter *sbhl-search-direction* nil "[Cyc] The direction of current search") (defun* get-sbhl-search-direction () (:inline t) *sbhl-search-direction*) (defun* sbhl-forward-search-p () (:inline t) "[Cyc] Whether the *SBHL-SEARCH-DIRECTION* is forward." (sbhl-forward-search-direction-p *sbhl-search-direction*)) (defun* sbhl-backward-search-p () (:inline t) "[Cyc] Whether the *SBHL-SEARCH-DIRECTION* is backward." (sbhl-backward-search-direction-p *sbhl-search-direction*)) ;; TODO - deprecate (defparameter *sbhl-index-arg* nil "[Cyc] Obsolete.") (defparameter *sbhl-search-index-arg* nil "[Cyc] The index arg for current search.") (defparameter *sbhl-map-function* nil "[Cyc] The recursive winding function of current search.") (defun* get-sbhl-map-function () (:inline t) *sbhl-map-function*) (defparameter *sbhl-unwind-function* nil "[Cyc] The function applied during recursive unwind.") (defun* get-sbhl-unwind-function () (:inline t) *sbhl-unwind-function*) (defparameter *sbhl-apply-unwind-function-p* nil "[Cyc] Toggle determining whether to apply *SBHL-UNWIND-FUNCTION*.") (defun* sbhl-apply-unwind-function-p () (:inline t) *sbhl-apply-unwind-function-p*) (defun* sbhl-toggle-unwind-function-on () (:inline t) "[Cyc] Sets to T *SBHL-APPLY-UNWIND-FUNCTION-P*." (setf *sbhl-apply-unwind-function-p* t)) (defparameter *sbhl-search-parent-marking* nil "[Cyc] The current node's parent marking.") (defun* set-sbhl-search-parent-marking (marking) (:inline t) "[Cyc] Sets *SBHL-SEARCH-PARENT-MARKING* to MARKING." (setf *sbhl-search-parent-marking* marking)) (defparameter *sbhl-nodes-previous-marking* nil "[Cyc] Previous marking of node.") (defparameter *sbhl-finished?* nil "[Cyc] Stores whether sbhl search is finished and if so, how.") (defun* sbhl-finished-with-goal () (:inline t) "[Cyc] Sets *SBHL-FINISHED?* to :GOAL. Used to specify that an SBHL search terminated upon reaching its goal condition." (setf *sbhl-finished?* :goal)) (defparameter *sbhl-stop-search-path?* nil "[Cyc] Stop mark and sweep from going further.") (defun* sbhl-stop-search-path-p () (:inline t) "[Cyc] Whether to stop the current search path." *sbhl-stop-search-path?*) (defun* sbhl-stop-search-path () (:inline t) (setf *sbhl-stop-search-path?* t)) (defparameter *sbhl-target-node* nil "[Cyc] The target node for current search.") (defparameter *sbhl-goal-node* nil "[Cyc] The goal node for current search.") (defun* sbhl-goal-node-p (node) (:inline t) "[Cyc] Whether NODE is equal to *sbhl-goal-node*" (eq node *sbhl-goal-node*)) (defun* get-sbhl-goal-node () (:inline t) *sbhl-goal-node*) (defparameter *sbhl-goal-nodes* nil "[Cyc] The goal nodes for current search for any goal.") (defun* get-sbhl-goal-nodes () (:inline t) "[Cyc] The current goal nodes." *sbhl-goal-nodes*) (defparameter *sbhl-isa?-goal* nil "[Cyc] The goal node for current search.") (defparameter *sbhl-result* nil "[Cyc] The result in search.") (defparameter *sbhl-justification-result* nil "[Cyc] The result in justification searches.") (defparameter *sbhl-consider-node-fn* nil "[Cyc] Function applied to each node during closure searches.") (defun* get-sbhl-consider-node-fn () (:inline t) *sbhl-consider-node-fn*) (defparameter *sbhl-compose-fn* nil "[Cyc] Function applied to each node during closure searches.") (defun* get-sbhl-compose-fn () (:inline t) *sbhl-compose-fn*) (defparameter *sbhl-combine-fn* #'nconc "[Cyc] Function applied to each node during closure searches.") (defparameter *sbhl-map-test-fn* nil "[Cyc] Function applied to each node during closure searches.") (defparameter *sbhl-accessed-gather-nodes* nil "[Cyc] The nodes upon which a gather has already been performed.") (defparameter *sbhl-dependents-cut-node* nil "[Cyc] The source node in dependent searches.") (defparameter *sbhl-access-arg* nil "[Cyc] The arg accessed in current SBHL mapping. Used for checking validity of terms within an arg position of a predicate.") (defparameter *sbhl-referent* nil "[Cyc] Variable that can be used for comparison during SBHL searched.") (defparameter *sbhl-current-leaf-queue* nil "[Cyc] Current search path during sample leaves search. Path is saved if successful.") (defparameter *sbhl-sample-leaf-queues* nil "[Cyc] The list of queues guiding sample leaf searches.") (defun* sbhl-leaf-sample-search-p () (:inline t) "[Cyc] Uses *sbhl-sample-leaf-queues* to answer whether current search is one that uses the leaf queues." *sbhl-sample-leaf-queues*) (defparameter *sbhl-extremal-test-fn* nil "[Cyc] Function used to test extremal nodes.") (defparameter *sbhl-check-for-goal-marking-p* nil "[Cyc] Whether to check whether a node is marked as :goal before checking other marking in search path termination.") (defun* sbhl-check-for-goal-marking-p () (:inline t) *sbhl-check-for-goal-marking-p*) (defparameter *sbhl-precomputed-goal-space* nil "[Cyc] The space bound for marking successful paths in repeated boolean searches.") (defparameter *infer-nat-sbhl?* t "[Cyc] Permit isa module to infer isa/genls of reified nats from result-type of functor?") ;; TODO - deprecate (defparameter *sbhl-mapping-pred* nil "[Cyc] Obsolete.") ;; TODO - deprecate (defparameter *maximize-sbhl-result?* nil "[Cyc] Obsolete.") ;; TODO - deprecate (defparameter *minimize-sbhl-result?* t "Obsolete.") (defparameter *sbhl-search-truth* nil "[Cyc] Used to determine whether the search is true or false.") (defun* sbhl-true-search-p () (:inline t) "[Cyc] Whether *SBHL-TV* generalizes to #$True-JustificationTruth. See SBHL-TV-GENERALIZES-TO-GENERAL-TV?" (sbhl-true-tv-p *sbhl-search-truth*)) (deflexical *sbhl-search-truth-values* (list #$MonotonicallyTrue #$DefaultTrue #$MonotonicallyFalse #$DefaultFalse #$True-JustificationTruth #$False-JustificationTruth #$ArbitraryTruth-JustificationTruth) "[Cyc] Valid SBHL truth values for searching.") (defun sbhl-search-truth-value-p (truth) "[Cyc] Whether TRUTH is a member of *SBHL-SEARCH-TRUTH-VALUES*." (member? truth *sbhl-search-truth-values*)) (deflexical *sbhl-true-tv* #$True-JustificationTruth "[Cyc] The encompassing true truth for searches.") (deflexical *sbhl-false-tv* #$False-JustificationTruth "[Cyc] The encompassing false truth for searches.") (defun* get-sbhl-true-tv () (:inline t) "[Cyc] The encompassing true truth." *sbhl-true-tv*) (defun* get-sbhl-false-tv () (:inline t) "[Cyc] The encompassing false truth." *sbhl-false-tv*) (defparameter *sbhl-tv* #$True-JustificationTruth "[Cyc] Search parameter.") (defun* get-sbhl-tv () (:inline t) "[Cyc] The truth relevance for the current search." *sbhl-tv*) (defparameter *relevant-sbhl-tv-function* nil "[Cyc] The truth relevance function for the current search.") (defun sbhl-tv-generalizes-to-general-tv? (tv general-tv) "[Cyc] Whether TV is subsumed by GENERAL-TV." (or (eq tv general-tv) ;; TODO READER - #$ returns an expression to be evaluated, so can't use it in CASE! (case tv (#$MonotonicallyTrue (or (eq general-tv #$DefaultTrue) (eq general-tv #$True-JustificationTruth) (eq general-tv #$ArbitraryTruth-JustifactionTruth))) (#$DefaultTrue (or (eq general-tv #$True-JustificationTruth) (eq general-tv #$ArbitraryTruth-JustificationTruth))) (#$True-JustificationTruth (eq general-tv #$ArbitraryTruth-JustificationTruth)) (#$MonotonicallyFalse (or (eq general-tv #$DefaultFalse) (eq general-tv #$False-JustificationTruth) (eq general-tv #$JustifactionTruth))) (#$DefaultFalse (or (eq general-tv #$False-JustificationTruth) (eq general-tv #$ArbitraryTruth-JustificationTruth))) (#$False-JustificationTruth (eq general-tv #$ArbitraryTruth-JustificationTruth)) (#$Unknown-JustificationTruth (eq general-tv #$ArbitraryTruth-JustificationTruth))))) (defun* relevant-sbhl-tv-is-general-tv (tv) (:inline t) "[Cyc] Whether TV generalizes to *sbhl-tv*" (sbhl-tv-generalizes-to-general-tv? tv *sbhl-tv*)) (defun relevant-sbhl-tv? (tv) "[Cyc] Applies *RELEVANT-SBHL-TV-FUNCTION* to TV, or if no function is bound as default applies RELEVANT-SBHL-TV-IS-GENERAL-TV." (if *relevant-sbhl-tv-function* (funcall *relevant-sbhl-tv-function* tv) (relevant-sbhl-tv-is-general-tv tv))) (defun* sbhl-true-tv-p (tv) (:inline t) "[Cyc] Whether TV generalizes to #$True-JustificationTruth." (sbhl-tv-generalizes-to-general-tv? tv #$True-JustificationTruth)) (defun* sbhl-false-tv-p (tv) (:inline t) "[Cyc] Whether TV generalizes to #$False-JustificationTruth." (sbhl-tv-generalizes-to-general-tv? tv #$False-JustificationTruth)) (defun sbhl-opposite-tv (tv) "[Cyc] The truth value with same strength and opposite truth from TV." ;; TODO READER - #$ returns an expression to be evaluated, so can't use it in CASE! (case tv (#$MonotonicallyTrue #$MonotonicallyFalse) (#$DefaultTrue #$DefaultFalse) (#$MonotonicallyFalse #$MonotonicallyTrue) (#$DefaultFalse #$DefaultTrue) (#$True-JustificationTruth #$False-JustificationTruth) (#$False-JustificationTruth #$True-JustificationTruth) (#$ArbitraryTruth-JustificationTruth #$ArbitraryTruth-JustificationTruth) (otherwise (sbhl-check-type tv sbhl-search-truth-value-p) nil))) (defun sbhl-true-tv (tv) "[Cyc] The true truth value with same strength as TV." (cond ((sbhl-true-tv-p tv) tv) ((sbhl-false-tv-p tv) (sbhl-opposite-tv tv)) (t (sbhl-error 1 "Expected true or false sbhl truth value. tv: ~a~%" tv)))) (defun sbhl-false-tv (tv) "[Cyc] The false truth value with same strength as TV." (cond ((sbhl-false-tv-p tv) tv) ((sbhl-true-tv-p tv) (sbhl-opposite-tv tv)) (t (sbhl-error 1 "Expected true or false sbhl truth value. tv: ~a~%" tv)))) (defun* sbhl-search-true-tv () (:inline t) "[Cyc] The true truth value with same strength as *SBHL-TV*." (sbhl-true-tv *sbhl-tv*)) (defun* sbhl-search-false-tv () (:inline t) "[Cyc] The false truth value with same strength as *SBHL-TV*." (sbhl-false-tv *sbhl-tv*)) (defun sbhl-translate-to-old-tv (tv) "[Cyc] The keyword associated with TV, either :TRUE or :FALSE." (cond ((sbhl-true-tv-p tv) :true) ((sbhl-false-tv-p tv) :false) (t (sbhl-error 1 "Unknown truth value for translation: ~a" tv)))) (defun sbhl-possibly-translate-tv (tv) (if (or (eq tv :true) (eq tv :false)) tv (sbhl-translate-to-old-tv tv)))
17,077
Common Lisp
.lisp
342
45.131579
145
0.713152
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
278dd78b7528032f5a27b4fe78aff4cf431885793b4d64e1a69a5243cbe92bee
6,808
[ -1 ]
6,809
sbhl-search-datastructures.lisp
white-flame_clyc/larkc-cycl/sbhl/sbhl-search-datastructures.lisp
#| Copyright (c) 2019-2020 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file derives from work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :clyc) ;; This only constains structs, but given the filename and the minimal function declarations in the java declare function, this is probably by design. (defstruct sbhl-stack num elements) (defstruct sbhl-link-node-search-state node module direction mt tv parent-node genl-inverse-mode? link-generator)
1,719
Common Lisp
.lisp
40
39.9
150
0.785542
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
77240317dc3a72b1c3de3f7f8c9bc2e155c9181260e88dbbd69651a493984fc4
6,809
[ -1 ]
6,810
clyc.asd
white-flame_clyc/clyc.asd
#| Copyright (c) 2019 White Flame This file is part of Clyc Clyc is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Clyc is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with Clyc. If not, see <https://www.gnu.org/licenses/>. This file incorporates work covered by the following copyright and permission notice: Copyright (c) 1995-2009 Cycorp Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. |# (in-package :asdf-user) (defsystem "clyc" :name "clyc" :author "White Flame" :licence "GNU Affero General Public License, version 3" :description "Port of Cyc to Common Lisp" :depends-on ("alexandria" "bordeaux-threads" "flexi-streams" "named-readtables" "usocket-server") :serial t :components ((:file "subl-support") (:module "larkc-cycl" ;; The list of files is in order of initialization from the original cycl.java ;; 413 non-missing components included in larkc version. ;; Some files only have some vars or structs with no behavior, ;; but we can see tons of commented out functions in ;; its declarations. These files are elided instead of ;; taking up visual/conceptual space for now. ;; Dependency ordering is still completely bonkered. :components (;; MISSING-LARKC (:file "cyc-cvs-id") ;; ELIDED (:file "meta-macros") - too low level ;; ELIDED (:file "access-macros") - too low level ;; ELIDED (:file "subl-macro-promotions") - too low level (:file "subl-promotions") (:file "subl-macros") ;; ELIDED (:file "format-nil") - cl:format (:file "modules") (:file "cyc-revision-extraction") (:file "system-parameters" :depends-on ("system-info")) (:file "system-version") (:file "system-info" :depends-on ("system-version")) (:file "utilities-macros" :depends-on ("numeric-date-utilities")) ;; ELIDED (:file "timing") - mostly missing-larkc ;; MISSING-LARKC (:file "cyc-file-dependencies") ;; MISSING-LARKC (:file "cycml-macros") (:file "control-vars") ;; MISSING-LARKC (:file "sunit-macros") ;; MISSING-LARKC (:file "sunit-external") (:file "cfasl" :depends-on ("cfasl-compression")) ;; MISSING-LARKC (:file "sxhash-external") ;; MISSING-LARKC (:file "red-implementation") ;; ELIDED (:file "red-api") - basically missing-larkc (:file "cyc-testing") ;; Concatenation of: ;; (:file "cyc-testing.cyc-testing-initialization") ;; (:file "cyc-testing.cyc-testing") ;; (:file "cyc-testing.generic-testing") (:file "hash-table-utilities") ;; ELIDED (:file "keyhash") - use standard hashtables (:file "set-contents") ;; MISSING-LARKC (:file "reader-writer-locks") (:file "memoization-state" :depends-on ("cache")) (:file "list-utilities") (:file "transform-list-utilities") (:file "vector-utilities") (:file "string-utilities") ;; ELIDED (:file "unicode-strings") - CL unicode support ;; ELIDED (:file "unicode-subsets") - CL unicode support ;; MISSING-LARKC (:file "unicode-support") ;; ELIDED (:file "unicode-streams") - CL unicode support ;; MISSING-LARKC (:file "defstruct-sequence") ;; MISSING-LARKC (:file "visitation-utilities") ;; MISSING-LARKC (:file "mail-utilities") ;; ELIDED (:file "mail-message") - only structs (:file "number-utilities") ;; ELIDED (:file "fraction-utilities") - CL rationals ;; MISSING-LARKC (:file "matrix-utilities") (:file "numeric-date-utilities") (:file "iteration") (:file "binary-tree") (:file "stacks") (:file "queues") (:file "deck") (:file "integer-sequence-generator") ;; MISSING-LARKC (:file "semaphores") (:file "process-utilities") ;; possibly missing-larkc ;; ELIDED (:file "os-process-utilities") - make-os-process is missing-larkc (:file "tcp") ;; added, was part of native JRTL (:file "tcp-server-utilities") (:file "pattern-match") (:file "tries") ;; ELIDED (:file "shelfs") - basically missing-larkc (:file "id-index") ;; ELIDED (:file "dictionary-contents") - use hashtables ;; ELIDED (:file "dictionary") - use hashtables (:file "cfasl-compression") (:file "cfasl-utilities") ;; ELIDED (:file "bijection") ;; basically missing-larkc ;; ELIDED (:file "glob") - basically missing-larkc ;; ELIDED (:file "keyhash-utilities") - since keyhash is (:file "set") (:file "set-utilities") (:file "dictionary-utilities") (:file "map-utilities") ;; ELIDED (:file "bag") - basically missing-larkc ;; ELIDED (:file "accumulation") - basically missing-larkc ;; ELIDED (:file "red-infrastructure") - dependencies are missing-larkc ;; ELIDED (:file "red-infrastructure-macros") - dependencies are missing-larkc ;; MISSING-LARKC (:file "red-utilities") (:file "file-utilities") ;; ELIDED (:file "stream-buffer") - only structs, no funcs ;; ELIDED (:file "hierarchical-visitor") - only structs ;; MISSING-LARKC (:file "strie") ;; ELIDED (:file "finite-state-transducer") - only structs (:file "cache") (:file "cache-utilities") (:file "special-variable-state") ;; ELIDED (:file "simple-lru-cache-strategy") - mostly missing-larkc ;; ELIDED (:file "file-hash-table") - behavior missing-larkc. contained read-fht-uint4, replaced by read-32bit-be ;; MISSING-LARKC (:file "file-hash-table-utilities") (:file "file-vector") (:file "file-vector-utilities") ;; MISSING-LARKC (:file "generic-table-utilities") ;; MISSING-LARKC (:file "sdbc-macros") ;; ELIDED (:file "sdbc") - just vars & structss (:file "graph-utilities") ;; ELIDED (:file "sparse-vector") - just struct ;; ELIDED (:file "sparse-matrix") - just struct ;; ELIDED (:file "remote-image") - just struct ;; MISSING-LARKC (:file "cyc-testing.cyc-testing-utilities") ;; ELIDED (:file "heap") - just struct ;; MISSING-LARKC (:file "decision-tree") (:file "misc-utilities") ;; ELIDED (:file "web-utilities") - just vars & structs ;; MISSING-LARKC (:file "timing-by-category") ;; ---- Start of CYC itself. Above here is generally the basic SubL definition & stdlib (:file "api-control-vars") (:file "eval-in-api") ;;(:file "eval-in-api-registrations") ;; TODO - contains hundres of registrations for the API, but the API doesn't work because of missing-larkc stuff (:file "api-kernel") (:file "cfasl-kernel") ;; ELIDED (:file "guardian") - just struct. Likely a threaded watchdog of some sort. (:file "hl-interface-infrastructure") (:file "kb-macros") (:file "constant-handles") ;; moved up before completion tools (:file "constant-completion-low") (:file "constant-completion-interface") (:file "constant-completion-high") (:file "constant-completion") (:file "constant-reader") (:file "enumeration-types") (:file "kb-control-vars") (:file "mt-vars") (:file "graphl-search-vars") (:file "ghl-search-vars") ;; ELIDED (:file "sbhl/sbhl-iteration") - struct only (:file "sbhl/sbhl-paranoia") (:file "sbhl/sbhl-module-vars") (:file "sbhl/sbhl-link-vars") (:file "sbhl/sbhl-marking-vars") (:file "sbhl/sbhl-search-datastructures") (:file "sbhl/sbhl-search-vars") ;; MISSING-LARKC (:file "sbhl/sbhl-time-vars") ;; ELIDED (:file "sbhl/sbhl-link-iterators") - structs only (:file "at-vars") (:file "gt-vars") (:file "czer-vars") (:file "mt-relevance-macros") (:file "pred-relevance-macros") (:file "at-macros") ;; MISSING-LARKC (:file "czer-macros") (:file "wff-macros") (:file "wff-vars") ;; MISSING-LARKC (:file "gt-macros") ;; MISSING-LARKC (:file "hl-macros") (:file "obsolete") ;; MISSING-LARKC (:file "obsolete-macros") (:file "kb-mapping-macros") ;; ELIDED (:file "kb-access-metering") - mostly missing-larkc (:file "kb-object-manager") (:file "hlmt") (:file "hlmt-czer") (:file "constants-interface") (:file "constant-index-manager") (:file "constants-low") (:file "constants-high") (:file "nart-handles") ;; MISSING-LARKC (:file "narts-interface") (:file "nart-index-manager") (:file "nart-hl-formula-manager") ;; MISSING-LARKC (:file "narts-low") (:file "narts-high") (:file "forts") (:file "assertion-handles") (:file "assertions-interface") (:file "assertion-manager") (:file "assertions-low") (:file "assertions-high") (:file "kb-hl-support-manager") (:file "kb-hl-supports") (:file "deduction-handles") (:file "deductions-interface") (:file "deduction-manager") (:file "deductions-low") (:file "deductions-high") (:file "unrepresented-term-index-manager") (:file "unrepresented-terms") (:file "arguments") (:file "clause-strucs") (:file "variables") ;; MISSING-LARKC (:file "format-cycl-expression") (:file "hl-storage-modules") (:file "hl-modifiers") ;; MISSING-LARKC (:file "sxhash-external-kb") ;; MISSING-LARKC (:file "el-macros") (:file "sbhl/sbhl-macros") (:file "cycl-variables") (:file "el-utilities") (:file "clause-utilities") (:file "cycl-utilities") (:file "cycl-grammar") (:file "el-grammar") ;; MISSING-LARKC (:file "unicode-nauts") (:file "term") (:file "kb-indexing-datastructures") (:file "kb-utilities") (:file "simple-indexing") (:file "kb-indexing-declarations") (:file "kb-indexing-macros") (:file "kb-indexing") (:file "virtual-indexing") (:file "kb-mapping") (:file "kb-mapping-utilities") (:file "kb-gp-mapping") (:file "somewhere-cache") (:file "auxiliary-indexing") ;; MISSING-LARKC (:file "inferred-indexing") (:file "arity") (:file "kb-accessors") ;; MISSING-LARKC (:file "kb-iterators") (:file "function-terms") (:file "relation-evaluation") ;;(:file "assertion-utilities") ;; MISSING-LARKC (:file "parameter-specification-utilities") ;;(:file "clauses") ;;(:file "bindings") ;;(:file "unification") ;;(:file "unification-utilities") ;;(:file "file-backed-cache") ;;(:file "graphl-graph-utilities") ;; MISSING-LARKC (:file "ghl-graph-utilities") ;;(:file "ghl-link-iterators") ;;(:file "ghl-marking-utilities") ;;(:file "ghl-search-utilities") ;;(:file "sbhl/sbhl-graphs") ;;(:file "sbhl/sbhl-caching-policies") ;;(:file "sbhl/sbhl-module-utilities") ;;(:file "sbhl/sbhl-links") ;; MISSING-LARKC (:file "sbhl/sbhl-nat-utilities") ;;(:file "sbhl/sbhl-link-utilities") ;;(:file "sbhl/sbhl-link-methods") ;;(:file "sbhl/sbhl-marking-utilities") ;;(:file "sbhl/sbhl-search-utilities") ;;(:file "sbhl/sbhl-marking-methods") ;;(:file "sbhl/sbhl-search-methods") ;;(:file "sbhl/sbhl-search-what-mts") ;;(:file "sbhl/sbhl-search-implied-relations") ;;(:file "sbhl/sbhl-module-declarations") ;;(:file "genls") ;;(:file "disjoint-with") ;;(:file "sdc") ;;(:file "isa") ;;(:file "genl-predicates") ;;(:file "negation-predicate") ;;(:file "genl-mts") ;;(:file "mt-relevance-cache") ;;(:file "predicate-relevance-cache") ;; MISSING-LARKC (:file "negation-mt") ;;(:file "ghl-search-methods") ;;(:file "sbhl/sbhl-cache") (:file "fort-types-interface") ;;(:file "czer-trampolines") ;;(:file "wff-utilities") ;;(:file "wff-module-datastructures") ;; MISSING-LARKC (:file "wff-modules") ;;(:file "wff") ;; MISSING-LARKC (:file "wff-suggest") ;;(:file "simplifier") ;; MISSING-LARKC (:file "tersifier") ;;(:file "verbosifier") ;;(:file "czer-utilities") ;;(:file "precanonicalizer") ;;(:file "postcanonicalizer") ;;(:file "clausifier") ;; MISSING-LARKC (:file "prop-sentence-clausifier") ;;(:file "czer-graph") ;;(:file "czer-main") ;;(:file "rule-macros") ;;(:file "skolems") ;;(:file "czer-meta") ;;(:file "uncanonicalizer") ;;(:file "canon-tl") ;;(:file "at-routines") ;;(:file "at-utilities") ;;(:file "at-admitted") ;;(:file "at-defns") ;;(:file "defns") ;;(:file "at-var-types") ;;(:file "at-cache") ;;(:file "arg-type") ;; MISSING-LARKC (:file "applicable-relations") ;;(:file "sksi.sksi-infrastructure.sksi-macros") ;; MISSING-LARKC (:file "inference.janus-macros") ;;(:file "gt-utilities") ;;(:file "gt-search") ;;(:file "gt-methods") ;;(:file "transitivity") ;; MISSING-LARKC (:file "transfers-through") ;;(:file "tva-utilities") ;;(:file "tva-tactic") ;;(:file "tva-strategy") ;;(:file "tva-inference") ;;(:file "tva-cache") ;;(:file "equality-store") ;;(:file "equals") ;;(:file "rewrite-of-propagation") ;;(:file "hl-supports") ;; MISSING-LARKC (:file "conflicts") ;; MISSING-LARKC (:file "ebl") ;;(:file "preserves-genls-in-arg") ;;(:file "formula-pattern-match") ;;(:file "cfasl-kb-methods") ;;(:file "inference.harness.inference-macros") ;;(:file "inference.harness.inference-modules") ;;(:file "search") ;;(:file "tms") ;;(:file "inference.harness.after-adding") ;;(:file "inference.harness.rule-after-adding") ;;(:file "inference.modules.after-adding-modules") ;;(:file "inference.harness.argumentation") ;;(:file "backward") (:file "psc") ;;(:file "inference.inference-trampolines") ;;(:file "inference.inference-completeness-utilities") ;;(:file "backward-utilities") ;;(:file "backward-results") ;; MISSING-LARKC (:file "transformation-heuristics") ;;(:file "inference.inference-pad-data") ;;(:file "inference.modules.preference-modules") ;; MISSING-LARKC (:file "inference.modules.preference-module-declarations") ;;(:file "inference.harness.inference-datastructures-enumerated-types") ;;(:file "inference.harness.inference-datastructures-problem-store") ;;(:file "inference.harness.inference-datastructures-problem-query") ;;(:file "inference.harness.inference-datastructures-problem") ;;(:file "inference.harness.inference-datastructures-problem-link") ;;(:file "inference.harness.inference-datastructures-tactic") ;;(:file "inference.harness.inference-datastructures-proof") ;;(:file "inference.harness.inference-datastructures-strategy") ;;(:file "inference.harness.inference-datastructures-forward-propagate") ;;(:file "inference.harness.inference-datastructures-inference") ;;(:file "inference.harness.inference-czer") ;; MISSING-LARKC (:file "inference.harness.inference-proof-spec") ;; MISSING-LARKC (:file "inference.harness.inference-proof-spec-store") ;;(:file "inference.harness.inference-worker") ;;(:file "inference.harness.inference-worker-answer") ;;(:file "inference.harness.inference-worker-restriction") ;;(:file "inference.harness.inference-worker-removal") ;;(:file "inference.harness.inference-worker-transformation") ;;(:file "inference.harness.inference-worker-residual-transformation") ;;(:file "inference.harness.inference-worker-rewrite") ;;(:file "inference.harness.inference-worker-split") ;;(:file "inference.harness.inference-worker-join-ordered") ;;(:file "inference.harness.inference-worker-join") ;;(:file "inference.harness.inference-worker-union") ;;(:file "inference.harness.inference-tactician-strategic-uninterestingness") ;;(:file "inference.harness.inference-lookahead-productivity") ;;(:file "inference.harness.inference-min-transformation-depth") ;;(:file "inference.harness.inference-tactician") ;;(:file "inference.harness.inference-tactician-utilities") ;;(:file "inference.harness.inference-strategic-heuristics") ;;(:file "inference.harness.inference-balanced-tactician-datastructures") ;;(:file "inference.harness.inference-balanced-tactician-strategic-uninterestingness") ;;(:file "inference.harness.inference-balanced-tactician-motivation") ;;(:file "inference.harness.inference-balanced-tactician-execution") ;;(:file "inference.harness.inference-heuristic-balanced-tactician") ;;(:file "inference.harness.balancing-tactician") ;;(:file "inference.harness.removal-tactician-datastructures") ;;(:file "inference.harness.removal-tactician-uninterestingness") ;;(:file "inference.harness.removal-tactician-motivation") ;;(:file "inference.harness.removal-tactician-execution") ;;(:file "inference.harness.removal-tactician") ;;(:file "inference.harness.transformation-tactician-datastructures") ;; MISSING-LARKC (:file "inference.harness.transformation-tactician-uninterestingness") ;; MISSING-LARKC (:file "inference.harness.transformation-tactician-motivation") ;; MISSING-LARKC (:file "inference.harness.transformation-tactician-execution") ;; MISSING-LARKC (:file "inference.harness.transformation-tactician") ;;(:file "inference.harness.new-root-tactician-datastructures") ;; MISSING-LARKC (:file "inference.harness.new-root-tactician-motivation") ;; MISSING-LARKC (:file "inference.harness.new-root-tactician-execution") ;; MISSING-LARKC (:file "inference.harness.new-root-tactician") ;;(:file "neural-net") ;;(:file "inference.harness.inference-strategist") ;;(:file "inference.harness.inference-kernel") ;;(:file "inference.harness.inference-trivial") ;; MISSING-LARKC (:file "inference.harness.inference-utilities") ;;(:file "inference.harness.inference-parameters") ;;(:file "inference.harness.inference-metrics") ;;(:file "inference.harness.inference-analysis") ;; MISSING-LARKC (:file "inference.harness.inference-serialization") ;;(:file "cyc-testing.inference-unit-tests") ;;(:file "cyc-testing.removal-module-tests") ;;(:file "cyc-testing.transformation-module-tests") ;;(:file "cyc-testing.evaluatable-relation-tests") ;; MISSING-LARKC (:file "cyc-testing.inference-testing-helpers") ;; MISSING-LARKC (:file "cyc-testing.inference-testing") ;;(:file "cyc-testing.removal-module-cost-tests") ;; MISSING-LARKC (:file "inference.kb-query") ;;(:file "inference.kbq-query-run") ;;(:file "inference.arete") ;;(:file "inference.janus") ;;(:file "inference.leviathan") ;; MISSING-LARKC (:file "inference.deep-inference-generator") ;; MISSING-LARKC (:file "inference.lilliput") ;; MISSING-LARKC (:file "inference.lilliput-caches") ;;(:file "inference.ask-utilities") ;;(:file "inference.harness.removal-module-utilities") ;;(:file "inference.modules.removal.removal-modules-lookup") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-minimization") ;;(:file "inference.modules.removal.removal-modules-evaluation") ;;(:file "inference.modules.removal.removal-modules-symmetry") ;;(:file "inference.modules.removal.removal-modules-transitivity") ;;(:file "inference.modules.removal.removal-modules-reflexivity") ;;(:file "inference.modules.removal.removal-modules-reflexive-on") ;;(:file "inference.modules.removal.removal-modules-genlpreds-lookup") ;;(:file "inference.modules.removal.removal-modules-relation-all") ;;(:file "inference.modules.removal.removal-modules-relation-all-instance") ;;(:file "inference.modules.removal.removal-modules-relation-all-exists") ;;(:file "inference.modules.removal.removal-modules-relation-instance-exists") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-term-external-id-string") ;;(:file "inference.modules.removal.removal-modules-backchain-required") ;;(:file "inference.modules.removal.removal-modules-abduction") ;;(:file "inference.modules.removal.meta-removal-modules") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-non-wff") ;;(:file "inference.modules.removal.removal-modules-isa") ;;(:file "inference.modules.removal.removal-modules-genls") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-denotes") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-classification") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-subset-of") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-nearest-isa") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-disjointwith") ;;(:file "inference.modules.removal.removal-modules-termofunit") ;;(:file "inference.modules.removal.removal-modules-natfunction") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-formula-arg-n") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-equals") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-evaluate") ;;(:file "inference.modules.removal.removal-modules-different") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-genlmt") ;;(:file "inference.modules.removal.removal-modules-genlpreds") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-genlinverse") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-negationpreds") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-negationinverse") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-ist") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-consistent") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-admitted-formula") ;;(:file "inference.modules.removal.removal-modules-asserted-formula") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-asserted-arg1-binary-preds") ;;(:file "inference.modules.removal.removal-modules-function-corresponding-predicate") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-start-offset") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-true-sentence") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-formula-implies") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-asserted-more-specifically") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-isomorphic-sentences") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-conceptually-related") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-integer-between") ;;(:file "inference.modules.removal.removal-modules-indexical-referent") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-constant-name") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-assertion-mt") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-term-strings") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-perform-subl") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-term-chosen") ;;(:file "inference.modules.removal.removal-modules-tva-lookup") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-bookkeeping") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-rtv") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-member-of-list") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-assertion-arguments") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-deduction-supports") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-assertion-deductions") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-assertion-hl-asserted-argument-keyword") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-inference-reflection") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-known-antecedent-rule") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-distance-between") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-lat-long") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-country-of-city") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-kappa") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-interval-range") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-ke-useless-precision-value") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-kb-indexing") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-concatenate-strings") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-query-answers") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-set-of-list-with-same-member-in-pos") ;;(:file "inference.modules.removal.removal-modules-conjunctive-pruning") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-kb-sentence") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-source-sentence") ;;(:file "inference.modules.transformation-modules") ;;(:file "inference.modules.simplification-modules") ;;(:file "inference.modules.rewrite-modules") ;;(:file "inference.harness.forward") ;;(:file "inference.modules.forward-modules") ;; MISSING-LARKC (:file "inference.forward-propagate-assertions") ;;(:file "inference.harness.abnormal") ;;(:file "inference.harness.hl-prototypes") ;;(:file "inference.collection-intersection") ;;(:file "inference.harness.inference-abduction-utilities") ;; MISSING-LARKC (:file "abduction") ;;(:file "fi") ;;(:file "cyc-bookkeeping") ;;(:file "cyc-kernel") ;; MISSING-LARKC (:file "inference.harness.prove") ;; MISSING-LARKC (:file "inference.inference-iterators") ;;(:file "ke") ;; MISSING-LARKC (:file "api-remote-objects") ;; MISSING-LARKC (:file "batch-ke") ;; MISSING-LARKC (:file "inference.inference-viewer") ;; MISSING-LARKC (:file "plot-generation") ;;(:file "cardinality-estimates") ;; MISSING-LARKC (:file "relationship-generality-estimates") ;;(:file "evaluation-defns") ;;(:file "collection-defns") ;; MISSING-LARKC (:file "ke-utilities") ;; MISSING-LARKC (:file "ke-text") ;; MISSING-LARKC (:file "kb-ontology-utilities") ;; MISSING-LARKC (:file "ontology-layers") ;;(:file "system-benchmarks") ;; MISSING-LARKC (:file "object-similarity") ;; MISSING-LARKC (:file "partitions") ;; MISSING-LARKC (:file "convert-partitions") ;; MISSING-LARKC (:file "core") ;; MISSING-LARKC (:file "kbs-utilities") ;; MISSING-LARKC (:file "kbs-identification") ;; MISSING-LARKC (:file "kbs-add-redundant") ;; MISSING-LARKC (:file "kbs-partition") ;; MISSING-LARKC (:file "kbs-cleanup") ;; MISSING-LARKC (:file "kbs-compare") ;; MISSING-LARKC (:file "kb-cleanup") ;; MISSING-LARKC (:file "genls-hierarchy-problems") ;;(:file "encapsulation") ;;(:file "transcript-utilities") ;;(:file "transcript-server") ;;(:file "operation-communication") ;;(:file "operation-queues") ;; MISSING-LARKC (:file "remote-operation-filters") ;;(:file "user-actions") ;; MISSING-LARKC (:file "formula-template-vars") ;; MISSING-LARKC (:file "xml-vars") ;; MISSING-LARKC (:file "xml-macros") ;;(:file "agenda") ;;(:file "subl-identifier") ;; MISSING-LARKC (:file "query-utilities") ;;(:file "kb-compare") ;;(:file "kb-paths") ;; MISSING-LARKC (:file "ke-coherence") ;; MISSING-LARKC (:file "ke-tools") ;; MISSING-LARKC (:file "kb-filtering") ;;(:file "xml-utilities") ;;(:file "misc-kb-utilities") ;;(:file "scientific-numbers") ;; MISSING-LARKC (:file "scientific-number-utilities") ;; MISSING-LARKC (:file "extended-numbers") ;; MISSING-LARKC (:file "arithmetic") ;;(:file "hl-storage-module-declarations") ;;(:file "bookkeeping-store") ;;(:file "dumper") ;;(:file "builder-utilities") ;; MISSING-LARKC (:file "gt-modules") ;;(:file "task-processor") ;;(:file "java-api-kernel") ;; MISSING-LARKC (:file "connection-guarding") ;; MISSING-LARKC (:file "inference.open-cyc-simple-inference-api") ;; MISSING-LARKC (:file "term-classification-tree") ;; MISSING-LARKC (:file "cyc-testing.ctest-macros") ;;(:file "cyc-testing.ctest-utils") ;; MISSING-LARKC (:file "cyc-testing.kb-content-test.kct-variables") ;;(:file "cyc-testing.kb-content-test.kct-utils") ;; MISSING-LARKC (:file "cyc-testing.kb-content-test.kct-cyc-testing") ;; MISSING-LARKC (:file "cyc-testing.kb-content-test.kct-thinking") ;;(:file "cycl-query-specification") ;;(:file "new-cycl-query-specification") ;;(:file "formula-templates") ;;(:file "graphic-library-format") ;;(:file "value-tables") ;; MISSING-LARKC (:file "script-instance-editor-api") ;; MISSING-LARKC (:file "similarity") ;; MISSING-LARKC (:file "constrained-term-finder") ;; MISSING-LARKC (:file "constraint-filters") ;;(:file "test-query-suite") ;; MISSING-LARKC (:file "nl-api-datastructures") ;;(:file "morphology") ;;(:file "file-backed-cache-setup") ;;(:file "standard-tokenization") ;;(:file "interval-span") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-relevant-similar-queries") ;; MISSING-LARKC (:file "inference.modules.removal.removal-modules-semantically-related") ;;(:file "folification") ;; MISSING-LARKC (:file "thcl") ;; MISSING-LARKC (:file "cycml") ;;(:file "cycml-generator") ;;(:file "concept-filter") ;;(:file "lucene-session") ;; MISSING-LARKC (:file "quirk.quirk-trampolines") ;; MISSING-LARKC (:file "nlp-tests") ;; MISSING-LARKC (:file "properties") ;; MISSING-LARKC (:file "webcache") ;;(:file "xref-database") ;;(:file "secure-translation") ;; MISSING-LARKC (:file "form-translation") ;;(:file "file-translation") ;;(:file "system-translation") ;; MISSING-LARKC (:file "common-optimization") ;;(:file "c-name-translation") ;;(:file "c-backend") ;; MISSING-LARKC (:file "optimized-funcall-declarations") ;;(:file "java-name-translation") ;; MISSING-LARKC (:file "java-backend") ;; MISSING-LARKC (:file "translator-utilities") ;;(:file "eu.larkc.core.LarkcInit") ;; MISSING-LARKC (:file "eu.larkc.core.endpoint.sparql.LarKCHttpServer") ))))
51,570
Common Lisp
.asd
650
43.363077
187
0.412652
white-flame/clyc
22
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
5b1de243a67b41ead33a0d2f03cf26e215dddaa5a756a36dc2a046d1be5a03c2
6,810
[ -1 ]
6,966
loader-sbcl.lisp
tlikonen_cl-eval-bot/loader-sbcl.lisp
;;;; Eval-bot loader (require :asdf) (require :sb-posix) (asdf:initialize-output-translations (list :output-translations :ignore-inherited-configuration (list (merge-pathnames "**/*.*") (merge-pathnames "build/**/*.*")))) (asdf:initialize-source-registry (list :source-registry :ignore-inherited-configuration (list :directory (merge-pathnames "src/")) (list :tree (merge-pathnames "quicklisp/dists/")))) (flet ((probe-load (path) (when (probe-file path) (load path))) (funcallstr (string &rest args) (apply (read-from-string string) args))) (or (probe-load "quicklisp/setup.lisp") (let ((url "http://beta.quicklisp.org/quicklisp.lisp") (init (nth-value 1 (sb-posix:mkstemp "/tmp/quicklisp-XXXXXX")))) (unwind-protect (progn (sb-ext:run-program "wget" (list "-O" init "--" url) :search t :output t) (when (probe-load init) (funcallstr "quicklisp-quickstart:install" :path "quicklisp/"))) (delete-file init))))) (ql:quickload '("swank" "eval-bot")) (in-package #:eval-bot) (defparameter *freenode* (make-client :server "irc.freenode.net" :nickname "clbot" :username "clbot" :realname "Common Lisp bot" :listen-targets nil :auto-join nil)) (loop :for port :from 50000 :upto 50050 :do (handler-case (return (swank:create-server :port port :dont-close t)) (sb-bsd-sockets:address-in-use-error () nil)))
1,664
Common Lisp
.lisp
42
29.928571
76
0.57373
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a89fc6853c94a59ebf1efe4aaf182a95f6aa13d3011d290a3694397a3bf0894a
6,966
[ -1 ]
6,967
sandbox-extra.lisp
tlikonen_cl-eval-bot/src/sandbox-extra.lisp
;;;; Eval-bot --- An IRC bot for evaluating Common Lisp expressions ;; Copyright (C) 2013 Teemu Likonen <[email protected]> ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public ;; License along with this program. If not, see ;; <http://www.gnu.org/licenses/>. (cl:defpackage #:sandbox-extra) (cl:in-package #:sandbox-extra) (cl:declaim (cl:optimize (cl:safety 3))) (cl:defmacro export-and-lock (cl:&body symbols) `(cl:progn ,@(cl:loop :for s :in symbols :append `((cl:setf (cl:get ',s :sandbox-locked) cl:t) (cl:export (cl:list ',s)))))) (export-and-lock help tell) (cl:define-symbol-macro help (cl:signal 'common:extra-command :command "help" :arguments cl:nil)) (cl:defmacro tell (nick sexp cl:&rest ignored) (cl:declare (cl:ignore ignored)) `(cl:let* ((form (cl:let ((cl:*print-case* :downcase)) (sandbox-cl:prin1-to-string ',sexp))) (values (cl:with-output-to-string (stream) (sandbox-impl:repl form stream)))) (cl:signal 'common:extra-command :command "tell" :arguments (cl:list ',nick form values))))
1,711
Common Lisp
.lisp
36
41.777778
72
0.667866
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d80885327110ff2480a664e1dd808b53a091d5188c594398ddabadfbcf7ba86d
6,967
[ -1 ]
6,968
sandbox-cl.lisp
tlikonen_cl-eval-bot/src/sandbox-cl.lisp
;;;; Eval-bot --- An IRC bot for evaluating Common Lisp expressions ;; Copyright (C) 2012-2016 Teemu Likonen <[email protected]> ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public ;; License along with this program. If not, see ;; <http://www.gnu.org/licenses/>. (cl:defpackage #:sandbox-cl) (cl:in-package #:sandbox-cl) (cl:declaim (cl:optimize (cl:safety 3))) ;;; Helpers for defining, importing and exporting (cl:defmacro import-export-symbols (cl:&body symbols) `(cl:loop :for symbol :in ',symbols :do (cl:shadowing-import (cl:list symbol)) (cl:export (cl:list symbol)))) (cl:defmacro sdefparameter (name initial-value) `(cl:progn (cl:export (cl:list ',name)) (cl:defparameter ,name ,initial-value))) (cl:defmacro sdefun (name lambda-list cl:&body body) `(cl:progn (cl:setf (cl:get ',name :sandbox-locked) cl:t) (cl:export (cl:list ',name)) (cl:defun ,name ,lambda-list ,@body))) (cl:defmacro sdefmacro (name lambda-list cl:&body body) `(cl:progn (cl:setf (cl:get ',name :sandbox-locked) cl:t) (cl:export (cl:list ',name)) (cl:defmacro ,name ,lambda-list ,@body))) (cl:defmacro disabled-features (cl:&body symbols) `(cl:loop :for symbol :in ',symbols :do (cl:setf (cl:get symbol :sandbox-locked) cl:t) (cl:export (cl:list symbol)) (cl:let ((name (cl:symbol-name symbol))) (cl:setf (cl:macro-function symbol) (cl:lambda (cl:&rest ignored) (cl:declare (cl:ignore ignored)) `(cl:error 'sandbox-impl:disabled-feature :name ,name)) (cl:symbol-function symbol) (cl:lambda (cl:&rest ignored) (cl:declare (cl:ignore ignored)) (cl:error 'sandbox-impl:disabled-feature :name name))) (cl:eval `(cl:defsetf ,symbol (cl:&rest ignored) () (cl:declare (cl:ignore ignored)) `(cl:error 'sandbox-impl:disabled-feature :name ,,name)))))) ;;; General #+sbcl (cl:eval-when (:compile-toplevel :load-toplevel :execute) (sb-ext:unlock-package "SB-IMPL")) #+sbcl (import-export-symbols ;SB-IMPL package is locked. sb-impl::backq-list sb-impl::backq-list* sb-impl::backq-append sb-impl::backq-cons sb-impl::backq-nconc sb-impl::backq-vector) (import-export-symbols cl:&allow-other-keys cl:&aux cl:&body cl:&environment cl:&key cl:&optional cl:&rest cl:&whole) ;;; The Evaluation and Compilation Dictionary (import-export-symbols cl:lambda cl:quote cl:special-operator-p cl:constantp) (disabled-features compile eval-when load-time-value compiler-macro-function define-compiler-macro macro-function macroexpand macroexpand-1 define-symbol-macro symbol-macrolet proclaim declaim the declare locally) (sdefun eval (form) (cl:values-list (sandbox-impl:translate-form (cl:multiple-value-list (cl:eval (sandbox-impl:translate-form form)))))) (sdefmacro defmacro (name lambda-list cl:&body body) (cl:if (cl:get name :sandbox-locked) (cl:error 'cl:package-error :package cl:nil) `(cl:defmacro ,name ,lambda-list ,@body))) ;;; The Types and Classes Dictionary (import-export-symbols cl:nil cl:boolean cl:function cl:compiled-function cl:generic-function cl:standard-generic-function cl:class cl:built-in-class cl:structure-class cl:standard-class cl:method cl:standard-method cl:structure-object cl:standard-object cl:method-combination cl:t cl:satisfies ;; cl:member Also a function. Imported later. cl:not cl:and cl:or cl:values cl:eql cl:coerce cl:subtypep cl:type-of cl:typep cl:type-error-datum cl:type-error-expected-type) (disabled-features deftype) ;;; The Data and Control Flow Dictionary (import-export-symbols cl:apply cl:fboundp cl:flet cl:labels cl:macrolet cl:funcall cl:function cl:functionp cl:compiled-function-p cl:call-arguments-limit cl:lambda-list-keywords cl:lambda-parameters-limit cl:defparameter cl:defvar cl:destructuring-bind cl:let cl:let* cl:progv cl:setq cl:psetq cl:block cl:go cl:return-from cl:return cl:tagbody cl:nil cl:not cl:t cl:eq cl:eql cl:equal cl:equalp cl:identity cl:complement cl:constantly cl:every cl:some cl:notevery cl:notany cl:and cl:cond cl:if cl:or cl:when cl:unless cl:case cl:ccase cl:ecase cl:typecase cl:ctypecase cl:etypecase cl:multiple-value-bind cl:multiple-value-list cl:multiple-value-prog1 cl:multiple-value-setq cl:values cl:values-list cl:multiple-values-limit cl:nth-value cl:prog cl:prog* cl:prog1 cl:prog2 cl:progn cl:setf cl:psetf cl:shiftf cl:rotatef) (disabled-features fdefinition fmakunbound function-lambda-expression defconstant define-modify-macro defsetf define-setf-expander get-setf-expansion unwind-protect catch throw) (sdefmacro defun (name lambda-list cl:&body body) (cl:if (cl:or (cl:and (cl:symbolp name) (cl:get name :sandbox-locked)) (cl:and (cl:consp name) (cl:eql (cl:first name) 'cl:setf) (cl:get (cl:second name) :sandbox-locked))) (cl:error 'cl:package-error :package cl:nil) `(cl:defun ,name ,lambda-list ,@body))) ;;; The Iteration Dictionary (import-export-symbols cl:do cl:do* cl:dotimes cl:dolist) (disabled-features loop) ;;; The Objects Dictionary (import-export-symbols cl:class-of) (disabled-features function-keywords ensure-generic-function allocate-instance reinitialize-instance shared-initialize update-instance-for-different-class update-instance-for-redefined-class change-class slot-boundp slot-exists-p slot-makunbound slot-missing slot-unbound slot-value method-qualifiers no-applicable-method remove-method make-instance make-instances-obsolete make-load-form make-load-form-saving-slots with-accessors with-slots defclass defgeneric defmethod find-class next-method-p call-method make-method call-next-method compute-applicable-methods define-method-combination find-method add-method initialize-instance class-name unbound-slot-instance) ;;; The Structures Dictionary (disabled-features defstruct copy-structure) ;;; The Conditions Dictionary (import-export-symbols cl:restart) (disabled-features cell-error-name assert error cerror check-type invalid-method-error method-combination-error signal simple-condition-format-control simple-condition-format-arguments warn invoke-debugger break handler-bind handler-case ignore-errors define-condition make-condition compute-restarts find-restart invoke-restart invoke-restart-interactively restart-bind restart-case restart-name with-condition-restarts with-simple-restart abort continue muffle-warning store-value use-value) ;;; The Symbols Dictionary (import-export-symbols cl:symbol cl:keyword cl:symbolp cl:keywordp cl:symbol-name cl:boundp) (disabled-features make-symbol copy-symbol gensym gentemp symbol-function symbol-package symbol-plist symbol-value get remprop makunbound set) ;;; The Packages Dictionary (disabled-features export find-symbol find-package find-all-symbols import list-all-packages rename-package shadow shadowing-import delete-package make-package with-package-iterator unexport unintern in-package unuse-package use-package defpackage do-symbols do-external-symbols do-all-symbols intern package-name package-nicknames package-shadowing-symbols package-use-list package-used-by-list packagep package-error-package) ;;; The Numbers Dictionary (import-export-symbols cl:number cl:complex cl:real cl:float cl:short-float cl:single-float cl:double-float cl:long-float cl:rational cl:ratio cl:integer cl:signed-byte cl:unsigned-byte cl:mod cl:bit cl:fixnum cl:bignum cl:= cl:/= cl:< cl:> cl:<= cl:>= cl:max cl:min cl:minusp cl:plusp cl:zerop cl:floor cl:ffloor cl:ceiling cl:fceiling cl:truncate cl:ftruncate cl:round cl:fround cl:sin cl:cos cl:tan cl:asin cl:acos cl:atan cl:pi cl:sinh cl:cosh cl:tanh cl:asinh cl:acosh cl:atanh cl:1+ cl:1- cl:abs cl:evenp cl:oddp cl:exp cl:expt cl:gcd cl:incf cl:decf cl:lcm cl:log cl:mod cl:rem cl:signum cl:sqrt cl:isqrt cl:random-state cl:make-random-state cl:random cl:random-state-p cl:*random-state* cl:numberp cl:cis cl:complex cl:complexp cl:conjugate cl:phase cl:realpart cl:imagpart cl:upgraded-complex-part-type cl:realp cl:numerator cl:denominator cl:rational cl:rationalize cl:rationalp cl:ash cl:integer-length cl:integerp cl:parse-integer cl:boole cl:boole-1 cl:boole-2 cl:boole-and cl:boole-andc1 cl:boole-andc2 cl:boole-c1 cl:boole-c2 cl:boole-clr cl:boole-eqv cl:boole-ior cl:boole-nand cl:boole-nor cl:boole-orc1 cl:boole-orc2 cl:boole-set cl:boole-xor cl:logand cl:logandc1 cl:logandc2 cl:logeqv cl:logior cl:lognand cl:lognor cl:lognot cl:logorc1 cl:logorc2 cl:logxor cl:logbitp cl:logcount cl:logtest cl:byte cl:byte-size cl:byte-position cl:deposit-field cl:dpb cl:ldb cl:ldb-test cl:mask-field cl:most-positive-fixnum cl:most-negative-fixnum cl:decode-float cl:scale-float cl:float-radix cl:float-sign cl:float-digits cl:float-precision cl:integer-decode-float cl:float cl:floatp cl:most-positive-short-float cl:least-positive-short-float cl:least-positive-normalized-short-float cl:most-positive-double-float cl:least-positive-double-float cl:least-positive-normalized-double-float cl:most-positive-long-float cl:least-positive-long-float cl:least-positive-normalized-long-float cl:most-positive-single-float cl:least-positive-single-float cl:least-positive-normalized-single-float cl:most-negative-short-float cl:least-negative-short-float cl:least-negative-normalized-short-float cl:most-negative-single-float cl:least-negative-single-float cl:least-negative-normalized-single-float cl:most-negative-double-float cl:least-negative-double-float cl:least-negative-normalized-double-float cl:most-negative-long-float cl:least-negative-long-float cl:least-negative-normalized-long-float cl:short-float-epsilon cl:short-float-negative-epsilon cl:single-float-epsilon cl:single-float-negative-epsilon cl:double-float-epsilon cl:double-float-negative-epsilon cl:long-float-epsilon cl:long-float-negative-epsilon) (disabled-features arithmetic-error-operands arithmetic-error-operation) ;;; The Characters Dictionary (import-export-symbols cl:character cl:base-char cl:standard-char cl:extended-char cl:char= cl:char/= cl:char< cl:char> cl:char<= cl:char>= cl:char-equal cl:char-not-equal cl:char-lessp cl:char-greaterp cl:char-not-greaterp cl:char-not-lessp cl:characterp cl:alpha-char-p cl:alphanumericp cl:digit-char cl:digit-char-p cl:graphic-char-p cl:standard-char-p cl:char-upcase cl:char-downcase cl:upper-case-p cl:lower-case-p cl:both-case-p cl:char-code cl:char-int cl:code-char cl:char-code-limit cl:char-name cl:name-char) ;;; The Conses Dictionary (import-export-symbols cl:list cl:null cl:cons cl:atom cl:cons cl:consp cl:atom cl:rplaca cl:rplacd cl:car cl:cdr cl:caar cl:cadr cl:cdar cl:cddr cl:caaar cl:caadr cl:cadar cl:caddr cl:cdaar cl:cdadr cl:cddar cl:cdddr cl:caaaar cl:caaadr cl:caadar cl:caaddr cl:cadaar cl:cadadr cl:caddar cl:cadddr cl:cdaaar cl:cdaadr cl:cdadar cl:cdaddr cl:cddaar cl:cddadr cl:cdddar cl:cddddr cl:copy-tree cl:sublis cl:nsublis cl:subst cl:subst-if cl:subst-if-not cl:nsubst cl:nsubst-if cl:nsubst-if-not cl:tree-equal cl:copy-list cl:list cl:list* cl:list-length cl:listp cl:make-list cl:push cl:pop cl:first cl:second cl:third cl:fourth cl:fifth cl:sixth cl:seventh cl:eighth cl:ninth cl:tenth cl:nth cl:endp cl:null cl:nconc cl:append cl:revappend cl:nreconc cl:butlast cl:nbutlast cl:last cl:ldiff cl:tailp cl:nthcdr cl:rest cl:member cl:member-if cl:member-if-not cl:mapc cl:mapcar cl:mapcan cl:mapcan cl:mapl cl:maplist cl:mapcon cl:acons cl:assoc cl:assoc-if cl:assoc-if-not cl:copy-alist cl:pairlis cl:rassoc cl:rassoc-if cl:rassoc-if-not cl:get-properties cl:getf cl:remf cl:intersection cl:nintersection cl:adjoin cl:pushnew cl:set-difference cl:nset-difference cl:set-exclusive-or cl:nset-exclusive-or cl:subsetp cl:union cl:nunion) ;;; The Arrays Dictionary (import-export-symbols cl:array cl:simple-array cl:vector cl:simple-vector cl:bit-vector cl:simple-bit-vector cl:make-array cl:adjust-array cl:adjustable-array-p cl:aref cl:array-dimension cl:array-dimensions cl:array-element-type cl:array-has-fill-pointer-p cl:array-displacement cl:array-in-bounds-p cl:array-rank cl:array-row-major-index cl:array-total-size cl:arrayp cl:fill-pointer cl:row-major-aref cl:upgraded-array-element-type cl:array-dimension-limit cl:array-rank-limit cl:array-total-size-limit cl:simple-vector-p cl:svref cl:vector-pop cl:vector-push cl:vector-push-extend cl:vectorp cl:bit cl:sbit cl:bit-and cl:bit-andc1 cl:bit-andc2 cl:bit-eqv cl:bit-ior cl:bit-nand cl:bit-nor cl:bit-not cl:bit-orc1 cl:bit-orc2 cl:bit-xor cl:bit-vector-p cl:simple-bit-vector-p) ;;; The Strings Dictionary (import-export-symbols cl:string cl:base-string cl:simple-base-string cl:simple-string-p cl:char cl:schar cl:string-upcase cl:string-downcase cl:string-capitalize cl:nstring-upcase cl:nstring-downcase cl:nstring-capitalize cl:string-trim cl:string-left-trim cl:string-right-trim cl:string= cl:string/= cl:string< cl:string> cl:string<= cl:string>= cl:string-equal cl:string-not-equal cl:string-lessp cl:string-greaterp cl:string-not-greaterp cl:string-not-lessp cl:stringp cl:make-string) ;;; The Sequence Dictionary (import-export-symbols cl:sequence cl:copy-seq cl:elt cl:fill cl:make-sequence cl:subseq cl:map cl:map-into cl:reduce cl:count cl:count-if cl:count-if-not cl:length cl:reverse cl:nreverse cl:sort cl:stable-sort cl:find cl:find-if cl:find-if-not cl:position cl:position-if cl:position-if-not cl:search cl:mismatch cl:replace cl:substitute cl:substitute-if cl:substitute-if-not cl:nsubstitute cl:nsubstitute-if cl:nsubstitute-if-not cl:concatenate cl:merge cl:remove cl:remove-if cl:remove-if-not cl:delete cl:delete-if cl:delete-if-not cl:remove-duplicates cl:delete-duplicates) ;;; The Hash Tables Dictionary (import-export-symbols cl:hash-table cl:make-hash-table cl:hash-table-p cl:hash-table-count cl:hash-table-rehash-size cl:hash-table-rehash-threshold cl:hash-table-size cl:hash-table-test cl:gethash cl:remhash cl:maphash cl:with-hash-table-iterator cl:clrhash cl:sxhash) ;;; The Filenames Dictionary (import-export-symbols cl:pathname cl:make-pathname cl:pathnamep cl:pathname-directory cl:pathname-name cl:pathname-type cl:pathname-version cl:namestring cl:file-namestring cl:directory-namestring cl:parse-namestring cl:wild-pathname-p cl:pathname-match-p cl:translate-pathname cl:merge-pathnames) (disabled-features pathname-host pathname-device load-logical-pathname-translations logical-pathname-translations logical-pathname host-namestring enough-namestring translate-logical-pathname) ;;; The Files Dictionary (disabled-features directory probe-file ensure-directories-exist truename file-author file-write-date rename-file delete-file file-error-pathname) ;;; The Stream Dictionary (import-export-symbols cl:stream cl:broadcast-stream cl:concatenated-stream cl:echo-stream cl:file-stream cl:string-stream cl:synonym-stream cl:two-way-stream cl:input-stream-p cl:output-stream-p cl:interactive-stream-p cl:open-stream-p cl:stream-element-type cl:streamp cl:peek-char cl:read-char cl:read-char-no-hang cl:terpri cl:fresh-line cl:unread-char cl:write-char cl:read-line cl:write-string cl:write-line cl:read-sequence cl:write-sequence cl:file-position cl:close cl:listen cl:clear-input cl:finish-output cl:force-output cl:clear-output cl:with-input-from-string cl:with-output-to-string) (disabled-features read-byte write-byte file-length file-string-length open stream-external-format with-open-file with-open-stream y-or-n-p yes-or-no-p make-synonym-stream synonym-stream-symbol broadcast-stream-streams make-broadcast-stream make-two-way-stream two-way-stream-input-stream two-way-stream-output-stream make-echo-stream concatenated-stream-streams make-concatenated-stream make-string-input-stream make-string-output-stream stream-error-stream) ;;; The Printer Dictionary (import-export-symbols cl:write cl:prin1 cl:print cl:pprint cl:princ cl:write-to-string cl:prin1-to-string cl:princ-to-string) (disabled-features copy-pprint-dispatch formatter pprint-dispatch pprint-exit-if-list-exhausted pprint-fill pprint-linear pprint-tabular pprint-indent pprint-logical-block pprint-newline pprint-pop pprint-tab print-object print-unreadable-object set-ppring-dispatch print-not-readable-object format) ;;; The Reader Dictionary (disabled-features copy-readtable make-dispatch-macro-character read-preserving-whitespace read-delimited-list readtable-case readtablep set-dispatch-macro-character get-dispatch-macro-character set-macro-character get-macro-character set-syntax-from-char with-standard-io-syntax) (sdefun read (cl:&rest args) (cl:values-list (sandbox-impl:translate-form (cl:multiple-value-list (cl:apply #'cl:read args))))) (sdefun read-from-string (cl:&rest args) (cl:values-list (sandbox-impl:translate-form (cl:multiple-value-list (cl:apply #'cl:read-from-string args))))) ;;; The System Construction Dictionary (disabled-features compile-file compile-file-pathname load with-compilation-unit provide require) ;;; The Environment Dictionary (import-export-symbols cl:decode-universal-time cl:encode-universal-time cl:get-universal-time cl:get-decoded-time cl:sleep cl:lisp-implementation-type cl:lisp-implementation-version) (disabled-features apropos apropos-list describe describe-object trace untrace step time get-internal-real-time get-internal-run-time disassemble documentation room ed inspect dribble short-site-name long-site-name machine-instance machine-type machine-version software-type software-version) (sdefun user-homedir-pathname (cl:&optional ignored) (cl:declare (cl:ignore ignored)) (cl:make-pathname :directory '(:absolute "home" "sandbox") :name cl:nil :type cl:nil))
19,066
Common Lisp
.lisp
361
48.362881
79
0.758336
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bb0198e2941508f909de5c70b41f3ee1f47653cece8adcc7ce83c34644a1bfe4
6,968
[ -1 ]
6,969
common.lisp
tlikonen_cl-eval-bot/src/common.lisp
;;;; Eval-bot --- An IRC bot for evaluating Common Lisp expressions ;; Copyright (C) 2012-2013 Teemu Likonen <[email protected]> ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as ;; published by the Free Software Foundation, either version 3 of the ;; License, or (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public ;; License along with this program. If not, see ;; <http://www.gnu.org/licenses/>. (defpackage #:common (:use #:cl) (:export #:with-thread #:update-sandbox-usage #:delete-unused-packages #:delete-all-packages #:list-user-sandbox-packages #:user-to-sandbox-name #:queue #:queue-add #:queue-pop #:queue-clear #:queue-length #:extra-command #:command #:arguments)) (in-package #:common) (define-condition extra-command () ((command :reader command :initarg :command) (arguments :reader arguments :initarg :arguments))) ;;; Threads (defmacro with-thread ((name &key timeout) &body body) (let ((main (gensym "MAIN-THREAD")) (time (gensym "TIMEOUT")) (main-body (loop :for form :in body :until (eql form :timeout) :collect form)) (timeout-body (rest (member :timeout body)))) `(let ((,time ,timeout)) (assert (or (not ,time) (and (realp ,time) (not (minusp ,time)))) nil "TIMEOUT must be a non-negative real number or NIL.") (let ((,main (bt:make-thread (lambda () ,@main-body) :name ,name))) (when ,time (bt:make-thread (lambda () (sleep ,time) (when (bt:thread-alive-p ,main) (bt:destroy-thread ,main) ,@timeout-body)) :name (format nil "~A timeout" (bt:thread-name ,main)))) ,main)))) ;;; Maintenance (defclass sandbox-package () ((lock :reader lock :initform (bt:make-lock "sandbox-package")) (last-use :accessor last-use))) (defvar *sandbox-usage* (make-hash-table :test #'equal)) (defun update-sandbox-usage (sandbox-name) (let ((package (gethash sandbox-name *sandbox-usage*))) (unless (typep package 'sandbox-package) (setf package (make-instance 'sandbox-package) (gethash sandbox-name *sandbox-usage*) package)) (bt:with-lock-held ((lock (gethash sandbox-name *sandbox-usage*))) (setf (last-use package) (get-universal-time))))) (defvar *max-sandbox-age* (* 15 60)) (defun delete-unused-packages () (let ((current-time (get-universal-time))) (maphash (lambda (package-name package) (bt:with-lock-held ((lock package)) (when (or (not (find-package package-name)) (> (- current-time (last-use package)) *max-sandbox-age*)) (remhash package-name *sandbox-usage*) (delete-package package-name)))) *sandbox-usage*))) (defun delete-all-packages () (maphash (lambda (package-name package) (bt:with-lock-held ((lock package)) (remhash package-name *sandbox-usage*) (delete-package package-name))) *sandbox-usage*)) (defvar *sandbox-package-prefix* "SANDBOX/") (defun list-user-sandbox-packages () (remove-if-not (lambda (item) (string= *sandbox-package-prefix* (subseq item 0 (min (length item) (length *sandbox-package-prefix*))))) (list-all-packages) :key #'package-name)) (defun user-to-sandbox-name (user) (let ((excl (position #\! user))) (string-upcase (concatenate 'string *sandbox-package-prefix* (subseq user (or excl 0)))))) ;;; Queues (defclass queue () ((queue-first :accessor queue-first :initform nil) (queue-last :accessor queue-last :initform nil) (queue-length :accessor queue-length :initform 0) (lock :reader lock :initform (bt:make-lock "queue")))) (defun queue-add (queue item) (bt:with-lock-held ((lock queue)) (with-slots (queue-first queue-last queue-length) queue (let ((new-cons (cons item nil))) (if (and queue-first queue-last) (setf (cdr queue-last) new-cons) (setf queue-first new-cons)) (setf queue-last new-cons) (incf queue-length) item)))) (defun queue-pop (queue) (bt:with-lock-held ((lock queue)) (with-slots (queue-first queue-last queue-length) queue (if queue-first (let ((first (pop queue-first))) (decf queue-length) (unless queue-first (setf queue-last nil)) (values first t)) (values nil nil))))) (defun queue-clear (queue) (bt:with-lock-held ((lock queue)) (setf (queue-first queue) nil (queue-last queue) nil (queue-length queue) 0)))
5,450
Common Lisp
.lisp
122
34.991803
78
0.592537
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f2899377e3b83e8019f9de385eac5ee2b490243fe4073445d0a36eecbdfcc2c5
6,969
[ -1 ]
6,970
eval-bot.asd
tlikonen_cl-eval-bot/src/eval-bot.asd
(defsystem "eval-bot" :description "An IRC bot for Common Lisp code evaluation" :author "Teemu Likonen <[email protected]>" :licence "GNU Affero General Public License version 3" :depends-on ("bordeaux-threads" "trivial-irc" "alexandria" "split-sequence" "babel") :components ((:file "sandbox-impl" :depends-on ("common")) (:file "sandbox-extra" :depends-on ("common" "sandbox-impl" "sandbox-cl")) (:file "sandbox-cl" :depends-on ("sandbox-impl")) (:file "common") (:file "eval-bot" :depends-on ("common" "sandbox-impl"))))
561
Common Lisp
.asd
12
42.5
77
0.673953
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
70c9faf2e3ba9a3847b264e9244a488c3cd582565e590296d76d28107511d484
6,970
[ -1 ]
6,972
start-bot-sbcl
tlikonen_cl-eval-bot/start-bot-sbcl
#!/bin/sh sbcl=sbcl export TZ=GMT cd "$(dirname "$0")" || exit 1 while true; do nice rlwrap -D -- "$sbcl" \ --control-stack-size 1 \ --disable-ldb --lose-on-corruption \ --noinform --no-sysinit --no-userinit \ --load loader-sbcl.lisp \ "$@" && exit 0 done
270
Common Lisp
.cl
12
20.333333
41
0.635294
tlikonen/cl-eval-bot
24
2
0
AGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
34596b38952e6c9920a5c6d4a003665b300a6fe385c46a78533fd6179ab05354
6,972
[ -1 ]
6,995
parse.lisp
rotatef_json-streams/parse.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (defun json-parse (source &rest options) (with-open-json-stream (jstream (apply #'make-json-input-stream source options)) (values (parse-single jstream) (slot-value jstream 'position)))) (defun json-parse-multiple (source &rest options) (with-open-json-stream (jstream (apply #'make-json-input-stream source :multiple t options)) (loop for value = (parse-single jstream) until (eql :eof value) collect value))) (defun parse-single (jstream) (labels ((parse-array (jstream) (cons :array (loop for value = (parse-value jstream) until (eql :end-array value) collect value))) (parse-object (jstream) (cons :object (loop for key = (parse-value jstream) until (eql :end-object key) collect (cons key (parse-value jstream))))) (parse-value (jstream) (let ((token (json-read jstream))) (case token (:true t) (:false nil) (:begin-array (parse-array jstream)) (:begin-object (parse-object jstream)) (otherwise token))))) (values (parse-value jstream) (json-stream-position jstream))))
2,158
Common Lisp
.lisp
47
37.085106
94
0.611692
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c489badce967c9b3ac8c98b3932e4a6d9f4dca60401782949d8753fca15ff68c
6,995
[ -1 ]
6,996
package.lisp
rotatef_json-streams/package.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defpackage #:json-streams (:use :common-lisp) (:export #:json-parse #:json-parse-multiple #:json-stringify #:json-stringify-multiple #:json-stream #:json-input-stream #:json-output-stream #:json-close #:with-open-json-stream #:json-error #:json-parse-error #:json-write-error #:make-json-output-stream #:json-write #:make-json-input-stream #:json-stream-position #:json-read #:json-object #:json-array #:json-string #:most-positive-json-integer #:most-negative-json-integer #:call-with-json-output #:with-json-output #:with-json-array #:with-json-object #:with-json-member #:json-output-member #:json-output-value #:json-output-boolean #:json-output-null #:json-output-alist #:json-output-plist))
1,598
Common Lisp
.lisp
52
27.557692
78
0.699219
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
2e2559a3bacba0a4dee0f4e6643adfd34b2b3fc385d5fc4c3157fbf77a02561a
6,996
[ -1 ]
6,997
input-stream.lisp
rotatef_json-streams/input-stream.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (defun make-json-input-stream (source &key (start 0) end close-stream multiple use-ratios (max-exponent 325) raw-strings (duplicate-key-check t)) (make-instance 'json-input-stream :stream (cond ((stringp source) (make-string-input-stream source start end)) ((and (streamp source) (input-stream-p source) (subtypep (stream-element-type source) 'character)) source) (t (error 'json-error :stream source :message (format nil "Source must be a string or a character input stream, got ~S." (type-of source))))) :position start :close-stream close-stream :duplicate-key-check duplicate-key-check :multiple multiple :use-ratios use-ratios :max-exponent max-exponent :raw-strings raw-strings)) (defun current-position () (slot-value *json-stream* 'position)) (defun peek-next-char () (with-slots (stream) *json-stream* (peek-char nil stream nil))) (defun read-next-char () (with-slots (stream current-char position newlines) *json-stream* (setf current-char (read-char stream nil)) (when current-char (incf position) (when (eql #\Newline current-char) (push position newlines))) current-char)) (defun unread-current-char () (with-slots (stream current-char position) *json-stream* (when current-char (decf position) (unread-char current-char stream)))) (defun skip-space () (loop while (member (read-next-char) '(#\Space #\Tab #\Newline #\Return))) (unread-current-char)) (defun expect-string (start string token) (loop for expect across string for char = (read-next-char) unless (eql char expect) do (%json-error "Expected ~S (as part of ~S), got ~S" expect string char)) (values token start (current-position))) (defun valid-unescaped-char-p (char) (when char (let ((code (char-code char))) (or (<= #x20 code #x21) (<= #x23 code #x5b) (<= #x5d code #x10ffff))))) (defun read-string-chars () (coerce (loop for char = (read-next-char) while (valid-unescaped-char-p char) collect char finally (unread-current-char)) 'string)) (defun read-4hexdig () (loop repeat 4 for weight = #x1000 then (/ weight 16) for char = (read-next-char) for digit = (and char (digit-char-p char 16)) do (unless digit (%json-error "Invalid char ~S in Unicode escape" char)) sum (* digit weight))) (defun read-escaped (start) (read-next-char) (let ((escaped (read-next-char))) (if (eql #\u escaped) (values (read-4hexdig) start (current-position)) (values escaped start (current-position))))) (defun read-integer (&key fractional-p) (loop for number = 0 then (+ (* number 10) digit) for size from 0 for char = (read-next-char) for digit = (and char (digit-char-p char)) while digit finally (progn (unread-current-char) (unless (plusp size) (%json-error "Expected digit, got ~S" char)) (return (if fractional-p (/ number (expt 10 size)) number))))) (defun read-number (start) (let* ((sign 1) (integer-part 0) (has-dot nil) (has-e nil) (fraction-part 0) (exponent-sign 1) (exponent 0)) (when (eql #\- (peek-next-char)) (read-next-char) (setf sign -1)) (if (eql #\0 (peek-next-char)) (read-next-char) (setf integer-part (read-integer))) (when (eql #\. (peek-next-char)) (setf has-dot t) (read-next-char) (setf fraction-part (read-integer :fractional-p t))) (when (member (peek-next-char) '(#\e #\E)) (setf has-e t) (read-next-char) (case (read-next-char) (#\+) (#\- (setf exponent-sign -1)) (otherwise (unread-current-char))) (setf exponent (read-integer))) (with-slots (use-ratios max-exponent) *json-stream* (when (> exponent max-exponent) (%json-error "Exponent ~A is too large (or small) (max-exponent is ~A)" exponent max-exponent)) (let ((number (* sign (+ integer-part fraction-part) (expt 10 (* exponent-sign exponent))))) (when (and (not use-ratios) (not (or has-dot has-e)) (not (<= +most-negative-json-integer+ number +most-positive-json-integer+))) (%json-error "Number with integer syntax to large ~D." number)) (values (if (and (not use-ratios) (or has-dot has-e) (or (not (<= +most-negative-json-integer+ number +most-positive-json-integer+)) (not (integerp number)))) (handler-case (coerce number 'double-float) (type-error () (%json-error "Number can't be converted to double-float ~D" number))) number) start (current-position)))))) (defun read-raw-token (&optional (*json-stream* *json-stream*)) (with-slots (string-mode) *json-stream* (let ((start-pos (current-position))) (cond ((eql :eof (car (state-stack))) (values :eof start-pos start-pos)) (string-mode (case (peek-next-char) ((nil) (values :eof start-pos (current-position))) (#\" (read-next-char) (setf string-mode nil) (values :string-delimiter start-pos (current-position))) (#\\ (read-escaped start-pos)) (otherwise (unless (valid-unescaped-char-p (peek-next-char)) (%json-error "Invalid char in string: ~S " (read-next-char))) (values (read-string-chars) start-pos (current-position))))) (t (skip-space) (case (peek-next-char) ((nil) (values :eof start-pos (current-position))) (#\{ (read-next-char) (values :begin-object start-pos (current-position))) (#\} (read-next-char) (values :end-object start-pos (current-position))) (#\[ (read-next-char) (values :begin-array start-pos (current-position))) (#\] (read-next-char) (values :end-array start-pos (current-position))) (#\: (read-next-char) (values :name-separator start-pos (current-position))) (#\, (read-next-char) (values :value-separator start-pos (current-position))) (#\f (expect-string start-pos "false" :false)) (#\n (expect-string start-pos "null" :null)) (#\t (expect-string start-pos "true" :true)) ((#\- #\0 #\1 #\2 #\3 #\4 #\5 #\6 #\7 #\8 #\9) (read-number start-pos)) (#\" (read-next-char) (setf string-mode t) (values :string-delimiter start-pos (current-position))) (otherwise (%json-error "Unexpected character ~S" (read-next-char))))))))) (defun parse-string-to-string (start) (let (token start2 end) (values (with-output-to-string (string) (loop (multiple-value-setq (token start2 end) (read-raw-token)) (cond ((eql :string-delimiter token) (return)) ((stringp token) (princ token string)) ((characterp token) (case token ((#\" #\\ #\/) (princ token string)) (#\b (princ #\Backspace string)) (#\f (princ #\Page string)) (#\n (princ #\Newline string)) (#\r (princ #\Return string)) (#\t (princ #\Tab string)) (otherwise (%json-error "Invalid escape \\~A" token)))) ((integerp token) (cond ((<= #xDC00 token #xDFFF) (%json-error "Invalid unicode escape ~4,'0X" token)) ((<= #xD800 token #xDBFF) (let ((lead token) (tail (read-raw-token))) (unless (and (integerp tail) (<= #xDC00 tail #xDFFF)) (%json-error "Invalid UTF-16 surrogate pair ~4,'0X ~4,'0X" lead tail)) #+JSON-STREAMS::UTF-16-STRINGS (progn (princ (code-char lead) string) (princ (code-char tail) string)) #-JSON-STREAMS::UTF-16-STRINGS (princ (code-char (+ #x10000 (ash (- lead #xD800) 10) (- tail #xDC00))) string))) (t (princ (code-char token) string)))) (t (%json-error "Invalid token ~S in string." token))))) start end))) (defun parse-raw-string (start) (let (token start2 end raw-string) (loop (multiple-value-setq (token start2 end) (read-raw-token)) (cond ((eql :string-delimiter token) (return)) ((stringp token) (loop for char across token do (push (char-code char) raw-string))) ((characterp token) (push (char-code (case token ((#\" #\\ #\/) token) (#\b #\Backspace) (#\f #\Page) (#\n #\Newline) (#\r #\Return) (#\t #\Tab) (otherwise (%json-error "Invalid escape \\~A" token)))) raw-string)) ((integerp token) (push token raw-string)) (t (%json-error "Invalid token ~S in string." token)))) (values (cons :string (nreverse raw-string)) start end))) (defun parse-string (start) (if (slot-value *json-stream* 'raw-strings) (parse-raw-string start) (parse-string-to-string start))) (defun read-token (&optional start (*json-stream* *json-stream*)) (with-slots (multiple stream) *json-stream* (multiple-value-bind (token start2 end) (read-raw-token) (unless start (setf start start2)) (let ((token-type (etypecase token (keyword token) (real :number)))) (labels ((reprocess () (ecase (car (state-stack)) (:before-json-text (unless multiple (switch-state :after-json-text)) (ecase* token-type (:begin-object (push-state :begin-object) (begin-object) (values token start end)) (:begin-array (push-state :before-first-array-item) (values token start end)) (:string-delimiter (parse-string start)) ((:false :null :true) (values token start end)) (:number (values token start end)) (:eof (unless multiple (%json-error "Empty JSON text")) (switch-state :eof) (values :eof start end)))) (:begin-object (ecase* token-type (:end-object (pop-state) (end-object) (values token start end)) (:string-delimiter (switch-state :after-object-key) (multiple-value-bind (key start end) (parse-string start) (check-key key) (values key start end))))) (:after-object-key (ecase* token-type (:name-separator (switch-state :after-object-value) (push-state :value) (read-token start)))) (:after-object-value (ecase* token-type (:value-separator (switch-state :before-object-key) (read-token start)) (:end-object (pop-state) (end-object) (values token start end)))) (:before-object-key (ecase* token-type (:string-delimiter (switch-state :after-object-key) (multiple-value-bind (key start end) (parse-string start) (check-key key) (values key start end))))) (:before-first-array-item (case token-type (:end-array (pop-state) (values token start end)) (otherwise (switch-state :after-array-item) (push-state :value) (reprocess)))) (:after-array-item (ecase* token-type (:value-separator (push-state :value) (read-token start)) (:end-array (pop-state) (values token start end)))) (:value (pop-state) (ecase* token-type (:begin-object (push-state :begin-object) (begin-object) (values token start end)) (:begin-array (push-state :before-first-array-item) (values token start end)) (:string-delimiter (parse-string start)) ((:false :null :true) (values token start end)) (:number (values token start end)))) (:after-json-text (ecase* token-type (:eof (switch-state :eof) (values :eof start end)))) (:eof (values :eof start end))))) (reprocess)))))) (defmethod %json-close ((*json-stream* json-input-stream)) (json-read *json-stream*)) (defun json-read (json-input-stream) (read-token nil json-input-stream))
16,441
Common Lisp
.lisp
380
27.631579
118
0.473799
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bb3bbbe6009b3f07a5b7d5a398e85d1d2e9e538c71f90bb77969dbbb7c63fd39
6,997
[ -1 ]
6,998
output.lisp
rotatef_json-streams/output.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2017 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (defun call-with-json-output (target options function) (if target (with-open-json-stream (*json-stream* (apply #'make-json-output-stream target options)) (funcall function)) (with-output-to-string (out) (with-open-json-stream (*json-stream* (apply #'make-json-output-stream out options)) (funcall function))))) (defmacro with-json-output ((&optional target &rest options) &body body) `(call-with-json-output ,target (list ,@options) (lambda () ,@body))) (defmacro with-json-array (&body body) `(progn (json-write :begin-array *json-stream*) ,@body (json-write :end-array *json-stream*))) (defmacro with-json-object (&body body) `(progn (json-write :begin-object *json-stream*) ,@body (json-write :end-object *json-stream*))) (defmacro with-json-member (key &body body) `(progn (json-write (json-encode-key ,key *json-stream*) *json-stream*) ,@body)) (defun json-output-member (key value) (json-write (json-encode-key key *json-stream*) *json-stream*) (json-output-value value)) (defun json-output-value (value) (etypecase value ((or string real) (json-write value *json-stream*)) (sequence (with-json-array (map nil #'json-output-value value))) (hash-table (with-json-object (maphash #'json-output-member value))))) (defun json-output-boolean (value) (json-write (if value :true :false) *json-stream*)) (defun json-output-null () (json-write :null *json-stream*)) (defun json-output-alist (alist) (with-json-object (loop for (key . value) in alist do (json-output-member key value)))) (defun json-output-plist (plist) (with-json-object (loop for (key value) on plist by #'cddr do (json-output-member key value))))
2,623
Common Lisp
.lisp
65
36.369231
93
0.684813
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
244cb5d150bba6ed74aa2c32eb573148b434d2b82b992ac0874402e27b41a847
6,998
[ -1 ]
6,999
stringify.lisp
rotatef_json-streams/stringify.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (defun json-stringify (value &optional target &rest options) (call-with-json-output target options (lambda () (json-stringify-single value)))) (defun json-stringify-multiple (value &optional target &rest options) (call-with-json-output target (list* :multiple t options) (lambda () (map nil #'json-stringify-single value)))) (defun json-stringify-single (value) (etypecase value ((or string real) (json-output-value value)) ((member t nil) (json-output-boolean value)) ((member :null) (json-output-null)) (json-array (with-json-array (map nil #'json-stringify-single (cdr value)))) (json-object (with-json-object (loop for (key . value) in (cdr value) do (with-json-member key (json-stringify-single value)))))))
1,724
Common Lisp
.lisp
41
36.268293
78
0.655131
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f8a071a2a9a673df523f6737e33eaf731c6866422deb2b03a66b85b356f623df
6,999
[ -1 ]
7,000
base.lisp
rotatef_json-streams/base.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (deftype json-object () '(cons (member :object) t)) (deftype json-array () '(cons (member :array) t)) (deftype json-string () '(or string (cons (member :string) t))) (when (= char-code-limit #x10000) (push 'utf-16-strings *features*)) (defconstant +most-positive-json-integer+ (expt 2 53)) (defconstant +most-negative-json-integer+ (- (expt 2 53))) (defvar *json-stream*) (defclass json-stream () ((stream :initarg :stream) (close-stream :initarg :close-stream) (state-stack :initform '(:before-json-text)) (duplicate-key-check :initarg :duplicate-key-check) (key-check-stack :initform nil))) (defclass json-input-stream (json-stream) ((multiple :initarg :multiple) (use-ratios :initarg :use-ratios) (max-exponent :initarg :max-exponent) (raw-strings :initarg :raw-strings) (current-char :initform nil) (position :initarg :position :reader json-stream-position) (newlines :initform '()) (string-mode :initform nil))) (defclass json-output-stream (json-stream) ((multiple :initarg :multiple) (escape-non-ascii :initarg :escape-non-ascii) (indent :initarg :indent) (level :initform 0) (key-encoder :initarg :key-encoder :initform nil))) (defgeneric %json-close (json-stream)) (defun json-close (json-stream &key abort) (with-slots (stream close-stream) json-stream (unless abort (%json-close json-stream)) (when close-stream (close stream :abort abort)))) (defmacro with-open-json-stream ((var stream) &body body) (let ((errorsp (gensym "ERRORSP"))) `(let ((,var ,stream) (,errorsp t)) (unwind-protect (multiple-value-prog1 ,@body (setf ,errorsp nil)) (json-close ,var :abort ,errorsp))))) (defun begin-object () (with-slots (duplicate-key-check key-check-stack) *json-stream* (when duplicate-key-check (push (make-hash-table :test #'equal) key-check-stack)))) (defun end-object () (with-slots (duplicate-key-check key-check-stack) *json-stream* (when duplicate-key-check (pop key-check-stack)))) (defun check-key (key) (with-slots (duplicate-key-check key-check-stack) *json-stream* (when duplicate-key-check (when (gethash key (car key-check-stack)) (%json-error "Duplicate key ~S in object" key)) (setf (gethash key (car key-check-stack)) t)))) (defmacro state-stack () `(slot-value *json-stream* 'state-stack)) (defun push-state (new-state) (push new-state (state-stack))) (defun pop-state () (pop (state-stack))) (defun switch-state (new-state) (pop-state) (push-state new-state)) (define-condition json-error (error) ((stream :initform *json-stream* :initarg :stream :reader json-error-stream) (message :initarg :message :reader json-error-message)) (:report (lambda (c stream) (format stream "JSON parse error from ~A: ~A" (json-error-stream c) (json-error-message c))))) (define-condition json-parse-error (json-error) () (:report (lambda (c stream) (let ((newlines (remove-duplicates (slot-value (json-error-stream c) 'newlines)))) (format stream "JSON parse error at line ~D column ~D: ~A" (1+ (length newlines)) (- (slot-value (json-error-stream c) 'position) (or (car newlines) 0)) (json-error-message c)))))) (define-condition json-write-error (json-error) () (:report (lambda (c stream) (format stream "JSON write error: ~A." (json-error-message c))))) (defun %json-error (message &rest args) (switch-state :eof) (error (etypecase *json-stream* (json-input-stream 'json-parse-error) (json-output-stream 'json-write-error)) :message (apply #'format nil message args))) (defmacro ecase* (keyform &body cases) (let ((key (gensym "KEY"))) `(let ((,key ,keyform)) (case ,key ,@cases (otherwise (%json-error "Expected one of ~S, got ~S in state ~S." ',(mapcar #'car cases) ,key (slot-value *json-stream* 'state-stack)))))))
5,087
Common Lisp
.lisp
129
33.457364
95
0.642334
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
60810128bfb3b908240d5cd879e117b33fdb773c67f881e9efcea4c3c9c38c4d
7,000
[ -1 ]
7,001
output-stream.lisp
rotatef_json-streams/output-stream.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package #:json-streams) (defun make-json-output-stream (stream &key close-stream multiple indent escape-non-ascii (duplicate-key-check t) key-encoder) (make-instance 'json-output-stream :stream stream :close-stream close-stream :duplicate-key-check duplicate-key-check :multiple multiple :indent indent :escape-non-ascii escape-non-ascii :key-encoder key-encoder)) (defun write-indent () (with-slots (stream indent level) *json-stream* (when indent (terpri stream) (dotimes (i level) (princ #\Tab stream))))) (defun write-number (number) (with-slots (stream level) *json-stream* (unless (or (integerp number) (floatp number)) (%json-error "Number must be integer or float, got ~D" number)) (when (and (integerp number) (not (<= +most-negative-json-integer+ number +most-positive-json-integer+))) (%json-error "Integer ~D too large" number)) (multiple-value-bind (quotient remainder) (floor number) (if (zerop remainder) (princ quotient stream) (write-float number stream))))) (defun write-unicode (stream code-point) (flet ((write-escape (value) (format stream "\\u~4,'0X" value))) (cond ((<= code-point #xFFFF) (write-escape code-point)) (t (write-escape (+ (ldb (byte 10 10) (- code-point #x10000)) #xD800)) (write-escape (+ (ldb (byte 10 0) (- code-point #x10000)) #xDC00)))))) (defun write-escaped-string (string) (with-slots (stream level escape-non-ascii) *json-stream* (princ #\" stream) (map nil (lambda (char) (when (and (integerp char) (< char 128)) (setf char (code-char char))) (case char (#\" (princ "\\\"" stream)) (#\\ (princ "\\\\" stream)) (#\Backspace (princ "\\b" stream)) (#\Page (princ "\\f" stream)) (#\Newline (princ "\\n" stream)) (#\Return (princ "\\r" stream)) (#\Tab (princ "\\t" stream)) (otherwise (if (integerp char) (format stream "\\u~4,'0X" char) (if (or (char< char #\Space) (and escape-non-ascii (> (char-code char) 127))) (write-unicode stream (char-code char)) (princ char stream)))))) (if (stringp string) string (cdr string))) (princ #\" stream))) (defun json-write (token *json-stream*) (with-slots (state-stack multiple stream indent level) *json-stream* (let ((token-type (etypecase token (keyword token) (null nil) (real :number) (json-string :string)))) (labels ((write-begin-object () (begin-object) (push-state :beginning-of-object) (princ #\{ stream) (incf level)) (write-object-key (first) (check-key token) (unless first (princ #\, stream)) (write-indent) (write-escaped-string token) (princ #\: stream) (when indent (princ #\Space stream)) (switch-state :after-object-key)) (write-end-object () (end-object) (decf level) (write-indent) (princ #\} stream) (pop-state)) (write-begin-array () (push-state :beginning-of-array) (princ #\[ stream) (incf level)) (write-array-item (first) (unless first (princ #\, stream)) (write-indent) (switch-state :after-array-item) (write-value)) (write-end-array () (decf level) (write-indent) (princ #\] stream) (pop-state)) (write-value () (push-state :value) (reprocess)) (reprocess () (ecase (car state-stack) (:before-json-text (unless multiple (switch-state :after-json-text)) (ecase* token-type (:begin-object (write-begin-object)) (:begin-array (write-begin-array)) ((:true :false :null :string :number) (write-value)) (:eof (unless multiple (%json-error "Empty JSON text")) (switch-state :eof)))) (:after-json-text (ecase* token-type (:eof (switch-state :eof)))) (:beginning-of-object (ecase* token-type (:end-object (write-end-object)) (:string (write-object-key t)))) (:after-object-key (switch-state :after-object-value) (write-value)) (:after-object-value (ecase* token-type (:end-object (write-end-object)) (:string (write-object-key nil)))) (:value (pop-state) (ecase* token-type (:begin-object (write-begin-object)) (:begin-array (write-begin-array)) (:false (princ "false" stream)) (:null (princ "null" stream)) (:true (princ "true" stream)) (:string (write-escaped-string token)) (:number (write-number token)))) (:beginning-of-array (case token-type (:end-array (write-end-array)) (otherwise (write-array-item t)))) (:after-array-item (case token-type (:end-array (write-end-array)) (otherwise (write-array-item nil)))) (:eof (ecase* token-type (:eof)))))) (reprocess)))) token) (defmethod %json-close ((*json-stream* json-output-stream)) (json-write :eof *json-stream*)) (defun json-encode-key (key json-stream) (with-slots (key-encoder) json-stream (if key-encoder (funcall key-encoder key) key)))
7,365
Common Lisp
.lisp
183
27.377049
126
0.504536
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
97b924b78942dc8a5986e1ffa35d447e396b1dd64730f76bc8d9b21fc9d1302b
7,001
[ -1 ]
7,002
sb-cover.lisp
rotatef_json-streams/tests/sb-cover.lisp
(require :sb-cover) (declaim (optimize sb-cover:store-coverage-data)) (asdf:oos 'asdf:load-op :json-streams-tests :force t) (json-streams-tests::run-all-tests) (sb-cover:report "/tmp/report2/")
194
Common Lisp
.lisp
5
37.8
53
0.751323
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7a98bd4ea80edcb1ccd5099245c4b9c43f3062c10e3e3aba86cb812c309f61a8
7,002
[ -1 ]
7,003
input.lisp
rotatef_json-streams/tests/input.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (in-package :json-streams-tests) (defun run-all-tests () (quickcheck (random-test) (run-test-files) (json-test-suite-test-parsing))) (define (a-json-array) (cons :array (generate (a-list a-json-value)))) (define (a-json-object) (cons :object (remove-duplicates (loop for (key value) in (generate (a-list (a-tuple #'a-string a-json-value))) collect (cons key value)) :key #'car :test #'string=))) (define (a-double-float) (coerce (generate a-real) 'double-float)) (define (a-number) (generate (a-member an-integer a-double-float))) (define (a-json-text) (pick-weighted (5 (generate a-json-array)) (5 (generate a-json-object)) (1 (generate a-json-value)))) (define (a-json-value) (pick-weighted (10 :null) (10 (generate a-boolean)) (10 (generate a-number)) (10 (generate #'a-string)) (1 (generate (a-member a-json-array a-json-object))))) (defun random-test () (for-all ((json a-json-text)) (is= json (json-parse (princ (json-stringify json)))) (terpri) (terpri))) (defun run-test-files (&optional (dir (asdf:system-relative-pathname :json-streams "tests/"))) (dolist (file (directory (merge-pathnames "*/*.json" dir))) (run-test-file file))) (defun read-all-tokens (in options) (with-open-json-stream (jstream (apply #'make-json-input-stream in options)) (loop for token = (handler-case (json-read jstream) (json-parse-error () :error)) collect token until (member token '(:eof :error))))) (defmacro with-open-file* ((stream pathname &rest options) &body body) (let ((binary (gensym "BINARY-STREAM"))) `(with-open-file (,binary ,pathname :element-type 'flex:octet ,@options) (with-open-stream (,stream (flex:make-flexi-stream ,binary :external-format '(:utf-8 :eol-style :lf))) ,@body)))) (defun run-test-file (file) (with-open-file* (in (make-pathname :type "lisp" :defaults file)) (loop for options = (read in nil) for expected-tokens = (read in nil) while expected-tokens do (with-open-file* (in file) (loop for token-num from 0 for expected in expected-tokens for got in (read-all-tokens in options) do (named (format nil "~A ~S ~D" options (pathname-name file) token-num) (is= expected got))))))) (defun json-test-suite-test-file (pathname) (with-open-file* (in pathname) (let* ((tokens (read-all-tokens in '(:duplicate-key-check nil))) (errorsp (not (not (find :error tokens))))) (values (ecase (char (pathname-name pathname) 0) (#\y (not errorsp)) (#\n errorsp) (#\i t)) errorsp tokens (unless errorsp (with-output-to-string (out) (with-open-json-stream (json (make-json-output-stream out :duplicate-key-check nil)) (dolist (token tokens) (json-write token json))))))))) (defparameter *json-test-suite-skip-tests* '("i_string_iso_latin_1" "i_string_not_in_unicode_range" "i_string_overlong_sequence_2_bytes" "i_string_overlong_sequence_6_bytes" "i_string_overlong_sequence_6_bytes_null" "i_string_UTF-16LE_with_BOM" "i_string_UTF-8_invalid_sequence" "i_string_UTF8_surrogate_U+D800" "i_string_invalid_utf-8" "i_string_lone_utf8_continuation_byte" "i_string_truncated-utf-8" "i_string_utf16BE_no_BOM" "i_string_utf16LE_no_BOM" "n_array_a_invalid_utf8" "n_array_invalid_utf8" "n_number_invalid-utf-8-in-bigger-int" "n_number_invalid-utf-8-in-exponent" "n_number_invalid-utf-8-in-int" "n_number_real_with_invalid_utf8_after_e" "n_object_pi_in_key_and_trailing_comma" "n_string_invalid-utf-8-in-escape" "n_string_invalid_utf8_after_escape" "n_structure_incomplete_UTF8_BOM" "n_structure_lone-invalid-utf-8" "n_structure_single_eacute" "y_string_nonCharacterInUTF-8_U+FFFF")) (defun json-test-suite-test-parsing (&optional (dir (asdf:system-relative-pathname :json-streams "tests/JSONTestSuite/test_parsing/"))) (loop for file in (directory (merge-pathnames "*.json" dir)) for name = (pathname-name file) do (format t "~%~A ... " name) (finish-output) (if (find name *json-test-suite-skip-tests* :test #'string=) (princ "SKIP") (with-simple-restart (contiune "Test ~A" name) (multiple-value-bind (ok errorsp) (json-test-suite-test-file file) (when errorsp (princ "(error)")) (when ok (princ " PASSED")) (test ok))))))
5,657
Common Lisp
.lisp
134
34.865672
135
0.620978
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4d31f6ce408f432e76feb503fb33e45cd5c2f64c7092f67ace2cbfec798a537e
7,003
[ -1 ]
7,004
packages.lisp
rotatef_json-streams/tests/packages.lisp
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defpackage :json-streams-tests (:use :common-lisp :json-streams :cl-quickcheck))
872
Common Lisp
.lisp
18
47.277778
78
0.723329
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cf00777b7c60ca0e9a8a6cc61c3a89b2a616948c91b62f49764ce47d1192d0f1
7,004
[ -1 ]
7,005
pass2.lisp
rotatef_json-streams/tests/json.org/pass2.lisp
() (:begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array "Not too deep" :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :eof)
522
Common Lisp
.lisp
41
10.731707
15
0.741127
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a62647e58cbcb0e4424056d4e004a7dad2cd69943b00f1551a12717d31011a30
7,005
[ -1 ]
7,006
pass1.lisp
rotatef_json-streams/tests/json.org/pass1.lisp
() (:BEGIN-ARRAY "JSON Test Pattern pass1" :BEGIN-OBJECT "object with 1 member" :BEGIN-ARRAY "array with 1 element" :END-ARRAY :END-OBJECT :BEGIN-OBJECT :END-OBJECT :BEGIN-ARRAY :END-ARRAY -42 :TRUE :FALSE :NULL :BEGIN-OBJECT "integer" 1234567890 "real" -9876.543210d0 "e" 0.123456789d-12 "E" 1.23456789d34 "" 23456789012d66 "zero" 0 "one" 1 "space" " " "quote" "\"" "backslash" "\\" "controls" " " "slash" "/ & /" "alpha" "abcdefghijklmnopqrstuvwyz" "ALPHA" "ABCDEFGHIJKLMNOPQRSTUVWYZ" "digit" "0123456789" "0123456789" "digit" "special" "`1~!@#$%^&*()_+-={':[,]}|;.</>?" "hex" "ģ䕧覫췯ꯍ" "true" :TRUE "false" :FALSE "null" :NULL "array" :BEGIN-ARRAY :END-ARRAY "object" :BEGIN-OBJECT :END-OBJECT "address" "50 St. James Street" "url" "http://www.JSON.org/" "comment" "// /* <!-- --" "# -- --> */" " " " s p a c e d " :BEGIN-ARRAY 1 2 3 4 5 6 7 :END-ARRAY "compact" :BEGIN-ARRAY 1 2 3 4 5 6 7 :END-ARRAY "jsontext" "{\"object with 1 member\":[\"array with 1 element\"]}" "quotes" "&#34; \" %22 0x22 034 &#x22;" "/\\\"쫾몾ꮘﳞ볚 `1~!@#$%^&*()_+-=[]{}|;:',./<>?" "A key can be any string" :END-OBJECT 0.5d0 98.6d0 99.44d0 1066 10 1 0.1d0 1 2 2 "rosebud" :END-ARRAY :eof)
1,252
Common Lisp
.lisp
59
18.79661
97
0.609402
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e86474ccd3fdc003afdeaac4cc791e06998004ff5cb4bcc0c6385192a645a8b5
7,006
[ -1 ]
7,007
fail18.lisp
rotatef_json-streams/tests/json.org/fail18.lisp
() (:begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array :begin-array "Too deep" :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :end-array :eof)
543
Common Lisp
.lisp
43
10.651163
13
0.741483
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c8ec08735079373c9baab0f0800260994fc4933c75a812cd19965dcd633914fc
7,007
[ -1 ]
7,008
pass3.lisp
rotatef_json-streams/tests/json.org/pass3.lisp
() (:begin-object "JSON Test Pattern pass3" :begin-object "The outermost value" "must be an object or array." "In this test" "It is an object." :end-object :end-object :eof)
182
Common Lisp
.lisp
9
18.333333
52
0.715116
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0cce6504fe69a6c906d479ab079e7d6323d83be4ae3393781ccf8e2fe623db08
7,008
[ -1 ]
7,009
invalid-utf-16.lisp
rotatef_json-streams/tests/json-streams/invalid-utf-16.lisp
() (:begin-array :error) (:raw-strings t) (:begin-array (:string 109 105 115 115 105 110 103 32 116 114 97 105 108 49 58 32 #xD900) (:string 109 105 115 115 105 110 103 32 116 114 97 105 108 50 58 32 #xD900 66) (:string 109 105 115 115 105 110 103 32 116 114 97 105 108 51 58 32 #xD900 #x65) (:string 109 105 115 115 105 110 103 32 108 101 97 100 58 32 #xDC10) (:string 119 114 111 110 103 32 111 114 100 101 114 58 32 #xDD1E #xD834) :end-array :eof)
460
Common Lisp
.lisp
12
36.583333
81
0.704698
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
80dde39c9d2379194305bda584548277e82e64b64fada8c59115af295cdbf940
7,009
[ -1 ]
7,010
large-number.lisp
rotatef_json-streams/tests/json-streams/large-number.lisp
() (:begin-array 5d300 :error) (:use-ratios t) (:begin-array 5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 9007199254740993 :end-array :eof)
404
Common Lisp
.lisp
10
38.7
302
0.936387
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
026b682eb73583f1893c75b6589997d50f24af93c7795e07d29d07f185c38ce9
7,010
[ -1 ]
7,011
multi.lisp
rotatef_json-streams/tests/json-streams/multi.lisp
(:multiple t) (:begin-array "one" :end-array :begin-array "two" :end-array :begin-object "three" 3 :end-object :eof)
128
Common Lisp
.lisp
12
8.75
14
0.695652
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
81ecd5596c0916fc8c29277a4648817ae03c48334ea9d193b27bdc3ec15daeeb
7,011
[ -1 ]
7,012
json-streams-tests.asd
rotatef_json-streams/json-streams-tests.asd
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defsystem #:json-streams-tests :name "json-streams-tests" :licence "GNU General Public Licence 3.0" :depends-on (:json-streams :cl-quickcheck :flexi-streams) :components ((:module "tests" :serial t :components ((:file "packages") (:file "input")))))
1,144
Common Lisp
.asd
25
40.52
78
0.657424
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
cc2c52f5668b221c46ecb6c9ed9c80a847cf8a411dce5012d8060dd2b2c64886
7,012
[ -1 ]
7,013
json-streams.asd
rotatef_json-streams/json-streams.asd
;;;; json-streams ;;;; ;;;; Copyright (C) 2013 Thomas Bakketun <[email protected]> ;;;; ;;;; This library 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 3 of the License, or ;;;; (at your option) any later version. ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;;; GNU General Public License for more details. ;;;; ;;;; You should have received a copy of the GNU General Public License ;;;; along with this library. If not, see <http://www.gnu.org/licenses/>. (defsystem #:json-streams :name "json-streams" :licence "GNU General Public Licence 3.0" :author "Thomas Bakketun <[email protected]>" :description "A stream based JSON parser/writer, well suited for higher as building block for higher level libraries." :depends-on () :serial t :components ((:file "package") (:file "write-float") (:file "base") (:file "output-stream") (:file "input-stream") (:file "parse") (:file "output") (:file "stringify")))
1,366
Common Lisp
.asd
31
39.193548
120
0.662669
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
7d63795547e9b1e53f91784050b29799f4b8c355c681b5eaa27a951a926334db
7,013
[ -1 ]
7,021
.travis.yml
rotatef_json-streams/.travis.yml
language: lisp branches: only: - master env: matrix: - LISP=clisp - LISP=ccl - LISP=ecl - LISP=sbcl install: - curl -L https://github.com/luismbo/cl-travis/raw/master/install.sh | sh script: - cl -e "(ql:quickload :json-streams) (ql:quickload :json-streams-tests) (json-streams-tests::run-all-tests)"
333
Common Lisp
.l
14
20.5
111
0.685714
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c84007b1a0b36d070418326a9469674ecfa081616bafa2af6a445a893a1e0535
7,021
[ -1 ]
7,031
invalid-utf-16.json
rotatef_json-streams/tests/json-streams/invalid-utf-16.json
["missing trail1: \uD900", "missing trail2: \uD900B", "missing trail3: \uD900\u0065", "missing lead: \uDC10", "wrong order: \uDD1E\uD834"]
143
Common Lisp
.l
5
26.8
32
0.695652
rotatef/json-streams
20
2
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4691b67d85cb501b9e13b2a8c819dbf24d46d6851df221184e2c6a7faf41d2ba
7,031
[ -1 ]
7,048
main.lisp
kjinho_ciao/tests/main.lisp
(defpackage ciao/tests/main (:use :cl :ciao :rove)) (in-package :ciao/tests/main) ;; NOTE: To run this test file, execute `(asdf:test-system :brief-tools)' in your Lisp. (deftest test-target-1 (testing "should (= 1 1) to be true" (ok (= 1 1))))
271
Common Lisp
.lisp
9
26.222222
87
0.634615
kjinho/ciao
24
3
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b81284c07fdd0de9a222a4e11033afe91b57a2a8ab879f0ae8db51e319785b7c
7,048
[ -1 ]
7,049
ciao.asd
kjinho_ciao/ciao.asd
(defsystem "ciao" :description "OAuth 2.0 Client for Common Lisp" :author "Jin-Ho King <[email protected]>" :license "LGPLv3" :version "0.0.1" :serial t :depends-on (#:hunchentoot #:dexador #:cl-json #:trivial-open-browser) :components ((:module "src" :components ((:file "ciao")))) :in-order-to ((test-op (test-op "ciao/tests")))) (defsystem "ciao/tests" :author "Jin-Ho King" :license "LGPLv3" :depends-on ("ciao" "rove") :components ((:module "tests" :components ((:file "main")))) :description "Test system for ciao" :perform (test-op (op c) (symbol-call :rove :run c)))
734
Common Lisp
.asd
24
23.125
55
0.556497
kjinho/ciao
24
3
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0bd934a5c99f7aca9d7774131821517de2fac83b686647bc437c644dc1a3527e
7,049
[ -1 ]
7,066
package.lisp
ahungry_glyphs/package.lisp
;; Glyphs - Reducing verbosity in Common Lisp ;; Copyright (C) 2013 Matthew Carter ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; package.lisp (defpackage #:glyphs (:use #:cl #:cl-ppcre #:parenscript #:named-readtables) (:export #:ƒ #:ƒ→ #:ƒƒ #:λ #:λλ #:α #:*ψ* #:ψ #:± #:syntax #:in-readtable))
944
Common Lisp
.lisp
21
42
72
0.711454
ahungry/glyphs
29
0
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
98474159446d52b9d95156b96f28fa75b8a25a9fc1f67927aab1a0864b6ff90f
7,066
[ -1 ]
7,067
glyphs.lisp
ahungry_glyphs/glyphs.lisp
;; Glyphs - Reducing verbosity in Common Lisp ;; Copyright (C) 2013 Matthew Carter ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; glyphs.lisp (in-package #:glyphs) ;;; "glyphs" goes here. Hacks and glory await! (defparameter *ψ* "") (defun gscan (stream char) (declare (ignore char)) ;; Needed if manually setting end char (let ((replace-list (read-delimited-list #\~ stream t))) `(progn (setf *ψ* ,(car replace-list)) (cl-ppcre:scan *ψ* α)))) (defun greplace (stream char) (declare (ignore char)) (let ((replace-list (read-delimited-list #\| stream t))) `(progn (cl-ppcre:regex-replace-all *ψ* α ,(car replace-list))))) ;; https://stackoverflow.com/questions/19319277/how-to-define-symbols-that-will-work-like-and-by-symbol-macro (defreadtable glyphs:syntax (:fuze :standard) (:macro-char #\~ #'gscan) (:macro-char #\| #'greplace)) (defun flatten (structure) (cond ((null structure) nil) ((atom structure) (list structure)) (t (mapcan #'flatten structure)))) (defmacro arg-walker (&rest args) `(setf ,@(loop for arg in args for i from 0 collect arg collect `(nth ,i list-match)))) (defmacro pm (name args &rest rest) `(defun ,name ,args (let ((list-match ,(car args))) ,@rest))) (defmacro defn (name types args &rest rest) "Type safe defun" (let ((types (remove-if (lambda (x) (or (equal '-> x) (equal '→ x))) types))) `(progn (defun ,name ,args ,@(loop for arg in (cdr args) for type in types collect `(check-type ,arg ,type)) ,@rest) (declaim (ftype (function ,(butlast types) ,@(last types)) ,name))))) (defmacro ƒ→ (name types &rest rest) "Similar to defun, requires using α as the default case. Includes the type safety of defn." `(defn ,name ,types (&optional glyphs:α ,@(remove-duplicates (loop for arg in (flatten rest) when (and (symbolp arg) (or (string= arg '? :end1 1) (string= arg 'α :end1 1)) (> (length (string arg)) 1)) collect arg))) (let ((glyphs:α (or glyphs:α t))) (cond ,@(loop for arg in rest for iter from 0 when (and (symbolp arg) (or (string= '→ arg) (string= '-> arg))) collect `(,(if (consp (nth (1- iter) rest)) `,(nth (1- iter) rest) `(equal glyphs:α ,(nth (1- iter) rest))) ,(nth (1+ iter) rest))))))) (defmacro ƒ (name &rest rest) "Similar to defun, requires using x as the default case" `(defun ,name (&optional glyphs:α ,@(remove-duplicates (loop for arg in (flatten rest) when (and (symbolp arg) (or (string= arg '? :end1 1) (string= arg 'α :end1 1)) (> (length (string arg)) 1)) collect arg))) (let ((glyphs:α (or glyphs:α t))) (cond ,@(loop for arg in rest for iter from 0 when (and (symbolp arg) (or (string= '→ arg) (string= '-> arg))) collect `(,(if (consp (nth (1- iter) rest)) `,(nth (1- iter) rest) `(equal glyphs:α ,(nth (1- iter) rest))) ,(nth (1+ iter) rest))))))) (defmacro f (&rest rest) "Good old ascii alternate for the ƒ macro" `(ƒ ,@rest)) (parenscript:defmacro+ps ƒƒ (name &rest rest) "PS - Similar to defun, requires using x as the default case" `(defun ,name (&optional glyphs:α ,@(remove-duplicates (loop for arg in (flatten rest) when (and (symbolp arg) (or (string= arg '? :end1 1) (string= arg 'α :end1 1)) (> (length (string arg)) 1)) collect arg))) (cond ,@(loop for arg in rest for iter from 0 when (and (symbolp arg) (or (string= '→ arg) (string= '-> arg))) collect `(,(if (consp (nth (1- iter) rest)) `,(nth (1- iter) rest) `(equal glyphs:α ,(nth (1- iter) rest))) ,(nth (1+ iter) rest)))))) (parenscript:defmacro+ps ff (&rest rest) `(ƒƒ ,@rest)) (defmacro λ (&rest rest) "Similar to lambda, requires using x as the default case" `(lambda (&optional glyphs:α ,@(remove-duplicates (loop for arg in (flatten rest) when (and (symbolp arg) (or (string= arg '? :end1 1) (string= arg 'α :end1 1)) (> (length (string arg)) 1)) collect arg))) (cond ,@(loop for arg in rest for iter from 0 when (and (symbolp arg) (or (string= '→ arg) (string= '-> arg))) collect `(,(if (consp (nth (1- iter) rest)) `,(nth (1- iter) rest) `(equal glyphs:α ,(nth (1- iter) rest))) ,(nth (1+ iter) rest)))))) (defmacro /. (&rest rest) `(λ ,@rest)) (parenscript:defmacro+ps λλ (&rest rest) "PS - Similar to lambda, requires using x as the default case" `(lambda (&optional glyphs:α ,@(remove-duplicates (loop for arg in (flatten rest) when (and (symbolp arg) (or (string= arg '? :end1 1) (string= arg 'α :end1 1)) (> (length (string arg)) 1)) collect arg))) (cond ,@(loop for arg in rest for iter from 0 when (and (symbolp arg) (or (string= '→ arg) (string= '-> arg))) collect `(,(if (consp (nth (1- iter) rest)) `,(nth (1- iter) rest) `(equal glyphs:α ,(nth (1- iter) rest))) ,(nth (1+ iter) rest)))))) (parenscript:defmacro+ps /./. (&rest rest) `(λλ ,@rest)) (defmacro ψ (data &rest rest) "Shortcut for a mapcar with the short lambda stuff" `(mapcar (λ ,@rest) ,data)) (defmacro ± (a b) `(loop for x from ,(- a b) to ,(+ a b) collect x)) (defmacro afn (n &rest r) "Define a function with an anaphoric it. arity/1" `(defun ,n (it) ,@r))
7,397
Common Lisp
.lisp
177
29.960452
109
0.508263
ahungry/glyphs
29
0
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
af784b32b020ac0c1e70248359bce34b19e54f49314fdbd910d08164cc01d27b
7,067
[ -1 ]
7,068
tests.lisp
ahungry_glyphs/tests/tests.lisp
(in-package :glyphs-test) (in-root-suite) (defsuite root-suite) (in-suite root-suite) (in-readtable glyphs:syntax) (ƒ addition α → (+ α αb)) (ƒ any-cats? ~"cat"~ → "yes" α → "no") (ƒ bad-to-good-sad-to-happy ~"bad"~ → |"good"| ~"sad"~ → |"happy"| α → α) (ƒ facto 0 → 1 α → (* α (facto (1- α)))) (deftest function-define () (is (= (+ 3 2) (addition 3 2)))) (deftest regex-matching () (is (equal "yes" (any-cats? "I love cats"))) (is (equal "no" (any-cats? "I love dogs")))) (deftest regex-replacement () (is (equal "I'm a good boy" (bad-to-good-sad-to-happy "I'm a bad boy"))) (is (equal "I'm a happy boy" (bad-to-good-sad-to-happy "I'm a sad boy"))) (is (equal "I'm a boy" (bad-to-good-sad-to-happy "I'm a boy")))) (deftest mapped-results () (is (equal '(12 15 18) (mapcar (λ α → (+ α αb αc)) '(1 2 3) '(4 5 6) '(7 8 9))))) (deftest facto-test () (is (= 40320 (facto 8)))) (defun run-tests () (root-suite))
1,031
Common Lisp
.lisp
34
25.676471
75
0.562698
ahungry/glyphs
29
0
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ab0705f6044e2c5f6c5eb9eaf82ca8c60937067968156491ed53679078dc7e65
7,068
[ -1 ]
7,069
glyphs-test.asd
ahungry_glyphs/glyphs-test.asd
;; Glyphs - Reducing verbosity in Common Lisp ;; Copyright (C) 2013 Matthew Carter ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; glyphs.asd (asdf:defsystem #:glyphs-test :serial t :description "Tests for Glyphs to reduce Common Lisp verbosity" :author "Matthew Carter <[email protected]>" :license "GPLv3" :depends-on (#:glyphs #:stefil) :components ((:file "tests/package") (:file "tests/tests")))
1,047
Common Lisp
.asd
25
39.12
72
0.727451
ahungry/glyphs
29
0
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c2d61eb2c17fca63244fc57d9e29f66a694fab40daa8591f3a3c3f7f7fb5b41e
7,069
[ -1 ]
7,070
glyphs.asd
ahungry_glyphs/glyphs.asd
;; Glyphs - Reducing verbosity in Common Lisp ;; Copyright (C) 2013 Matthew Carter ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <http://www.gnu.org/licenses/>. ;;;; glyphs.asd (asdf:defsystem #:glyphs :serial t :description "Glyphs to reduce Common Lisp verbosity" :author "Matthew Carter <[email protected]>" :license "GPLv3" :depends-on (#:cl-ppcre #:parenscript #:named-readtables) :components ((:file "package") (:file "glyphs")))
1,062
Common Lisp
.asd
26
37.576923
72
0.717602
ahungry/glyphs
29
0
0
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
bcc9d00a4b89207fb998b70ffc0a68acb2220e58587c3215a8c2410ab73e784b
7,070
[ -1 ]
7,091
shotgun.lisp
borodust_notalone/shotgun.lisp
(cl:in-package :notalone) (define-image shotgun-fire "images/shotgun_fire.png") (define-sound shotgun "sounds/shotgun.wav") (defclass shotgun (positionable renderable) ((fire-animation))) (defmethod initialize-instance :after ((this shotgun) &key) (with-slots (fire-animation) this (setf fire-animation (make-animation '((0 0 160 160 0.0) (160 0 320 160 0.1) (320 0 480 160 0.15) (480 0 600 160 0.20) (0 0 0 0 0.3)))))) (defun pull-trigger (shotgun) (with-slots (fire-animation) shotgun (play-sound 'shotgun) (start-animation fire-animation (bodge-util:real-time-seconds)))) (defun shot-expired-p (shotgun current-time) (with-slots (fire-animation) shotgun (> (- current-time (start-time-of fire-animation)) (animation-length fire-animation)))) (defmethod render ((this shotgun)) (with-slots (fire-animation) this (with-pushed-canvas () (rotate-canvas (- (/ pi 2))) (let* ((frame (get-frame fire-animation (bodge-util:real-time-seconds))) (origin (keyframe-origin frame)) (end (keyframe-end frame))) (draw-image (vec2 -80 0) 'shotgun-fire :origin origin :width (- (x end) (x origin)) :height (- (y end) (y origin)))))))
1,428
Common Lisp
.lisp
31
35.129032
76
0.576479
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c78aad9f33237aebb82e041608b9539c647cc8d969281028385acdd28998c01e
7,091
[ -1 ]
7,092
math.lisp
borodust_notalone/math.lisp
(cl:in-package :notalone) ;; https://codereview.stackexchange.com/a/86428 (defun intersect-p (segment-start segment-end circle-center circle-radius) (let* ((p1 segment-start) (p2 segment-end) (q circle-center) (r circle-radius) (v (subt p2 p1)) (a (ge.ng:dot v v)) (b (* 2 (ge.ng:dot v (subt p1 q)))) (c (+ (ge.ng:dot p1 p1) (ge.ng:dot q q) (- (* 2 (ge.ng:dot p1 q))) (- (expt r 2)))) (disc (- (expt b 2) (* 4 a c)))) (if (< disc 0) nil (let* ((sqrt-disc (sqrt disc)) (t1 (/ (+ (- b) sqrt-disc) (* 2 a))) (t2 (/ (- (- b) sqrt-disc) (* 2 a)))) (or (<= 0 t1 1) (<= 0 t2 1)))))) (defun rotate-vec (vec angle) (vec2 (- (* (x vec) (cos angle)) (* (y vec) (sin angle))) (+ (* (x vec) (sin angle)) (* (y vec) (cos angle)))))
953
Common Lisp
.lisp
26
26.615385
74
0.430736
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9b553124c0403c98ecadc217119441c9a51d43a6c54fb145b9dc0bbcedf9bae3
7,092
[ -1 ]
7,093
zombie.lisp
borodust_notalone/zombie.lisp
(cl:in-package :notalone) (define-image zombie "images/zombie.png") (define-sound brains-1 "sounds/spooky/brains.ogg") (define-sound brains-2 "sounds/spooky/brains2.ogg") (define-sound brains-3 "sounds/spooky/brains3.ogg") (define-sound groan "sounds/spooky/groan.ogg") (define-sound crackly-groan "sounds/spooky/crackly_groan.ogg") (define-constant +zombie-spawn-sounds+ #(brains-1 brains-2 brains-3 groan) :test #'equalp) (defparameter *zombie-walk-front* (make-animation '((0 219 62 291 0) (124 219 186 291 0.25) (0 219 62 291 0.5)) :looped-p t)) (defparameter *zombie-walk-back* (make-animation '((0 72 62 144 0) (125 72 186 144 0.25) (0 72 62 144 0.5)) :looped-p t)) (defparameter *zombie-walk-right* (make-animation '((0 144 62 219 0) (121 145 186 219 0.25) (0 144 62 219 0.5)) :looped-p t)) (defparameter *zombie-walk-left* (make-animation '((0 0 60 72 0) (120 1 186 72 0.25) (0 0 60 72 0.5)) :looped-p t)) (defparameter *zombie-speed* 110) (defclass zombie (movable renderable) ()) (defun seek-player (zombie player) (if (dead-p player) (setf (velocity-of zombie) (vec2 0 0)) (let* ((zombie-position (position-of zombie)) (player-position (position-of player))) (setf (velocity-of zombie) (mult (ge.ng:normalize (vec2 (- (x player-position) (x zombie-position) 30) (- (y player-position) (y zombie-position) 35))) *zombie-speed*))))) (defmethod render ((this zombie)) (let* ((frame (get-frame *zombie-walk-front* (bodge-util:real-time-seconds))) (origin (keyframe-origin frame)) (end (keyframe-end frame))) (draw-image *viewport-origin* 'zombie :origin (keyframe-origin frame) :width (- (x end) (x origin)) :height (- (y end) (y origin)))))
2,771
Common Lisp
.lisp
47
34.085106
88
0.428254
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
78b5908fcb0e121ce50a5917114fc45b6182afca6ecda84a06ab96f6d0c96186
7,093
[ -1 ]
7,094
player.lisp
borodust_notalone/player.lisp
(cl:in-package :notalone) (defvar *player-speed* 100) ; px/sec (defclass player (movable renderable) ((dead-p :initform nil :reader dead-p))) (defun kill-player (player) (with-slots (dead-p) player (setf dead-p t))) (defgeneric look-at (player x y) (:method (player x y))) (defmethod look-at ((player player) x y) (setf (angle-of player) (atan (- y (y *viewport-center*)) (- x (x *viewport-center*))))) (defmethod render ((this player)) (with-pushed-canvas () (rotate-canvas (- (/ pi 2))) (let ((start-angle (* 2.5 (/ pi 8))) (end-angle (* 5.5 (/ pi 8))) (radius 250) (aa-delta 1.0)) (draw-arc *viewport-origin* radius start-angle end-angle :fill-paint *white*) (draw-polygon (list (vec2 -5 0) (vec2 5 0) (vec2 (* radius (cos start-angle)) (+ aa-delta (* radius (sin start-angle)))) (vec2 (* radius (cos end-angle)) (+ aa-delta (* radius (sin end-angle))))) :fill-paint *white*) (draw-arc (vec2 0 -9) 10 start-angle end-angle :fill-paint *black*))))
1,103
Common Lisp
.lisp
24
38.583333
103
0.579588
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
06e83aeb55f387afa8d5a3c3263860d2a23f52003b14ccf70a7917d3f8508aeb
7,094
[ -1 ]
7,095
util.lisp
borodust_notalone/util.lisp
(cl:in-package :notalone) (defvar *black* (vec4 0 0 0 1)) (defvar *white* (vec4 1 1 1 1)) (defvar *viewport-width* 800) (defvar *viewport-height* 600) (defvar *viewport-origin* (vec2 0 0)) (defvar *viewport-center* (vec2 (/ *viewport-width* 2) (/ *viewport-height* 2))) (define-constant +diagonal-unit+ 0.70710677 :test #'=) ;;; ;;; Rendering ;;; (defgeneric render (object) (:method (object) (declare (ignore object)))) (defclass renderable () ()) (defmethod render :around ((this renderable)) (with-pushed-canvas () (call-next-method))) ;;; ;;; Position ;;; (defgeneric (setf position-of) (vec2 positionable)) (defclass positionable () ((position :initform (vec2 0 0) :initarg :position :reader position-of) (angle :initform 0 :initarg :angle :accessor angle-of))) (defmethod (setf position-of) ((vec vec2) (this positionable)) (setf (x (position-of this)) (x vec) (y (position-of this)) (y vec)) (position-of this)) (defmethod (setf position-of) ((vec vec2) (this positionable)) (setf (x (position-of this)) (x vec) (y (position-of this)) (y vec)) (position-of this)) ;;; ;;; Moving ;;; (defclass movable (positionable) ((velocity :initform (vec2 0 0) :accessor velocity-of) (last-updated :initform (bodge-util:real-time-seconds)))) (defun calc-position (movable current-time) (with-slots (last-updated) movable (if (/= current-time last-updated) (let ((time-delta (- current-time last-updated))) (setf last-updated current-time (position-of movable) (add (position-of movable) (mult (velocity-of movable) time-delta)))) (position-of movable)))) ;;; ;;; Keyboard ;;; (defgeneric press-key (keyboard key) (:method (keyboard key))) (defgeneric release-key (keyboard key) (:method (keyboard key))) (defclass keyboard () ((pressed-keys :initform nil :reader key-combination-of) (state-listener :initarg :on-state-change))) (defun %invoke-state-listener (keyboard) (with-slots (state-listener) keyboard (when state-listener (funcall state-listener keyboard)))) (defmethod press-key ((keyboard keyboard) key) (with-slots (pressed-keys state-listener) keyboard (push key pressed-keys) (%invoke-state-listener keyboard))) (defmethod release-key ((keyboard keyboard) key) (with-slots (pressed-keys) keyboard (deletef pressed-keys key) (%invoke-state-listener keyboard))) (defun key-combination-pressed-p (keyboard &rest keys) (with-slots (pressed-keys) keyboard (set-equal (intersection pressed-keys keys) keys)))
2,625
Common Lisp
.lisp
72
32.444444
85
0.685068
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c6f861313cd551a5e7611ba0650d7e64ba2aace91181ba863480f227f5ce5d81
7,095
[ -1 ]
7,096
main.lisp
borodust_notalone/main.lisp
(cl:in-package :notalone) (define-sound orbital-colossus "sounds/Orbital_Colossus.ogg") (register-resource-package :notalone (asdf:system-relative-pathname :notalone "assets/")) (defgame notalone () ((world :initform (make-instance 'world)) (game-state)) (:viewport-width *viewport-width*) (:viewport-height *viewport-height*) (:viewport-title "NOTALONE") (:prepare-resources nil)) (defmethod post-initialize :after ((this notalone)) (with-slots (game-state) this (setf game-state (make-instance 'resource-preparation)) (flet ((%look-at (x y) (look-at game-state x y))) (bind-cursor #'%look-at)) (labels ((%bind-button (button) (bind-button button :pressed (lambda () (press-key game-state button))) (bind-button button :released (lambda () (release-key game-state button))))) (%bind-button :w) (%bind-button :a) (%bind-button :s) (%bind-button :d) (%bind-button :enter)) (bind-button :mouse-left :pressed (lambda () (shoot game-state))) (bind-button :escape :pressed #'gamekit:stop) (prepare-resources 'zombie 'brains-1 'brains-2 'brains-3 'groan 'crackly-groan 'shotgun-fire 'shotgun 'orbital-colossus))) (defmethod notice-resources ((this notalone) &rest resource-names) (declare (ignore resource-names)) (with-slots (game-state world) this (labels ((restart-game () (setf world (make-instance 'world)) (start-game)) (end-game () (setf game-state (make-instance 'game-end :world world :restart #'restart-game))) (start-game () (setf game-state (make-instance 'game :end #'end-game :world world)))) (setf game-state (make-instance 'game-start :start #'start-game))))) (defun unbind-buttons () (loop for button in '(:w :a :s :d :mouse-left) do (bind-button button :pressed nil) do (bind-button button :released nil))) (defmethod draw ((this notalone)) (with-slots (game-state) this (render game-state))) (defmethod act ((this notalone)) (with-slots (game-state) this (act game-state))) (defun play-game (&optional blocking) (gamekit:start 'notalone :blocking blocking))
2,395
Common Lisp
.lisp
56
34.196429
96
0.611374
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d50f48b26c60e4bec0be3abd632c19f17b6bcd9530974b522555695be2ece052
7,096
[ -1 ]
7,097
state.lisp
borodust_notalone/state.lisp
(cl:in-package :notalone) (defgeneric shoot (keyboard) (:method (keyboard))) (defclass game-state () ()) (defmethod act ((this game-state)) (declare (ignore this))) ;;; ;;; ;;; (defclass resource-preparation (game-state) ()) (defmethod render ((this resource-preparation)) (draw-rect *viewport-origin* *viewport-width* *viewport-height* :fill-paint *black*) (draw-text "NOTALONE" (vec2 320 400) :fill-color *white*) (draw-text "Loading..." (vec2 330 100) :fill-color *white*)) ;;; ;;; ;;; (defclass game-start (game-state) ((start-callback :initarg :start))) (defmethod initialize-instance :after ((this game-start) &key) (play-sound 'crackly-groan :looped-p t)) (defmethod press-key ((this game-start) (key (eql :enter))) (with-slots (start-callback) this (stop-sound 'crackly-groan) (funcall start-callback))) (defmethod render ((this game-start)) (draw-rect *viewport-origin* *viewport-width* *viewport-height* :fill-paint *black*) (draw-text "NOTALONE" (vec2 320 400) :fill-color *white*) (draw-text "Press Enter to start" (vec2 280 100) :fill-color *white*)) ;;; ;;; ;;; (defclass game (game-state) ((keyboard) (last-groan :initform 0) (end-callback :initarg :end) (last-zombie-spawned :initform 0) (world :initarg :world))) (defmethod press-key ((this game) key) (with-slots (keyboard) this (press-key keyboard key))) (defmethod release-key ((this game) key) (with-slots (keyboard) this (release-key keyboard key))) (defmethod shoot ((this game)) (with-slots (world) this (fire-shotgun world))) (defun key-combination-to-velocity (keyboard) (cond ((key-combination-pressed-p keyboard :w :d) (vec2 +diagonal-unit+ +diagonal-unit+)) ((key-combination-pressed-p keyboard :s :d) (vec2 +diagonal-unit+ (- +diagonal-unit+))) ((key-combination-pressed-p keyboard :a :s) (vec2 (- +diagonal-unit+) (- +diagonal-unit+))) ((key-combination-pressed-p keyboard :a :w) (vec2 (- +diagonal-unit+) +diagonal-unit+)) ((key-combination-pressed-p keyboard :w) (vec2 0 1)) ((key-combination-pressed-p keyboard :a) (vec2 -1 0)) ((key-combination-pressed-p keyboard :s) (vec2 0 -1)) ((key-combination-pressed-p keyboard :d) (vec2 1 0)) (t (vec2 0 0)))) (defmethod look-at ((this game) x y) (with-slots (world) this (look-at (player-of world) x y))) (defmethod initialize-instance :after ((this game) &key) (with-slots (keyboard world) this (labels ((update-velocity (keyboard) (setf (velocity-of (player-of world)) (mult (key-combination-to-velocity keyboard) *player-speed*)))) (setf keyboard (make-instance 'keyboard :on-state-change #'update-velocity)) (play-sound 'orbital-colossus)))) (defmethod act ((this game)) (with-slots (world last-zombie-spawned end-callback last-groan) this (lead-zombies world) (unless (dead-p (player-of world)) (let ((current-time (bodge-util:real-time-seconds)) (player-position (position-of (player-of world)))) (when (> (- current-time last-groan) 2) (play-sound (aref +zombie-spawn-sounds+ (random (length +zombie-spawn-sounds+)))) (setf last-groan current-time)) (when (> (- current-time last-zombie-spawned) 1) (setf last-zombie-spawned current-time) (let* ((angle (random (* 2 pi))) (position (add player-position (mult (rotate-vec (vec2 1 0) angle) (+ 300 (random 300)))))) (spawn-zombie world (x position) (y position))))) (when (zombies-won-p world) (kill-player (player-of world)) (funcall end-callback))))) (defmethod render ((this game)) (with-slots (world) this (render world))) ;;; ;;; ;;; (defclass game-end (game-state) ((world :initarg :world) (restart-callback :initarg :restart))) (defmethod render ((this game-end)) (with-slots (world) this (render world) (draw-text "Press Enter to restart game" (vec2 250 100) :fill-color *white*))) (defmethod look-at ((this game-end) x y) (with-slots (world) this (look-at (player-of world) x y))) (defmethod press-key ((this game-end) (key (eql :enter))) (with-slots (restart-callback) this (funcall restart-callback)))
4,358
Common Lisp
.lisp
105
36.095238
97
0.648931
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
b40e97cc0bac5b7db210b62289e1d7657e366406649f374c8e80ae0d176236fb
7,097
[ -1 ]
7,098
world.lisp
borodust_notalone/world.lisp
(cl:in-package :notalone) (defclass world (renderable) ((player :initform (make-instance 'player) :reader player-of) (frags :initform 0) (zombies :initform nil) (junk :initform nil) (shots :initform nil))) (defun zombie-hit-p (player zombie) (let ((player-pos (position-of player))) (intersect-p player-pos (add player-pos (mult (rotate-vec (vec2 1 0) (angle-of player)) 130)) (add (vec2 30 35) (position-of zombie)) 40))) (defun fire-shotgun (world) (with-slots (shots player zombies frags) world (setf shots (loop for shot in shots unless (shot-expired-p shot (bodge-util:real-time-seconds)) collect shot)) (let* ((player-pos (position-of player)) (shot (make-instance 'shotgun :position (vec2 (x player-pos) (y player-pos)) :angle (angle-of player)))) (pull-trigger shot) (push shot shots)) (setf zombies (loop for zombie in zombies as hit-p = (zombie-hit-p player zombie) when hit-p do (incf frags) unless hit-p collect zombie)))) (defun spawn-zombie (world x y) (with-slots (zombies) world (push (make-instance 'zombie :position (vec2 x y)) zombies))) (defun lead-zombies (world) (with-slots (zombies) world (loop for zombie in zombies do (seek-player zombie (player-of world))))) (defun zombies-won-p (world) (with-slots (zombies player) world (loop for zombie in zombies thereis (< (ge.ng:vector-length (subt (position-of player) (add (vec2 30 35) (position-of zombie)))) 50)))) (defmethod render ((this world)) (with-slots (player zombies junk shots frags) this (let ((player-position (calc-position player (bodge-util:real-time-seconds)))) (draw-rect *viewport-origin* *viewport-width* *viewport-height* :fill-paint *black*) (draw-text (format nil "~A" frags) (vec2 10 10) :fill-color *white*) (translate-canvas (x *viewport-center*) (y *viewport-center*)) (with-pushed-canvas () (rotate-canvas (angle-of player)) (render player)) (loop for zombie in zombies do (with-pushed-canvas () (let ((zombie-pos (calc-position zombie (bodge-util:real-time-seconds)))) (translate-canvas (- (x zombie-pos) (x player-position)) (- (y zombie-pos) (y player-position)))) (render zombie))) (loop for thing in junk do (with-pushed-canvas () (translate-canvas (- (x (position-of junk)) (x player-position)) (- (y (position-of junk)) (y player-position))) (render junk))) (loop for shot in shots do (with-pushed-canvas () (let ((shot-position (position-of shot))) (translate-canvas (- (x shot-position) (x player-position)) (- (y shot-position) (y player-position)))) (rotate-canvas (angle-of shot)) (render shot))) (when (dead-p player) (draw-text "YOU DIED" (vec2 -50 100) :fill-color *black*) (draw-text "YOU DIED" (vec2 -50 -100) :fill-color *white*)))))
3,355
Common Lisp
.lisp
69
37.405797
97
0.574572
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a0b0991604ef2c8e1c5e5c9f991dcd2e907d4c73a1d7b1dbac82173280989a9b
7,098
[ -1 ]
7,099
junk.lisp
borodust_notalone/junk.lisp
(cl:in-package :notalone) (defclass junk (positionable renderable) ()) (defmethod render ((this junk)) (draw-rect *viewport-origin* 80 30 :stroke-paint (vec4 0 0 0 1) :thickness 1.5))
190
Common Lisp
.lisp
4
45
82
0.725275
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
fb282d2db0b2f785d17782590c71ca637906ef480b4edcb44246d52b8c219159
7,099
[ -1 ]
7,100
animation.lisp
borodust_notalone/animation.lisp
(cl:in-package :notalone) (defstruct keyframe (origin (vec2 0 0) :type vec2 :read-only t) (end (vec2 0 0) :type vec2 :read-only t) (time 0 :type single-float :read-only t)) (defclass animation () ((sequence :initarg :sequence :initform nil) (looped-p :initarg :looped-p :initform nil) (started :initform 0 :reader start-time-of))) (defun make-animation (sequence &key looped-p) (let ((frames (loop for (x-orig y-orig x-end y-end time) in (sort sequence #'< :key #'fifth) collect (make-keyframe :origin (vec2 x-orig y-orig) :end (vec2 x-end y-end) :time (bodge-util:f time))))) (make-instance 'animation :looped-p looped-p :sequence (make-array (length frames) :element-type 'keyframe :initial-contents frames)))) (defun start-animation (animation current-time) (with-slots (started) animation (setf started current-time))) (defun animation-length (animation) (with-slots (sequence) animation (- (keyframe-time (aref sequence (1- (length sequence)))) (keyframe-time (aref sequence 0))))) (defun get-looped-time (animation time) (let* ((animation-length (animation-length animation))) (if (= animation-length 0) 0 (mod time animation-length)))) (defun get-frame (animation current-time) (with-slots (sequence started looped-p) animation (let* ((time-delta (- current-time started)) (animation-timestamp (if looped-p (get-looped-time animation time-delta) time-delta))) (multiple-value-bind (result idx) (bodge-util:search-sorted animation-timestamp sequence :test #'= :key #'keyframe-time) (or result (aref sequence (max (1- idx) 0)))))))
1,876
Common Lisp
.lisp
38
39.447368
97
0.61239
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
0c79107feb4a275b026d09cbf9194b151445f47ee45d459d5ba931a63e1d9f1f
7,100
[ -1 ]
7,101
packages.lisp
borodust_notalone/packages.lisp
(cl:defpackage :notalone (:use :cl :alexandria :trivial-gamekit) (:shadowing-import-from :trivial-gamekit :lerp) (:export play-game))
166
Common Lisp
.lisp
5
25.8
42
0.621118
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f575b97238038c37950979905769deb8936551568499bce2b88be32a48210549
7,101
[ -1 ]
7,102
notalone.asd
borodust_notalone/notalone.asd
(asdf:defsystem :notalone :description "Autumn 2017 Lisp Game Jam entry" :license "GPLv3" :version "1.0.0" :author "Pavel Korolev <[email protected]>" :depends-on (alexandria bodge-utilities trivial-gamekit) :serial t :components ((:file "packages") (:file "util") (:file "math") (:file "animation") (:file "player") (:file "zombie") (:file "junk") (:file "shotgun") (:file "world") (:file "state") (:file "main")))
579
Common Lisp
.asd
18
22.055556
58
0.502674
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ef8e942b31a47b1aa7321bf9a785d03d797b7a69f63b07369b38027528bcae7e
7,102
[ -1 ]
7,112
.travis.yml
borodust_notalone/.travis.yml
language: common-lisp sudo: false addons: apt: packages: - zip env: global: - GAMEKIT_SYSTEM_NAME: notalone - GAMEKIT_APPLICATION_PACKAGE: notalone - GAMEKIT_APPLICATION_MAIN_CLASS: notalone - PATH: ~/bin/:$PATH - GAMEKIT_TARGET_PACKAGE: $GAMEKIT_SYSTEM_NAME-x86-64-$TRAVIS_OS_NAME-$TRAVIS_BRANCH.zip - GAMEKIT_BUILD_DIR: /tmp/$GAMEKIT_SYSTEM_NAME - secure: "DjslSWh4Wjqe/Jd90IwhUb9VZK22aPcIGqMu0era66YVOW6p6OgUGxpOj/w4DbqHcLQBdO6BCtckBV4DFmJPYtYd9wMxAyhi/h1GgeoKjhRDM29uJvPoAe3r4MJxm4zyY8jREQl/5YNN7Q/StrMMDQLWnUPwZZVQrVFd9ppkYrPqxfbsN9Bf3G2ijAdZtjnUlAZhSWS7zPUed6LsKWc9frl1ef1rdnDpCsH7XtqUrKLRvJOl4Gjijt64lkRgXc/QmeSIU7qU92WnV//2K/9RvGNRxspjJlIVGXXlE6Am3GntFSWBt7Vd9wdCNMbchG/d37v/nGm9JfOGuka1gAhOqf6tsrM6J3pAtw/b0q9PnN7YD4RGyuGsapxILFNnUndOGwFIVdll37GV7lH839rUUA4ORPHiv1KnrMS4vSaWX7hV9n9C1eUXhskLo2YnRRdcB3WmY4uP+h/z+tBlRnW84Fe1jxtWhTpDXHGHVQCFfi6mJoZhQ84FnUJZmEsXcMobjlapCkfjrvpIUSGp651H8GyuVoVGd0JqSz2fgf+o0W1Cmp/gggYJCSsMMERizJJ3lNwimkKtYOYRjY128U4BUGJibk0lMI9O0FUqnZ4jtUeIE06foLgcEGkz8gipB7BC3WcwA8IyNsgAWdNhxyOVMgyqU590C2gJ39rDw9mI8fA=" branches: only: - "/^v\\d+(\\.\\d+)+$/" os: - linux - osx install: - curl -L http://bodge.borodust.org/files/install.sh | sh -s ccl script: - > lisp $HOME/bodge/scripts/build-gamekit-system.lisp $GAMEKIT_SYSTEM_NAME $GAMEKIT_APPLICATION_PACKAGE $GAMEKIT_APPLICATION_MAIN_CLASS $TRAVIS_BUILD_DIR $GAMEKIT_BUILD_DIR before_deploy: - mv "$GAMEKIT_BUILD_DIR/$GAMEKIT_SYSTEM_NAME.zip" $GAMEKIT_TARGET_PACKAGE deploy: provider: releases api-key: $GITHUB_TOKEN file: $GAMEKIT_TARGET_PACKAGE skip_cleanup: true overwrite: true on: tags: true
1,661
Common Lisp
.l
39
39.487179
698
0.82342
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
ebd8d58e035d6013efa18bda62179882e3d9c5882a0b1b017bba53bc35c6de26
7,112
[ -1 ]
7,116
.appveyor.yml
borodust_notalone/.appveyor.yml
image: - Visual Studio 2017 platform: - x64 environment: global: GAMEKIT_SYSTEM_NAME: notalone GAMEKIT_APPLICATION_PACKAGE: notalone GAMEKIT_APPLICATION_MAIN_CLASS: notalone GAMEKIT_ARTIFACT: $(GAMEKIT_SYSTEM_NAME)-x86-64-windows-$(APPVEYOR_REPO_TAG_NAME).zip GAMEKIT_BUILD_DIR: $(TMP)\$(GAMEKIT_SYSTEM_NAME) skip_non_tags: true branches: only: - master - "/^v\\d+(\\.\\d+)+$/" install: - set PATH=C:\msys64\usr\bin\;%PATH% - pacman --noconfirm -S zip - sh -c "curl -L http://bodge.borodust.org/files/install.sh | sh -s ccl" build_script: - > sh -c "$HOME/bin/lisp $HOME/bodge/scripts/build-gamekit-system.lisp %GAMEKIT_SYSTEM_NAME% %GAMEKIT_APPLICATION_PACKAGE% %GAMEKIT_APPLICATION_MAIN_CLASS% $(cygpath -u '%APPVEYOR_BUILD_FOLDER%') $(cygpath -u '%GAMEKIT_BUILD_DIR%')" - mv %GAMEKIT_BUILD_DIR%\%GAMEKIT_SYSTEM_NAME%.zip %GAMEKIT_ARTIFACT% artifacts: - path: "%GAMEKIT_ARTIFACT%" name: release_archive deploy: provider: GitHub release: $(APPVEYOR_REPO_TAG_NAME) tag: $(APPVEYOR_REPO_TAG_NAME) description: $(APPVEYOR_REPO_COMMIT_MESSAGE) auth_token: secure: Z5XWjDOBlCrmfz3SQAjnLKtdgI5B2b/owJhRPNWYGrI+qwVNbBc4cZiroBZReWP7 artifact: release_archive force_update: true draft: false prerelease: false on: appveyor_repo_tag: true
1,334
Common Lisp
.l
43
27.604651
89
0.717849
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
549fcc95a979aa423e934cb32053a253f21706551d2f5a61cda82a159c8aca47
7,116
[ -1 ]
7,118
default.nix
borodust_notalone/nix/default.nix
with import <nixpkgs> {}; stdenv.mkDerivation { name = "notalone-1.2.2"; builder = ./builder.sh; nativeBuildInputs = [ pkgs.makeWrapper pkgs.patchelf ]; libPath = lib.makeLibraryPath [ pkgs.libGL pkgs.pulseaudio xorg.libXxf86vm xorg.libX11 xorg.libxcb xorg.libXinerama xorg.libXcursor xorg.libXrandr ]; src = fetchzip { url = "https://github.com/borodust/notalone/releases/download/v1.2.2/notalone-x86-64-linux-v1.2.2.zip"; sha256 = "03lqzk3nrqs8d0sd2xj78z1jijvjxvfh8dycq9vsbq53s6932qh5"; }; }
753
Common Lisp
.l
18
26.444444
107
0.519074
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c5f0cb000e826ad4f793b512b37f122979ebf9d76407381fa7e0c6dd08980f04
7,118
[ -1 ]
7,119
builder.sh
borodust_notalone/nix/builder.sh
source $stdenv/setup TARGET_DIR="$out" EXECUTABLE=$TARGET_DIR/notalone LIB_PATH="$TARGET_DIR/lib:$libPath" echo "LIB_PATH: $LIB_PATH" mkdir -p $TARGET_DIR cp -R $src/* $TARGET_DIR chmod +w $EXECUTABLE patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $EXECUTABLE wrapProgram $TARGET_DIR/notalone --prefix LD_LIBRARY_PATH : "$LIB_PATH"
359
Common Lisp
.l
10
34.6
82
0.760116
borodust/notalone
23
1
1
GPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c4216d9bb3a223196008ba3df7b41db845a7eea5a9145b97081d8a16419c2d81
7,119
[ -1 ]
7,134
package.lisp
szos_cl-advice/package.lisp
;;;; package.lisp (defpackage #:cl-advice (:use #:cl) (:export #:advisable-function-p #:make-advisable #:make-unadvisable #:ensure-advisable-function #:ensure-unadvisable-function #:with-implicit-conversion #:with-unadvisable-function #:advisable-lambda #:defun-advisable #:*allow-implicit-conversion* #:define-advisory-functions #:add-advice #:replace-advice #:list-advice #:remove-advice #:remove-nth-advice #:implicit-conversion-to-advisable-function #:circular-advice-dependency))
703
Common Lisp
.lisp
21
22.095238
54
0.570992
szos/cl-advice
21
1
0
LGPL-2.1
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
976f61341db6b63c059558d4070e34c28391291bb1e8648b39e8b210f1ff7eb1
7,134
[ -1 ]
7,135
tests.lisp
szos_cl-advice/tests.lisp
(defpackage :cl-advice-tests (:use :cl :fiveam) (:import-from :cl-advice #:defun-advisable #:advisable-function-p #:make-advisable #:make-unadvisable #:add-advice #:remove-advice #:replace-advice) (:export :run-tests)) (in-package :cl-advice-tests) (defun run-tests () (fiveam:run! 'cl-advice-test-suite)) (def-suite* cl-advice-test-suite) (defun foutput (fun &rest args) (with-output-to-string (*standard-output*) (apply fun args))) (defun-advisable advisable-main () (format t "main.")) (defun main () (format t "main.")) (defun before () (format t "before.")) (defun after () (format t "after.")) (defun around (next) (format t "begin.") (funcall next) (format t "end.")) (defun before1 () (format t "before1.")) (def-test advice-tests () (is (string= (foutput 'advisable-main) "main.") "Advisable function") (is (advisable-function-p (symbol-function 'advisable-main)) "Is advisable") (is (string= (foutput 'main) "main.") "Without advice") (is (not (advisable-function-p (symbol-function 'main))) "Not advisable") (signals cl-advice:implicit-conversion-to-advisable-function (cl-advice:with-implicit-conversion (:disallowed) (add-advice :before 'main 'before)) "Add advice to non advisable fails") (make-advisable 'main) (is (advisable-function-p (symbol-function 'main)) "Is advisable") (is (string= (foutput 'main) "main.") "Eval after advisable") (add-advice :before 'main 'before) (is (string= (foutput 'main) "before.main.") "Before advice") (add-advice :before 'main 'before1) (is (string= (foutput 'main) "before1.before.main.") "Add before advice again") (replace-advice :before 'main 'before1 'before) (is (string= (foutput 'main) "before.before.main.") "Replace before advice") (remove-advice :before 'main 'before) (remove-advice :before 'main 'before1) (is (string= (foutput 'main) "main.") "After remove :before advice") (add-advice :after 'main 'after) (is (string= (foutput 'main) "main.after.") "After advice") (remove-advice :after 'main 'after) (is (string= (foutput 'main) "main.") "After remove :after advice") (add-advice :around 'main 'around) (is (string= (foutput 'main) "begin.main.end.") "Around advice") (remove-advice :around 'main 'around) (is (string= (foutput 'main) "main.") "After remove :around advice") ;; all advices (add-advice :before 'main 'before) (add-advice :after 'main 'after) (add-advice :around 'main 'around) (is (string= (foutput 'main) "before.begin.main.end.after.") "All advices") (make-unadvisable 'main) (is (string= (foutput 'main) "main.") "After make-unadvisable") (is (not (advisable-function-p (symbol-function 'main)))) ) (defun main-args (x y) (format t "main~a." (list x y))) (defun before-args (x y) (format t "before~a." (list x y))) (defun after-args (x y) (format t "after~a." (list x y))) (defun around-args (next x y) (format t "begin~a." (list x y)) (funcall next x y) (format t "end.")) (defun before1-args (x y) (format t "before1~a." (list x y))) (def-test advice-args-tests () (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "Without advice") (is (not (advisable-function-p (symbol-function 'main-args))) "Not advisable") (signals cl-advice:implicit-conversion-to-advisable-function (cl-advice:with-implicit-conversion (:disallowed) (add-advice :before 'main-args 'before-args)) "Add advice to non advisable fails") (make-advisable 'main-args) (is (advisable-function-p (symbol-function 'main-args)) "Is advisable") (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "Eval after advisable") (add-advice :before 'main-args 'before-args) (is (string= (foutput 'main-args 'x 'y) "before(X Y).main(X Y).") "Before advice") (add-advice :before 'main-args 'before1-args) (is (string= (foutput 'main-args 'x 'y) "before1(X Y).before(X Y).main(X Y).") "Add before advice again") (replace-advice :before 'main-args 'before1-args 'before-args) (is (string= (foutput 'main-args 'x 'y) "before(X Y).before(X Y).main(X Y).") "Replace before advice") (remove-advice :before 'main-args 'before-args) (remove-advice :before 'main-args 'before1-args) (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "After remove :before advice") (add-advice :after 'main-args 'after-args) (is (string= (foutput 'main-args 'x 'y) "main(X Y).after(X Y).") "After advice") (remove-advice :after 'main-args 'after-args) (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "After remove :after advice") (add-advice :around 'main-args 'around-args) (is (string= (foutput 'main-args 'x 'y) "begin(X Y).main(X Y).end.") "Around advice") (remove-advice :around 'main-args 'around-args) (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "After remove :around advice") ;; all advices (add-advice :before 'main-args 'before-args) (add-advice :after 'main-args 'after-args) (add-advice :around 'main-args 'around-args) (is (string= (foutput 'main-args 'x 'y) "before(X Y).begin(X Y).main(X Y).end.after(X Y).") "All advices") (make-unadvisable 'main-args) (is (string= (foutput 'main-args 'x 'y) "main(X Y).") "After make-unadvisable") (is (not (advisable-function-p (symbol-function 'main-args))))) (defun values-main (a b) (values a b)) (defun values-before (a b) (format t "Before(~A ~A)" a b)) (defun values-after (a b) (format t "After(~A ~A)" a b)) (defun values-around (next a b) (multiple-value-list (funcall next a b))) (def-test advice-multiple-values () (is (string= (foutput 'values-main 'a 'b) "") "Without advice") (is (equal (multiple-value-list (values-main 'a 'b)) (list 'a 'b)) "Check unadvised return value") (make-advisable 'values-main :arguments '(a b)) (is (advisable-function-p #'values-main) "Is advisable") (add-advice :around 'values-main 'values-around) (is (equal (values-main 'a 'b) (list 'a 'b)) "Around advice modifies return value") (add-advice :before 'values-main 'values-before) (add-advice :after 'values-main 'values-after) (is (string= (foutput 'values-main 'a 'b) "Before(A B)After(A B)") "Eval after adding before/after advice") (make-unadvisable 'values-main) (is (not (advisable-function-p #'values-main)) "Is unadvisable")) (defun circular-a () (format t "circular-a.")) (defun circular-b () (format t "circular-b.")) (defun circular-c () (format t "circular-c.")) (defun circular-d () (format t "circular-d.")) (def-test advice-circular-dependency-test () (mapc #'(lambda (f) (make-advisable f :arguments '())) '(circular-a circular-b circular-c circular-d)) (add-advice :before 'circular-a 'circular-b) (add-advice :before 'circular-b 'circular-c) (add-advice :before 'circular-c 'circular-d) (signals cl-advice:circular-advice-dependency (add-advice :before 'circular-d 'circular-a)) (signals cl-advice:circular-advice-dependency (add-advice :around 'circular-d 'circular-a)) (signals cl-advice:circular-advice-dependency (add-advice :after 'circular-d 'circular-a)) (mapc #'(lambda (f) (make-unadvisable f)) '(circular-a circular-b circular-c circular-d)))
7,379
Common Lisp
.lisp
164
40.810976
108
0.665825
szos/cl-advice
21
1
0
LGPL-2.1
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
1e1927d716c2310027cbaae769b19df244f4b8c6c33639f63afe0152902e6e80
7,135
[ -1 ]
7,136
cl-advice.asd
szos_cl-advice/cl-advice.asd
;;;; cl-advice.asd (asdf:defsystem #:cl-advice :description "Portable advice for Common Lisp" :author "szos at posteo dot net" :license "LGPL" :version "1.1.1" :serial t :depends-on (#:closer-mop) :components ((:file "package") (:file "cl-advice")) :in-order-to ((asdf:test-op (asdf:test-op :cl-advice-tests))))
345
Common Lisp
.asd
11
27.454545
64
0.645646
szos/cl-advice
21
1
0
LGPL-2.1
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a90591406dafdcdc014ab9629dc7dac3c5d3eca82b3467a6002b01a9986887ef
7,136
[ -1 ]
7,137
cl-advice-tests.asd
szos_cl-advice/cl-advice-tests.asd
;;;; cl-advice-tests.asd (asdf:defsystem #:cl-advice-tests :description "Tests for cl-advice" :author "szos at posteo dot net" :license "LGPL" :version "0.0.1" :serial t :depends-on (#:cl-advice #:fiveam) :components ((:file "tests")) :perform (asdf:test-op (op c) (uiop:symbol-call :cl-advice-tests :run-tests)))
357
Common Lisp
.asd
11
27.636364
73
0.631884
szos/cl-advice
21
1
0
LGPL-2.1
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c22b0dc922c4fb5dac3b81212cdfd541fe0544e94c39167ac2dc720a921977fa
7,137
[ -1 ]
7,157
filepaths.lisp
fosskers_filepaths/src/filepaths.lisp
(defpackage filepaths (:use :cl) ;; --- Structural tests --- ;; (:export #:rootp #:emptyp #:starts-with-p #:ends-with-p #:absolutep #:relativep #:directoryp) ;; --- Construction --- ;; (:export #:join) ;; --- Component Access --- ;; (:export #:base #:with-base #:name #:with-name #:parent #:with-parent #:extension #:with-extension #:drop-extension #:add-extension) ;; --- Conversion --- ;; (:export #:components #:from-list #:ensure-directory #:ensure-string #:ensure-path #:to-string #:from-string) ;; --- Conditions --- ;; (:export #:no-filename #:empty-path #:root-no-parent) (:documentation "Modern and consistent filepath manipulation.")) (in-package :filepaths) (defvar +empty-path+ #p"") (defvar +filesystem-root+ #p"/") (defvar +separator+ #\/) (declaim (ftype (function ((or pathname string)) boolean) rootp)) (defun rootp (path) "Is the given PATH the root directory?" (or (and (stringp path) (string-equal "/" path)) (and (pathnamep path) (equal +filesystem-root+ path)))) #+nil (rootp #p"/") (declaim (ftype (function ((or pathname string)) boolean) emptyp)) (defun emptyp (path) "Is the given PATH an empty string?" (or (and (stringp path) (= 0 (length path))) (and (pathnamep path) (equal +empty-path+ path)))) #+nil (emptyp #p"") (defun starts-with-p (path base) "Are the initial components of a PATH some BASE?" (let ((bools (mapcar #'equal (components path) (components base)))) (reduce (lambda (a b) (and a b)) bools :initial-value t))) #+nil (starts-with-p #p"/foo/bar/baz/zing.json" "/foo/bar") (defun ends-with-p (path child) "Are the final components of a PATH some given CHILD?" (let ((bools (mapcar #'equal (reverse (components path)) (reverse (components child))))) (reduce (lambda (a b) (and a b)) bools :initial-value t))) #+nil (ends-with-p #p"/foo/bar/baz/zing.json" "baz/zing.json") (declaim (ftype (function ((or pathname string)) boolean) absolutep)) (defun absolutep (path) "Yields T when the given PATH is a full, absolute path." (if (pathnamep path) (eq :absolute (car (pathname-directory path))) (and (< 0 (length path)) (equal +separator+ (char path 0))))) #+nil (absolutep "/home/colin/foo.txt") (declaim (ftype (function ((or pathname string)) boolean) relativep)) (defun relativep (path) "Yields T when the given PATH is a relative one." (not (absolutep path))) #+nil (relativep #p"/home/colin/foo.txt") #+nil (relativep #p"foo.txt") (declaim (ftype (function ((or pathname string)) boolean) directoryp)) (defun directoryp (path) "Yields T if the PATH represents a directory. Note that this only checks the formatting of the path, and does not query the filesystem." (if (pathnamep path) (and (not (null (pathname-directory path))) (not (pathname-name path))) (equal +separator+ (char path (1- (length path)))))) #+nil (directoryp "/foo/bar/") #+nil (directoryp "/foo/bar/baz.txt") (declaim (ftype (function ((or pathname string)) simple-string) base)) (defun base (path) "The non-extension, non-directory portion of the filename of a PATH." (let ((b (pathname-name path))) (if (not b) (error 'no-filename :path path) (string-if-keyword-impl-specific b)))) #+nil (base "/foo/bar/baz.txt") #+nil (base #p"/foo/bar/ゆびわ.txt") (declaim (ftype (function ((or pathname string) string) pathname) with-base)) (defun with-base (path new) "Swap the base portion of a PATH with a NEW one. Yields a new path object." (let ((path (ensure-path path))) (make-pathname :name new :type (pathname-type path) :directory (pathname-directory path) :version :newest))) #+nil (with-base #p"/foo/bar/baz.txt" "jack") (declaim (ftype (function ((or pathname string)) simple-string) name)) (defun name (path) "The filename of a PATH with no other directory components." (let ((n (file-namestring path))) (if (= 0 (length n)) (error 'no-filename :path path) n))) #+nil (name "/foo/bar/baz.txt") (declaim (ftype (function ((or pathname string) (or pathname string)) pathname) with-name)) (defun with-name (path new) "Swap the filename portion of a PATH with a NEW one. Yields a new path object." (let ((path (ensure-path path))) (make-pathname :name (base new) :type (extension new) :directory (pathname-directory path) :version :newest))) #+nil (with-name #p"/foo/bar/baz.txt" "jack.json") (declaim (ftype (function ((or pathname string)) pathname) parent)) (defun parent (path) "Yield PATH without its final component, if there is one." (cond ((emptyp path) (error 'empty-path)) ((rootp path) (error 'root-no-parent)) (t (let* ((s (ensure-string path)) (path (if (directoryp s) (string-right-trim "/" s) s))) (from-string (directory-namestring path)))))) #+nil (parent "/foo/bar/baz.txt") #+nil (parent "/foo/bar/") #+nil (parent "/foo/") (declaim (ftype (function ((or pathname string) (or pathname string)) pathname) with-parent)) (defun with-parent (path parent) "Swap the parent portion of a PATH." (join parent (name path))) #+nil (with-parent #p"/foo/bar/baz.json" #p"/zing") (declaim (ftype (function ((or pathname string)) (or simple-string null)) extension)) (defun extension (path) "The extension of a given PATH." (pathname-type path)) #+nil (extension #p"/foo/bar.json") #+nil (extension #p"/") (declaim (ftype (function ((or pathname string) string) pathname) with-extension)) (defun with-extension (path ext) "Swap the entire extension of a given PATH. Yields a new path object." (let ((path (ensure-path path))) (if (directoryp path) (error 'no-filename :path path) (make-pathname :name (base path) :type ext :directory (pathname-directory path) :version :newest)))) #+nil (with-extension #p"/foo/bar/baz.txt" "json") #+nil (with-extension #p"/foo/bar/" "json") (declaim (ftype (function ((or pathname string)) pathname) drop-extension)) (defun drop-extension (path) "Remove an extension from a PATH." (let* ((path (ensure-path path)) (stem (base path)) (ext (extension stem)) (name (if ext (base stem) stem))) ;; Similar to `add-extension', there's some cleverness here where we need to ;; check if we must move an "inner" extension back outward. For instance, in ;; the case of foo.json.zip. It looks like we're always setting `:type' to ;; something concrete, but this will properly be NIL in the normal case ;; where only one extension was present. (make-pathname :name name :type ext :directory (pathname-directory path) :version :newest))) #+nil (drop-extension #p"/foo/bar/baz.json") #+nil (drop-extension #p"/foo/bar/baz.json.zip") (declaim (ftype (function ((or pathname string) string) pathname) add-extension)) (defun add-extension (path ext) "Add an extension to the given path, even if it already has one." (let* ((path (ensure-path path)) (already (extension path))) (if already ;; The pathname type only wants a single extension present in the ;; `:type' field, or else there is strange behaviour elsewhere (for ;; instance involving `to-string'). The old extension must thus become ;; part of the stem, and the only value reported by `extension' is the ;; new one, not the composite. This behaviour reflects that of Rust's ;; standard library. (make-pathname :name (concatenate 'string (base path) "." already) :type ext :directory (pathname-directory path) :version :newest) (with-extension path ext)))) #+nil (add-extension #p"/foo/bar/baz.txt" "zip") (declaim (ftype (function ((or pathname string) (or pathname string) &rest (or pathname string)) pathname) join)) (defun join (parent child &rest components) "Combine two or more components together." (let* ((parent (ensure-path parent)) (combined (remove-if (lambda (s) (or (string-equal +separator+ s) (string-equal "" s))) (mapcan #'components (cons child components)))) (final (car (last combined))) (rest (butlast combined)) (abs-or-rel (if (absolutep parent) :absolute :relative)) (par-comps (components parent)) (final-base (base final))) (make-pathname :name (cond #+sbcl ((string-equal "**" final-base) (sbcl-wildcard)) #+(or abcl ccl allegro) ((string-equal "**" final-base) final-base) (t (keyword-if-special final-base))) :type (extension final) :version :newest :directory (cons abs-or-rel (mapcar #'keyword-if-special (append (if (absolutep parent) (cdr par-comps) par-comps) rest)))))) #+nil (join "/" "foo" "bar" ".." "." ".." "baz" "stuff.json") #+nil #p"/foo/bar/.././../baz/stuff.json" #+nil (join "/foo" "bar" "**" "*.json") #+nil (join "/foo" "bar" "**.json") #+nil (join "/foo" "bar" "baz" "test.json") #+nil (join "/foo/bar" "baz/test.json") (declaim (ftype (function ((or pathname string)) list) components)) (defun components (path) "Every component of a PATH broken up as a list." (cond ((emptyp path) '()) ;; HACK 2024-06-17 Until ECL/Clasp support `**' in `:name' position. ;; ;; And not even a good hack, since it can be broken in cases where the ;; `**' comes at the end. #+(or ecl clasp) ((and (stringp path) (string-equal "**" path)) '("**")) (t (let* ((path (ensure-path path)) (comp (mapcar #'string-if-keyword (cdr (pathname-directory path)))) (list (if (directoryp path) comp (let* ((ext (extension path)) (file (if ext (concatenate 'string (base path) "." ext) (base path)))) (append comp (list file)))))) (if (absolutep path) (cons "/" list) list))))) #+nil (components "/foo/bar/baz.json") #+nil (components "/foo/bar/.././../baz/stuff.json") (declaim (ftype (function (list) pathname) from-list)) (defun from-list (list) "Given a LIST of path components, construct a proper pathname object." (if (null list) #p"" (destructuring-bind (parent &rest rest) list (if (null rest) (ensure-path parent) (apply #'join parent (car rest) (cdr rest)))))) #+nil (from-list '("foo" "bar" "baz")) (declaim (ftype (function ((or pathname string)) pathname) ensure-directory)) (defun ensure-directory (path) "If a given PATH doesn't end in a path separator, add one." (let ((path (ensure-path path))) (if (directoryp path) path (make-pathname :name nil :type nil :directory (append (pathname-directory path) (list (name path))))))) #+nil (ensure-directory #p"/foo/bar/baz") (declaim (ftype (function ((or pathname string)) simple-string) ensure-string)) (defun ensure-string (path) "A PATH is definitely a string after this." (if (pathnamep path) (to-string path) path)) (declaim (ftype (function (pathname) simple-string) to-string)) (defun to-string (path) "Convert a PATH object into string." (namestring path)) (declaim (ftype (function ((or pathname string)) pathname) ensure-path)) (defun ensure-path (path) "A PATH is definitely a pathname after this." (if (pathnamep path) path (from-string path))) (declaim (ftype (function (string) pathname) from-string)) (defun from-string (s) "Convert a string into a proper filepath object." (pathname s)) #+nil (join "/" "foo" "bar" ".." "." ".." "baz" "stuff.json") #+nil (pathname "/foo/bar/.././../baz/test.json") #+nil (pathname "/foo/bar/../baz/test.json") #+nil #p"/foo/bar/.././../baz/test.json" ;; --- Conditions --- ;; (define-condition no-filename (error) ((path :initarg :path :reader no-filename-path)) (:documentation "The given path was expected to be a filename, but it may have been a directory or empty string instead.") (:report (lambda (condition stream) (format stream "The given path was expected to be a filename: ~a" (no-filename-path condition))))) (define-condition empty-path (error) () (:documentation "A non-empty path was expected, but an empty one was given.") (:report (lambda (condition stream) (declare (ignore condition)) (format stream "Empty path given where a concrete one was expected.")))) (define-condition root-no-parent (error) () (:documentation "The filesystem root has no parent.") (:report (lambda (condition stream) (declare (ignore condition)) (format stream "The filesystem root has no parent.")))) ;; --- Utilities --- ;; (declaim (ftype (function (t) string) string-if-keyword-impl-specific)) (defun string-if-keyword-impl-specific (item) "Like `string-if-keyword' but with special consideration for implementations. Assumed to be used internally within `base' to account for when the file base is a wildcard character." (cond #+sbcl ((sb-impl::pattern-p item) "**") ; FIXME 2024-06-16 Actually check the contents. (t (string-if-keyword item)))) (declaim (ftype (function ((or string keyword)) string) string-if-keyword)) (defun string-if-keyword (item) "There are certain keywords that represent special path components. These need to be converted back into their original string representations if present." (cond ((or (eq item :up) (eq item :back)) "..") ((eq item :wild) "*") ((eq item :wild-inferiors) "**") (t item))) #+nil (string-if-keyword :up) (declaim (ftype (function (string) (or string keyword)) keyword-if-special)) (defun keyword-if-special (item) "Like `string-if-keyword', certain strings need to be converted to keywords before being stored in the `:directory' portion of a pathname." (cond ((string-equal ".." item) :up) ((string-equal "**" item) :wild-inferiors) ((string-equal "*" item) :wild) (t item))) #+sbcl (defun sbcl-wildcard () "A SBCL-specific pattern type created when a ** appears in a path." (sb-impl::make-pattern '(:multi-char-wild :multi-char-wild)))
15,295
Common Lisp
.lisp
374
33.852941
113
0.610075
fosskers/filepaths
25
0
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
8101b54389e4fb0d5579575621b27efaa312f23f2483e98273f5ec9b6c965455
7,157
[ -1 ]
7,158
main.lisp
fosskers_filepaths/tests/main.lisp
(defpackage filepaths/tests (:use :cl :parachute) (:local-nicknames (:p :filepaths))) (in-package :filepaths/tests) (define-test suite) (define-test "Structural Tests" :parent suite (true (p:rootp "/")) (false (p:rootp "/foo")) (true (p:emptyp "")) (false (p:emptyp "/foo")) (true (p:absolutep "/home/colin/foo.txt")) (false (p:absolutep "colin/foo.txt")) (true (p:absolutep "/")) (false (p:absolutep "")) (false (p:relativep "/home/colin/foo.txt")) (true (p:relativep "foo.txt")) (true (p:starts-with-p "/foo/bar/baz/zing.json" "/foo/bar")) (true (p:ends-with-p "/foo/bar/baz/zing.json" "baz/zing.json")) (true (p:directoryp "/foo/bar/")) (true (p:directoryp #p"/foo/bar/")) (false (p:directoryp "/foo/bar/baz.txt")) (false (p:directoryp #p"/foo/bar/baz.txt"))) (define-test "Construction" :parent suite (is equal #p"/foo/bar/baz/test.json" (p:join "/foo" "bar" "baz" "test.json")) (is equal #p"/bar/baz/foo.json" (p:join #p"/bar/baz/" #p"foo.json")) (is equal #p"/bar/baz/foo.json" (p:join #p"/bar/baz" #p"foo.json")) (is equal #p"/foo/bar/baz/test.json" (p:join "/foo" "" "bar" "/" "baz" "test.json")) (is equal #p"/bar/baz/test.json" (p:join "/" "bar" "baz" "test.json")) (is equal #p"/foo/bar/baz/test.json" (p:join "/foo/bar" "baz/test.json")) #-(or clasp ecl) (is equal #p"/foo/**.json" (p:join "/foo" "**.json")) (is equal #p"/foo/**/*.json" (p:join "/foo" "**" "*.json")) ;; Naughty under CCL and Allegro. (is equal #p"/foo/bar/.././../baz/stuff.json" (p:join "/" "foo" "bar" ".." "." ".." "baz" "stuff.json")) (fail (p:join "/foo" "/")) (fail (p:join "/foo" ""))) (define-test "Component Access" :parent suite (is equal "baz" (p:base "/foo/bar/baz.txt")) (is equal "ゆびわ" (p:base #p"/foo/bar/ゆびわ.txt")) (is equal "baz.txt" (p:base "/foo/bar/baz.txt.zip")) (is equal "*" (p:base "/foo/bar/*.zip")) #-(or clasp ecl) (is equal "**" (p:base "/foo/bar/**.zip")) (fail (p:base "/foo/bar/")) (is equal #p"/foo/bar/jack.txt" (p:with-base "/foo/bar/baz.txt" "jack")) (is equal "baz.txt" (p:name "baz.txt")) (is equal "baz.txt" (p:name "/foo/bar/baz.txt")) (fail (p:name "/foo/bar/")) (fail (p:name "")) (is equal #p"/foo/bar/jack.json" (p:with-name "/foo/bar/baz.txt" "jack.json")) (is equal #p"/foo/bar/" (p:parent "/foo/bar/baz.txt")) (is equal #p"/foo/" (p:parent "/foo/bar/")) (is equal #p"/" (p:parent "/foo/")) (fail (p:parent "/")) (fail (p:parent "")) (is equal #p"/zing/baz.json" (p:with-parent "/foo/bar/baz.json" "/zing")) (is equal "json" (p:extension "/foo/bar.json")) (false (p:extension "/")) (is equal #p"/foo/bar/baz.json" (p:with-extension "/foo/bar/baz.txt" "json")) (fail (p:with-extension "/foo/bar/" "json")) (is equal #p"/foo/bar/baz" (p:drop-extension #p"/foo/bar/baz.json")) (is equal #p"/foo/bar/baz.json" (p:drop-extension #p"/foo/bar/baz.json.zip")) (is equal #p"/foo/bar/baz.txt.zip" (p:add-extension "/foo/bar/baz.txt" "zip")) (is equal #p"/foo/bar/baz.txt" (p:add-extension "/foo/bar/baz" "txt")) (fail (p:add-extension "/foo/bar/" "txt"))) (define-test "Conversion" :parent suite (is equal '("/" "foo" "bar" "baz.json") (p:components "/foo/bar/baz.json")) (is equal '("foo" "bar" "baz.json") (p:components "foo/bar/baz.json")) (is equal '("/") (p:components "/")) (is equal '() (p:components "")) (is equal #p"" (p:from-list '())) (is equal #p"foo" (p:from-list '("foo"))) (is equal #p"foo/bar/baz" (p:from-list '("foo" "bar" "baz"))) (let ((path #p"/foo/bar/baz/file.txt")) (is equal path (p:from-list (p:components path)))) (let ((path #p"/foo/bar/.././../baz/stuff.json")) (is equal path (p:from-list (p:components path)))) (let ((path #p"/foo/bar/baz/")) (is equal path (p:ensure-directory path))) (is equal #p"/foo/bar/baz/" (p:ensure-directory "/foo/bar/baz")) (is equal #p"/foo/bar/baz.json/" (p:ensure-directory "/foo/bar/baz.json")) (of-type string (p:ensure-string #p"/foo")) (of-type pathname (p:ensure-path "/foo")))
4,055
Common Lisp
.lisp
87
43.494253
106
0.597722
fosskers/filepaths
25
0
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4d15ac36b89818d5b3d96d15792e7dea24b2a57377b8e2ab8c1df7a2b17e9ff3
7,158
[ -1 ]
7,159
filepaths.asd
fosskers_filepaths/filepaths.asd
(defsystem "filepaths" :version "0.1.2" :author "Colin Woodbury <[email protected]>" :license "LGPL-3.0-only" :depends-on () :components ((:module "src" :components ((:file "filepaths")))) :description "Modern and consistent filepath manipulation." :in-order-to ((test-op (test-op :filepaths/tests)))) (defsystem "filepaths/tests" :author "Colin Woodbury <[email protected]>" :license "LGPL-3.0-only" :depends-on (:filepaths :parachute) :components ((:module "tests" :components ((:file "main")))) :description "Test system for filepaths" :perform (test-op (op c) (symbol-call :parachute :test :filepaths/tests)))
705
Common Lisp
.asd
19
31.315789
76
0.643796
fosskers/filepaths
25
0
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
d6620074715f8b106b074f5c5945e860bbaecfcd1349b3459eaafcae82cb4a85
7,159
[ -1 ]
7,161
qlfile.lock
fosskers_filepaths/qlfile.lock
("quicklisp" . (:class qlot/source/dist:source-dist :initargs (:distribution "https://beta.quicklisp.org/dist/quicklisp.txt" :%version :latest) :version "2023-10-21")) ("ultralisp" . (:class qlot/source/dist:source-dist :initargs (:distribution "https://dist.ultralisp.org/" :%version :latest) :version "20240616063501"))
332
Common Lisp
.l
8
39.25
93
0.728395
fosskers/filepaths
25
0
0
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
42c6396e0fa20446d18c58c527513622e9fb6c79770cc0183ca9fe4bf5fe81ea
7,161
[ -1 ]
7,179
package.lisp
mrossini-ethz_parseq/package.lisp
(defpackage :parseq (:use :common-lisp) (:export defrule parseq with-local-rules with-saved-rules trace-rule untrace-rule))
128
Common Lisp
.lisp
3
40.333333
85
0.768
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
028622d54601eec52100597f690d69e61c879c9f6494594c5bdf6ce0f85d05c6
7,179
[ -1 ]
7,180
conditions.lisp
mrossini-ethz_parseq/conditions.lisp
(in-package :parseq) (define-condition parseq-error (simple-error) () (:documentation "Generic error for the parseq library")) (export 'parseq-error) (define-condition generic-parse-error (parseq-error) () (:documentation "Generic parsing error")) (define-condition parse-match-error (generic-parse-error) ((position :initarg :position :accessor parse-error-position) (terminals :initarg :terminals :initform nil :accessor parse-error-terminals)) (:documentation "Error condition for when the sequence does not match the parsing grammar rules.")) (define-condition parse-junk-error (generic-parse-error) () (:documentation "Error condition for when the sequence is only partially parsed, leaving junk at the end.")) (export '(generic-parse-error parse-match-error parse-junk-error parse-error-position parse-error-terminals)) (define-condition rule-definition-error (parseq-error) () (:documentation "Generic error for rule definitions")) (define-condition invalid-terminal-error (rule-definition-error) () (:documentation "Error condition for rule definitions where a terminal is unknown.")) (define-condition invalid-operation-error (rule-definition-error) () (:documentation "Error condition for rule definitions where the usage of an operation is invalid.")) (define-condition processing-options-error (rule-definition-error) () (:documentation "Error condition for rule definitions where a processing option is invalid.")) (export '(rule-definition-error invalid-terminal-error invalid-operation-error processing-options-error)) (define-condition runtime-error (parseq-error) () (:documentation "Generic runtime error")) (define-condition unknown-rule-error (runtime-error) () (:documentation "Error condition for situations where a rule definition is not found at runtime.")) (define-condition invalid-terminal-runtime-error (runtime-error) () (:documentation "Error condition for situations where an invalid terminal in an expression is detected at runtime.")) (define-condition invalid-rule-error (runtime-error) () (:documentation "Error condition for malformed calls to rules.")) (define-condition left-recursion-error (runtime-error) () (:documentation "Error condition for situations where left recursion is detected at runtime.")) (export '(runtime-error unknown-rule-error invalid-rule-error left-recursion-error)) (defmacro f-error (type (&rest initargs) control &rest args) "Like (error ...), but allows the condition type to be specified (which is required to inherit from simple-condition)." `(error ',type ,@initargs :format-control ,control :format-arguments (list ,@args)))
2,635
Common Lisp
.lisp
36
71.083333
121
0.782961
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
3137e4e5119d94a489de5efe32d0a1840ea84d46defd2ddb8047e51e8341011e
7,180
[ -1 ]
7,181
code-coverage.lisp
mrossini-ethz_parseq/test/code-coverage.lisp
;;; Load SB-COVER (require :sb-cover) ;;; Turn on generation of code coverage instrumentation in the compiler (declaim (optimize sb-cover:store-coverage-data)) ;;; Load some code, ensuring that it's recompiled with the new optimization ;;; policy. (asdf:test-system :parseq :force t) ;;; Produce a coverage report (sb-cover:report "/tmp/report/parseq/") ;;; Turn off instrumentation (declaim (optimize (sb-cover:store-coverage-data 0)))
442
Common Lisp
.lisp
11
38.727273
75
0.762911
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
78606a7b11fe3f0299c04abcb4ebb99299f421bfbbca0608812ab05f7492c80c
7,181
[ -1 ]
7,182
test.lisp
mrossini-ethz_parseq/test/test.lisp
(in-package :parseq) (defrule terminal-t () t) (defrule terminal-nil () nil) (defrule terminal-symbol () 'a) (defrule terminal-character () #\a) (defrule terminal-string () "abc") (defrule terminal-vector () #(1 2 3)) (defrule terminal-number () 5) (defrule terminal-any-char () char) (defrule terminal-any-stdchar () stdchar) (defrule terminal-any-alpha () alpha) (defrule terminal-any-digit () digit) (defrule terminal-any-alphanumeric () alphanumeric) (defrule terminal-any-byte () byte) (defrule terminal-any-symbol () symbol) (defrule terminal-any-keyword () keyword) (defrule terminal-any-form () form) (defrule terminal-any-atom () atom) (defrule terminal-any-list () list) (defrule terminal-any-cons () cons) (defrule terminal-any-vector () vector) (defrule terminal-any-number () number) (defrule terminal-any-integer () integer) (defrule terminal-any-string () string) (defrule terminal-char-expr () (char "+a-zA-D7-9.;-")) (defrule nonterminal-and () (and 'a 'b 'c)) (defrule nonterminal-and~ () (and~ 'a 'b 'c 'd)) (defrule nonterminal-and~~ () (and~~ (1 2 (1) (2 3)) 'a 'b 'c 'd)) (defrule nonterminal-and~~2 () (and~~ (* + ?) 'a 'b 'c)) (defrule nonterminal-or () (or 'a 'b 'c)) (defrule nonterminal-not () (not 'a)) (defrule nonterminal-* () (* 'a)) (defrule nonterminal-+ () (+ 'a)) (defrule nonterminal-? () (? 'a)) (defrule nonterminal-& () (& 'a)) (defrule nonterminal-! () (! 'a)) (defrule nonterminal-rep () (rep 4 'a)) (defrule nonterminal-rep-b () (rep (4) 'a)) (defrule nonterminal-rep-ab () (rep (3 5) 'a)) (defrule nonterminal-rep-nil-b () (rep (nil 5) 'a)) (defrule nonterminal-rep-a-nil () (rep (3 nil) 'a)) (defrule nonterminal-rep-nil-nil () (rep (nil nil) 'a)) (defrule nonterminal-rep-* () (rep * 'a)) (defrule nonterminal-rep-+ () (rep + 'a)) (defrule nonterminal-rep-? () (rep ? 'a)) (defrule nonterminal-list () (list 'a 'b)) (defrule nonterminal-string () (string #\a #\b)) (defrule nonterminal-vector () (vector 4 5)) (defrule parameter-terminal (x) x) (defrule parameter-terminal-2 (x) x) (defrule parameter-terminal-indirect () (parameter-terminal 'a)) (defrule parameter-repeat (x) (rep x 'a)) ;; This is a convoluted test that uses nesting of nonterminals with parameters (defrule parameter-slist (item sep) (and item (* (and sep item)))) (defrule parameter-slist-user-sep (y) (or 'b y)) (defrule parameter-slist-user (z) (parameter-slist 'a (parameter-slist-user-sep z))) (defrule parameter-slist-user-user () (parameter-slist-user 'c)) (defrule parameter-constant (x) 'a (:constant x)) (defrule parameter-optional (&optional (x 5 x-p)) 'a (:constant (list x x-p))) (defrule parameter-keyword (&key ((:x xx) 5 x-p)) 'a (:constant (list xx x-p))) (defrule parameter-rest (&rest x) 'a (:constant x)) (defrule option-constant () (and 'a 'b 'c) (:constant 4)) (defrule option-lambda () (and 'a 'b 'c) (:lambda (x y z) (list z y x))) (defrule option-lambda-rest () (and 'a 'b 'c) (:lambda (&rest items) (reverse items))) (defrule option-destructure () (and (* 'a) 'b) (:destructure ((&rest a) b) `(,@a ,b))) (defrule option-choose () (and 'a (* 'b) (rep 1 'c) (? (and (+ 'd) 'e)) 'f) (:choose 0 0 '(1 5) 2 '(3 1) '(3 0 0) -1 -10)) (defrule option-identity-t () (and 'a 'b 'c) (:identity t)) (defrule option-identity-n () (and 'a 'b 'c) (:identity nil)) (defrule option-flatten () (and (and 'a 'b) (and 'c 'd) (and 'e 'f)) (:flatten)) (defrule option-string () (and (and #\a "b") "cd" (and #\e #\f)) (:string)) (defrule option-string-symbol () (and (and #\a "b") "cd" (and #\e 'f)) (:string)) (defrule option-vector () (and (and 1 2) (and 3 4) (and 5 6)) (:vector)) (defrule option-test () number (:test (x) (= x 5))) (defrule option-not () number (:not (x) (= x 5))) (defrule multiopt-proc () number (:lambda (x) (1+ x)) (:lambda (x) (1+ x))) (defrule multiopt-test-a () number (:test (x) (= x 5)) (:lambda (x) (1+ x))) (defrule multiopt-test-b () number (:lambda (x) (1+ x)) (:test (x) (= x 5))) (defrule bind-single () (and bind-single-number bind-single-repeat) (:let x)) (defrule bind-single-number () number (:external x) (:lambda (num) (setf x num))) (defrule bind-single-repeat () (rep x 'a) (:external x)) (defrule bind-nest-number () number (:external x) (:lambda (num) (setf x num))) (defrule bind-nest-repeat () (rep x bind-single) (:external x) ) (defrule bind-nest () (and bind-nest-number bind-nest-repeat) (:let x)) (defrule nest-or-and () (or (and 'a 'b) (and 'a 'c) (and 'd 'e))) (defrule nest-and-or () (and (or 'a 'b) (or 'a 'c) (or 'd 'e))) (defrule nest-*-and () (* (and 'a 'b))) (defrule nest-and-* () (and (* 'a) (* 'b))) (defrule nest-+-and () (+ (and 'a 'b))) (defrule nest-and-+ () (and (+ 'a) (+ 'b))) (defrule nest-list-list () (list (list 'a))) (defrule parse-error () (and terminal-symbol (or (and 'b (* 'd) (parameter-terminal 'e)) (and 'c (or 'g 'h)) (and 'b 'f)))) (defrule recursion () (or (and 'a recursion) 'a)) (defrule left-recursion () (or (and 'a left-recursion 'b) (and left-recursion 'a) 'a)) (defrule left-recursion-indirect () (and (? 'b) left-recursion-indirect-2)) (defrule left-recursion-indirect-2 () (and (? 'b) left-recursion-indirect)) (defrule packrat-symbol () symbol (:packrat t)) (defrule packrat-symbol-user () (+ packrat-symbol)) (defrule packrat-a (a b c) 'a (:external x y z) (:constant (list a b c x y z)) (:packrat t)) (defrule packrat-b () 'b (:packrat t)) (defrule packrat-ab (a b c) (and (packrat-a a b c) packrat-b)) (defrule packrat-ab-2 (a b c) (and (packrat-a a b c) packrat-b) (:let (z 7))) (defrule packrat-abc-1 () (or (and (packrat-ab 1 2 3) 'c) (packrat-ab 1 2 3)) (:let (x 4) (y 5) (z 6))) (defrule packrat-abc-2 () (or (and (packrat-ab 1 2 3) 'c) (packrat-ab 1 2 4)) (:let (x 4) (y 5) (z 6))) (defrule packrat-abc-3 () (or (and (packrat-ab 1 2 3) 'c) (packrat-ab-2 1 2 3)) (:let (x 4) (y 5) (z 6))) (defrule loop-name () (and 'named symbol)) (defrule loop-iteration-with () (and 'with symbol '= form (* (and 'and symbol '= form)))) (defrule loop-iteration-up () (and (? (and (or 'from 'upfrom) form)) (? (and (or 'upto 'to 'below) form)))) (defrule loop-iteration-down1 () (and 'from form (or 'downto 'above) form)) (defrule loop-iteration-down2 () (and 'downfrom form (? (and (or 'downto 'to 'above) form)))) (defrule loop-iteration-numeric () (and (or loop-iteration-down1 loop-iteration-down2 loop-iteration-up) (? (and 'by form)))) (defrule loop-iteration-list () (and (or 'in 'on) form (? (and 'by form)))) (defrule loop-iteration-flex () (and '= form (? (and 'then form)))) (defrule loop-iteration-vector () (and 'across form)) (defrule loop-iteration-key () (and (or 'hash-key 'hash-keys) (or 'of 'in) form (? (and 'using (list (and 'hash-value symbol)))))) (defrule loop-iteration-value () (and (or 'hash-value 'hash-values) (or 'of 'in) form (? (and 'using (list (and 'hash-key symbol)))))) (defrule loop-iteration-package () (and (or 'symbol 'symbols 'present-symbol 'present-symbols 'external-symbol 'external-symbols) (or 'of 'in) form)) (defrule loop-iteration-hash () (and 'being (or 'the 'each) (or loop-iteration-key loop-iteration-value loop-iteration-package))) (defrule loop-iteration-for-body () (or loop-iteration-list loop-iteration-flex loop-iteration-vector loop-iteration-hash loop-iteration-numeric)) (defrule loop-iteration-for () (and (or 'for 'as) symbol loop-iteration-for-body (* (and 'and symbol loop-iteration-for-body)))) (defrule loop-iteration () (or loop-iteration-with loop-iteration-for)) (defrule loop-around () (and (or 'initially 'finally) (+ (not loop-post-iteration)))) (defrule loop-repeat () (and 'repeat form)) (defrule loop-test () (and (or 'while 'until 'always 'never 'thereis) form)) (defrule loop-control () (or loop-around loop-repeat loop-test)) (defrule loop-do () (and (or 'do 'doing) (+ (not loop-post-iteration)))) (defrule loop-condition-and () (and loop-action (* (and 'and loop-action)))) (defrule loop-condition () (and (or 'if 'when 'unless) form loop-condition-and (? (and 'else loop-condition-and)) (? 'end))) (defrule loop-return () (and 'return (or 'it form))) (defrule loop-collect () (and (or 'collect 'collecting 'append 'appending 'nconc 'nconcing) (or 'it form) (? (and 'into form)))) (defrule loop-stat () (and (or 'count 'counting 'sum 'summing 'maximize 'maximizing 'minimize 'minimizing) (or 'it form) (? (and 'into form)))) (defrule loop-action () (or loop-do loop-condition loop-return loop-collect loop-stat)) ;; + (defrule loop-post-iteration () (or loop-control loop-action)) (defrule loop () (and (? loop-name) (* loop-iteration) (* loop-post-iteration))) (defrule url () (or url-generic url-httpaddress)) (defrule url-generic () (and url-scheme ":" url-path (? (and "?" url-search)))) (defrule url-scheme () url-ialpha (:string)) (defrule url-httpaddress () (and "http://" url-hostport (? (and #\/ url-path)) (? (and #\? url-search))) (:destructure (scheme (host port) path search) (list scheme host (if port (second port)) (if path (second path)) (if search (second search))))) (defrule url-hostport () (and url-host (? (and #\: url-port)))) (defrule url-host () (or url-hostname url-hostnumber) (:string)) (defrule url-hostname () (and url-ialpha (? (and #\. url-hostname)))) (defrule url-hostnumber () (and url-digits #\. url-digits #\. url-digits #\. url-digits)) (defrule url-port () url-digits (:string) (:function #'parse-integer)) (defrule url-path () (and url-xpalphas (? (and #\/ url-path))) (:string)) (defrule url-search () (and url-xalphas (? (and #\+ url-search))) (:destructure (str more) (append (list str) (if more (second more))))) (defrule url-xalpha () (or url-alpha url-digit url-safe url-extra url-escape)) (defrule url-xalphas () (+ url-xalpha) (:string)) (defrule url-xpalpha () (or url-xalpha #\+)) (defrule url-xpalphas () (+ url-xpalpha)) (defrule url-ialpha () (and url-alpha (? url-xalphas))) (defrule url-alpha () char (:test (x) (alpha-char-p x))) (defrule url-digit () char (:test (x) (digit-char-p x))) (defrule url-digits () (+ url-digit)) (defrule url-safe () (or #\$ #\- #\_ #\@ #\. #\&)) (defrule url-extra () (or #\! #\* #\" #\' #\( #\) #\; #\, #\Space)) (defrule url-escape () (and #\% url-hex url-hex)) (defrule url-hex () (or url-digit #\a #\b #\c #\d #\e #\f #\A #\B #\C #\D #\E #\F)) ;; ----- Helpers ---------------------------------------- (defun xnor (&rest forms) (evenp (count-if #'identity forms))) (defun test-parseq (expression list &optional success (result nil result-p) junk-allowed (test #'equal)) (multiple-value-bind (rslt success-p) (parseq expression list :junk-allowed junk-allowed) (and (xnor success success-p) (or (not result-p) (funcall test rslt result))))) ;; ----- Low level tests -------------------------------- (define-test treepos-test () (check (equalp (make-treepos 1 2 3) #(1 2 3)) (equalp (make-treepos) #(0)) (condition= (make-treepos -1) error) (equalp (treepos-copy (make-treepos 1 2 3)) (make-treepos 1 2 3)) (= (treepos-depth (make-treepos 1 2 3)) 3) (eql (treepos-valid (make-treepos 0) '()) nil) (eql (treepos-valid (make-treepos 0) '(a b)) t) (eql (treepos-valid (make-treepos 1) '(a b)) t) (eql (treepos-valid (make-treepos 2) '(a b)) nil) (eql (treepos-valid (make-treepos 0 0) '(a (b c))) nil) (eql (treepos-valid (make-treepos 1 0) '(a (b c))) t) (eql (treepos-valid (make-treepos 1 1) '(a (b c))) t) (eql (treepos-valid (make-treepos 1 2) '(a (b c))) nil) (eql (treepos-valid (make-treepos 2 0) '(a (b c))) nil) (equal (treeitem #() '(a b c d e)) '(a b c d e)) (equal (treeitem (make-treepos) '(a b c d e)) 'a) (equal (treeitem (make-treepos 1 1) '(a (b b2) c d e)) 'b2) (condition= (treeitem (make-treepos 0 1) '(a (b b2) c d e)) error) (condition= (treeitem (make-treepos 1 2) '(a (b b2) c d e)) error) (= (treepos-length (make-treepos 1) '(a (b c) d)) 2) (condition= (treepos-length (make-treepos 0) '(a (b c) d)) generic-parse-error) (equalp (treepos-step (make-treepos 1)) (make-treepos 2)) (equalp (treepos-step (make-treepos 1 2 3 4)) (make-treepos 1 2 3 5)) (equalp (treepos-step-down (make-treepos 1)) (make-treepos 1 0)) (equalp (treepos-step-down (make-treepos 1 2 3 4)) (make-treepos 1 2 3 4 0)) (eql (treepos> (make-treepos 1) (make-treepos 1)) nil) (eql (treepos> (make-treepos 2) (make-treepos 1)) t) (eql (treepos> (make-treepos 1) (make-treepos 2)) nil) (eql (treepos> (make-treepos 1 2 3) (make-treepos 1 2 3)) nil) (eql (treepos> (make-treepos 1 2 4) (make-treepos 1 2 3)) t) (eql (treepos> (make-treepos 1 2 4) (make-treepos 1 3 3)) nil) (eql (treepos> (make-treepos 1 2 3) (make-treepos 1 2)) t) (eql (treepos> (make-treepos 1 2 3) (make-treepos 1 3)) nil) (eql (treepos> (make-treepos 1 3) (make-treepos 1 2 3)) t) (eql (treepos> (make-treepos 1 3) (make-treepos 1 3 3)) nil) (eql (treepos= (make-treepos 1 2 3) (make-treepos 1 2 3)) t) (eql (treepos= (make-treepos 1 2 3) (make-treepos 1 2 3 0)) nil))) ;; ----- High level tests ------------------------------- (define-test terminal-test () (check (test-parseq 'terminal-t '(t) t t) (test-parseq 'terminal-t '(5) t 5) (test-parseq 'terminal-t '(nil) nil nil) (test-parseq 'terminal-nil '(nil) t nil) (test-parseq 'terminal-nil '(()) t nil) (test-parseq 'terminal-nil '(t) nil nil) (test-parseq 'terminal-symbol '(a) t 'a) (test-parseq 'terminal-symbol '(b) nil nil) (test-parseq 'terminal-symbol '(1) nil nil) (test-parseq 'terminal-character '(#\a) t #\a) (test-parseq 'terminal-character '(#\b) nil nil) (test-parseq 'terminal-character '(1) nil nil) (test-parseq 'terminal-string "abc" t "abc") (test-parseq 'terminal-string '("abc") t "abc") (test-parseq 'terminal-string '(1) nil nil) (test-parseq 'terminal-string "def" nil nil) (test-parseq 'terminal-vector #(1 2 3) t #(1 2 3) nil #'equalp) (test-parseq 'terminal-vector '(#(1 2 3)) t #(1 2 3) nil #'equalp) (test-parseq 'terminal-vector '((1 2 3)) nil nil) (test-parseq 'terminal-vector '("1 2 3") nil nil) (test-parseq 'terminal-vector #(4 5 6) nil nil #'equalp) (test-parseq 'terminal-number '(5) t 5) (test-parseq 'terminal-number '(4) nil nil) (test-parseq 'terminal-number '("abc") nil nil) (test-parseq 'terminal-any-char '(#\f) t #\f) (test-parseq 'terminal-any-char '(#\g) t #\g) (test-parseq 'terminal-any-char '(f) nil nil) (test-parseq 'terminal-any-stdchar '(#\f) t #\f) (test-parseq 'terminal-any-stdchar '(#\g) t #\g) (test-parseq 'terminal-any-stdchar '(#\Tab) nil nil) (test-parseq 'terminal-any-stdchar '(f) nil nil) (test-parseq 'terminal-any-alpha '(#\f) t #\f) (test-parseq 'terminal-any-alpha '(#\g) t #\g) (test-parseq 'terminal-any-alpha '(#\8) nil nil) (test-parseq 'terminal-any-alpha '(f) nil nil) (test-parseq 'terminal-any-digit '(#\7) t #\7) (test-parseq 'terminal-any-digit '(#\8) t #\8) (test-parseq 'terminal-any-digit '(#\f) nil nil) (test-parseq 'terminal-any-digit '(f) nil nil) (test-parseq 'terminal-any-alphanumeric '(#\f) t #\f) (test-parseq 'terminal-any-alphanumeric '(#\8) t #\8) (test-parseq 'terminal-any-alphanumeric '(#\Space) nil nil) (test-parseq 'terminal-any-alphanumeric '(f) nil nil) (test-parseq 'terminal-any-byte '(255) t 255) (test-parseq 'terminal-any-byte '(256) nil nil) (test-parseq 'terminal-any-byte '(0) t 0) (test-parseq 'terminal-any-byte '(-1) nil nil) (test-parseq 'terminal-any-byte '(a) nil nil) (test-parseq 'terminal-any-symbol '(f) t 'f) (test-parseq 'terminal-any-symbol '(#\f) nil nil) (test-parseq 'terminal-any-keyword '(:a) t :a) (test-parseq 'terminal-any-keyword '(a) nil nil) (test-parseq 'terminal-any-keyword '(#\a) nil nil) (test-parseq 'terminal-any-form '(nil) t nil) (test-parseq 'terminal-any-form '(#\a) t #\a) (test-parseq 'terminal-any-form '((foo)) t '(foo)) (test-parseq 'terminal-any-atom '(nil) t nil) (test-parseq 'terminal-any-atom '(4) t 4) (test-parseq 'terminal-any-atom '((1 2)) nil nil) (test-parseq 'terminal-any-list '(nil) t nil) (test-parseq 'terminal-any-list '((+ 1 2)) t '(+ 1 2)) (test-parseq 'terminal-any-list '(4) nil nil) (test-parseq 'terminal-any-cons '(nil) nil nil) (test-parseq 'terminal-any-cons '((1 . 2)) t '(1 . 2)) (test-parseq 'terminal-any-cons '((1 2)) t '(1 2)) (test-parseq 'terminal-any-cons '(4) nil nil) (test-parseq 'terminal-any-vector '(#(1 2)) t #(1 2) nil #'equalp) (test-parseq 'terminal-any-vector '(4) nil nil nil #'equalp) (test-parseq 'terminal-any-number '(4) t 4) (test-parseq 'terminal-any-number '(#\4) nil nil) (test-parseq 'terminal-any-integer '(4) t 4) (test-parseq 'terminal-any-integer '(4/5) nil nil) (test-parseq 'terminal-any-integer '(4.5) nil nil) (test-parseq 'terminal-any-integer '(#\4) nil nil) (test-parseq 'terminal-any-string '("foo") t "foo") (test-parseq 'terminal-any-string '(#\f) nil nil) ;; (char "+a-zA-D7-9.;-") (test-parseq 'terminal-char-expr "a" t #\a) (test-parseq 'terminal-char-expr "z" t #\z) (test-parseq 'terminal-char-expr "f" t #\f) (test-parseq 'terminal-char-expr "A" t #\A) (test-parseq 'terminal-char-expr "B" t #\B) (test-parseq 'terminal-char-expr "D" t #\D) (test-parseq 'terminal-char-expr "E" nil nil) (test-parseq 'terminal-char-expr "Z" nil nil) (test-parseq 'terminal-char-expr "0" nil nil) (test-parseq 'terminal-char-expr "6" nil nil) (test-parseq 'terminal-char-expr "7" t #\7) (test-parseq 'terminal-char-expr "8" t #\8) (test-parseq 'terminal-char-expr "9" t #\9) (test-parseq 'terminal-char-expr "." t #\.) (test-parseq 'terminal-char-expr ";" t #\;) (test-parseq 'terminal-char-expr "-" t #\-) (test-parseq 'terminal-char-expr "+" t #\+) (test-parseq 'terminal-char-expr "," nil nil))) (define-test and-test () (check ;; (and 'a 'b 'c) (test-parseq 'nonterminal-and '(a b c) t '(a b c)) (test-parseq 'nonterminal-and '(a b) nil nil) (test-parseq 'nonterminal-and '(a c) nil nil) (test-parseq 'nonterminal-and '(a) nil nil))) (define-test and~-test () (check ;; (and~ 'a 'b 'c 'd) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c d)) t '(a b c d)) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c)) nil nil) (test-parseq 'nonterminal-and~ '(a b c d a) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) (test-parseq 'nonterminal-and~ (shuffle '(a b c d a)) nil nil) ;; (and~~ (1 2 (1) (2 3)) 'a 'b 'c 'd) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d)) t '((a) (b b) (c) (d d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a b b d d)) t '((a) (b b) () (d d))) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a a b b c d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) (test-parseq 'nonterminal-and~~ (shuffle '(a b b c d d d d)) nil nil) ;; (and~~ (* + ?) 'a 'b 'c) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a a a b b b c)) t '((a a a) (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(b b b c)) t '(() (b b b) (c))) (test-parseq 'nonterminal-and~~2 (shuffle '(a b)) t '((a) (b) ())) (test-parseq 'nonterminal-and~~2 (shuffle '(a b)) t '((a) (b) ())) (test-parseq 'nonterminal-and~~2 (shuffle '(a b)) t '((a) (b) ())) (test-parseq 'nonterminal-and~~2 (shuffle '(a b)) t '((a) (b) ())) (test-parseq 'nonterminal-and~~2 (shuffle '(a)) nil nil) (test-parseq 'nonterminal-and~~2 (shuffle '(b c c)) nil nil))) (define-test or-test () (check ;; (or 'a 'b 'c) (test-parseq 'nonterminal-or '(a) t 'a) (test-parseq 'nonterminal-or '(b) t 'b) (test-parseq 'nonterminal-or '(c) t 'c) (test-parseq 'nonterminal-or '(d) nil nil))) (define-test not-test () (check ;; (not 'a) (test-parseq 'nonterminal-not '() nil nil) (test-parseq 'nonterminal-not '(a) nil nil) (test-parseq 'nonterminal-not '(b) t 'b))) (define-test *-test () (check ;; (* 'a) (test-parseq 'nonterminal-* '() t nil) (test-parseq 'nonterminal-* '(a) t '(a)) (test-parseq 'nonterminal-* '(a a) t '(a a)) (test-parseq 'nonterminal-* '(a a a) t '(a a a)) (test-parseq 'nonterminal-* '(b) nil nil) (test-parseq 'nonterminal-* '(b) t nil t) (test-parseq 'nonterminal-* '(a b) nil nil) (test-parseq 'nonterminal-* '(a b) t '(a) t))) (define-test +-test () (check ;; (+ 'a) (test-parseq 'nonterminal-+ '() nil nil) (test-parseq 'nonterminal-+ '(a) t '(a)) (test-parseq 'nonterminal-+ '(a a) t '(a a)) (test-parseq 'nonterminal-+ '(a a a) t '(a a a)) (test-parseq 'nonterminal-+ '(b) nil nil) (test-parseq 'nonterminal-+ '(a b) nil nil) (test-parseq 'nonterminal-+ '(a b) t '(a) t))) (define-test ?-test () (check ;; (? 'a) (test-parseq 'nonterminal-? '() t nil) (test-parseq 'nonterminal-? '(a) t 'a) (test-parseq 'nonterminal-? '(b) t nil t))) (define-test &-test () (check ;; (& 'a) (test-parseq 'nonterminal-& '(a) t 'a t) (test-parseq 'nonterminal-& '(b) nil nil t))) (define-test !-test () (check ;; (! 'a) (test-parseq 'nonterminal-! '() nil nil) (test-parseq 'nonterminal-! '(a) nil nil) (test-parseq 'nonterminal-! '(b) t 'b t))) (define-test rep-test () (check ;; (rep 4 'a) (test-parseq 'nonterminal-rep '() nil nil) (test-parseq 'nonterminal-rep '(a a a) nil nil) (test-parseq 'nonterminal-rep '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep '(a a a a a) nil nil) ;; (rep (4) 'a) (test-parseq 'nonterminal-rep-b '() t '()) (test-parseq 'nonterminal-rep-b '(a) t '(a)) (test-parseq 'nonterminal-rep-b '(a a) t '(a a)) (test-parseq 'nonterminal-rep-b '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-b '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep-b '(a a a a a) nil nil) ;; (rep (nil 5) 'a) (test-parseq 'nonterminal-rep-nil-b '() t '()) (test-parseq 'nonterminal-rep-nil-b '(a) t '(a)) (test-parseq 'nonterminal-rep-nil-b '(a a) t '(a a)) (test-parseq 'nonterminal-rep-nil-b '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-nil-b '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep-nil-b '(a a a a a) t '(a a a a a)) (test-parseq 'nonterminal-rep-nil-b '(a a a a a a) nil nil) ;; (rep (3 5) 'a) (test-parseq 'nonterminal-rep-ab '(a a) nil nil) (test-parseq 'nonterminal-rep-ab '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-ab '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep-ab '(a a a a a) t '(a a a a a)) (test-parseq 'nonterminal-rep-ab '(a a a a a a) nil nil) ;; (rep (3 nil) 'a) (test-parseq 'nonterminal-rep-a-nil '(a) nil nil) (test-parseq 'nonterminal-rep-a-nil '(a a) nil nil) (test-parseq 'nonterminal-rep-a-nil '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-a-nil '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep-a-nil '(a a a a a) t '(a a a a a)) (test-parseq 'nonterminal-rep-a-nil '(a a a a a a) t '(a a a a a a)) ;; (rep (nil nil) 'a) (test-parseq 'nonterminal-rep-nil-nil '() t '()) (test-parseq 'nonterminal-rep-nil-nil '(a) t '(a)) (test-parseq 'nonterminal-rep-nil-nil '(a a) t '(a a)) (test-parseq 'nonterminal-rep-nil-nil '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-nil-nil '(a a a a) t '(a a a a)) (test-parseq 'nonterminal-rep-nil-nil '(a a a a a) t '(a a a a a)) (test-parseq 'nonterminal-rep-nil-nil '(a a a a a a) t '(a a a a a a)) ;; (rep * 'a) (test-parseq 'nonterminal-rep-* '() t '()) (test-parseq 'nonterminal-rep-* '(a) t '(a)) (test-parseq 'nonterminal-rep-* '(a a) t '(a a)) (test-parseq 'nonterminal-rep-* '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-* '(a a a a) t '(a a a a)) ;; (rep + 'a) (test-parseq 'nonterminal-rep-+ '() nil nil) (test-parseq 'nonterminal-rep-+ '(a) t '(a)) (test-parseq 'nonterminal-rep-+ '(a a) t '(a a)) (test-parseq 'nonterminal-rep-+ '(a a a) t '(a a a)) (test-parseq 'nonterminal-rep-+ '(a a a a) t '(a a a a)) ;; (rep ? 'a) (test-parseq 'nonterminal-rep-? '() t '()) (test-parseq 'nonterminal-rep-? '(a) t '(a)) (test-parseq 'nonterminal-rep-? '(a a) nil nil))) (define-test list-test () (check ;; (list 'a) (test-parseq 'nonterminal-list '() nil nil) (test-parseq 'nonterminal-list '(a) nil nil) (test-parseq 'nonterminal-list '((a)) nil nil) (test-parseq 'nonterminal-list '((a b)) t '(a b)) (test-parseq 'nonterminal-list '((a c)) nil nil) (test-parseq 'nonterminal-list '((b b)) nil nil) (test-parseq 'nonterminal-list '(#(a b)) nil nil))) (define-test string-test () (check ;; (string #\a) (test-parseq 'nonterminal-string '("") nil nil) (test-parseq 'nonterminal-string '("a") nil nil) (test-parseq 'nonterminal-string '("b") nil nil) (test-parseq 'nonterminal-string '("aa") nil nil) (test-parseq 'nonterminal-string '("ab") t '(#\a #\b)) (test-parseq 'nonterminal-string '("bb") nil nil) (test-parseq 'nonterminal-string '((#\a #\b)) nil nil))) (define-test string-type-test () (check ;; These tests handle the subtle differences that led to the update of #'sequence=. ;; The update fixes every place that deals with strings (defrule too). ;; The observed specific types are enforced to guarantee test portability. (test-parseq 'terminal-string "abc" t "abc") (test-parseq 'terminal-string (coerce "abc" '(simple-array character (3))) t "abc") (test-parseq 'terminal-string (coerce "abc" '(simple-base-string 3)) t "abc"))) (define-test vector-test () (check ;; (vector 4) (test-parseq 'nonterminal-vector '(#()) nil nil) (test-parseq 'nonterminal-vector '(#(3)) nil nil) (test-parseq 'nonterminal-vector '(#(4)) nil nil) (test-parseq 'nonterminal-vector '(#(4 4)) nil nil) (test-parseq 'nonterminal-vector '(#(4 5)) t '(4 5)) (test-parseq 'nonterminal-vector '(#(5 5)) nil nil) (test-parseq 'nonterminal-vector '((4)) nil nil))) (define-test parse-test () (check ;; (vector 4) (condition= (parseq 'terminal-t '() :parse-error t) generic-parse-error) (condition= (parseq 'terminal-t '(1 2) :parse-error t) generic-parse-error) (= (parseq 'terminal-t '(1 2) :end 2 :parse-error t :junk-allowed t) 1) (condition= (parseq '(1 2) ()) invalid-rule-error))) (define-test parameter-test () (check ;; x (test-parseq '(parameter-terminal 'a) '(a) t 'a) (test-parseq '(parameter-terminal 'a) '(b) nil nil) (test-parseq '(parameter-terminal #\a) "a" t #\a) (test-parseq '(parameter-terminal #\a) "b" nil nil) (test-parseq '(parameter-terminal "abc") "abc" t "abc") (test-parseq '(parameter-terminal "abc") "def" nil nil) (test-parseq '(parameter-terminal "abc") '("abc") t "abc") (test-parseq '(parameter-terminal "abc") '("def") nil nil) (test-parseq '(parameter-terminal #(1 2 3)) #(1 2 3) t #(1 2 3) nil #'equalp) (test-parseq '(parameter-terminal #(1 2 3)) #(4 5 6) nil nil) (test-parseq '(parameter-terminal #(1 2 3)) '(#(1 2 3)) t #(1 2 3) nil #'equalp) (test-parseq '(parameter-terminal #(1 2 3)) '(#(4 5 6)) nil nil) (test-parseq '(parameter-terminal 5) '(5) t 5) (test-parseq '(parameter-terminal 5) '(6) nil nil) (test-parseq '(parameter-terminal terminal-t) '(1) t 1) (test-parseq '(parameter-terminal (parameter-terminal-2 'a)) '(a) t 'a) (condition= (parseq '(parameter-terminal #2A((3 4) (1 2))) '(a)) invalid-terminal-runtime-error) ;; (parameter-terminal 'a) (test-parseq 'parameter-terminal-indirect '(a) t 'a) ;; (rep x 'a)) (test-parseq '(parameter-repeat 3) '(a a) nil nil) (test-parseq '(parameter-repeat 3) '(a a a) t '(a a a)) (test-parseq '(parameter-repeat 3) '(a a a a) nil nil) ;; a b a b a b a (test-parseq '(parameter-slist-user-user) '(a) t '(a nil) nil) (test-parseq '(parameter-slist-user-user) '(a b a) t '(a ((b a))) nil) (test-parseq '(parameter-slist-user-user) '(a b a b a) t '(a ((b a) (b a))) nil) (test-parseq '(parameter-slist-user-user) '(a b a b a b a) t '(a ((b a) (b a) (b a))) nil) (test-parseq '(parameter-slist-user-user) '(a b a) t '(a ((b a))) nil) (test-parseq '(parameter-slist-user-user) '(a c a) t '(a ((c a))) nil) (test-parseq '(parameter-slist-user-user) '(a b a c a) t '(a ((b a) (c a))) nil) (test-parseq '(parameter-slist-user-user) '(a b a c a b a) t '(a ((b a) (c a) (b a))) nil) ;; 'a (:constant x) (test-parseq '(parameter-constant b) '(a) t 'b))) ;; Optional parameter (test-parseq 'parameter-optional '(a) t '(5 nil)) (test-parseq '(parameter-optional) '(a) t '(5 nil)) (test-parseq '(parameter-optional 1) '(a) t '(1 t)) ;; Keyword parameter (test-parseq 'parameter-keyword '(a) t '(5 nil)) (test-parseq '(parameter-keyword) '(a) t '(5 nil)) (test-parseq '(parameter-keyword :x 1) '(a) t '(1 t)) ;; Rest parameter (test-parseq 'parameter-rest '(a) t '()) (test-parseq '(parameter-rest) '(a) t '()) (test-parseq '(parameter-rest 1) '(a) t '(1)) (test-parseq '(parameter-rest 1 2) '(a) t '(1 2)) (define-test option-test () (check ;; (and 'a 'b 'c) (:constant 4) (test-parseq 'option-constant '(a b c) t 4) ;; (and 'a 'b 'c) (:lambda (x y z) (list z y x)) (test-parseq 'option-lambda '(a b c) t '(c b a)) ;; (and 'a 'b 'c) (:lambda (&rest items) (reverse items)) (test-parseq 'option-lambda-rest '(a b c) t '(c b a)) ;; (and (* 'a) 'b) (:destructure ((&rest a) b) `(,@a ,b)) (test-parseq 'option-destructure '(a a a b) t '(a a a b)) ;; (and 'a (* 'b) (rep 1 'c) (? (and (+ 'd) 'e)) 'f) (:choose 0 0 '(1 5) 2 '(3 1) '(3 0 0) -1 -10) (test-parseq 'option-choose '(a b c d e f) t '(a a nil (c) e d f nil)) (test-parseq 'option-choose '(a b b b b b b b c d e f) t '(a a b (c) e d f nil)) (test-parseq 'option-choose '(a c d e f) t '(a a nil (c) e d f nil)) (test-parseq 'option-choose '(a b c f) t '(a a nil (c) nil nil f nil)) ;; (and 'a 'b 'c) (:identity t) (test-parseq 'option-identity-t '(a b c) t '(a b c)) ;; (and 'a 'b 'c) (:identity nil) (test-parseq 'option-identity-n '(a b c) t nil) ;; (and (and 'a 'b) (and 'c 'd) (and 'e 'f)) (:flatten) (test-parseq 'option-flatten '(a b c d e f) t '(a b c d e f)) ;; (and (and #\a "b") "cd" (and #\e #\f)) (:string) (test-parseq 'option-string "abcdef" t "abcdef") (test-parseq 'option-string '(#\a "b" "cd" #\e #\f) t "abcdef") (test-parseq 'option-string #(#\a "b" "cd" #\e #\f) t "abcdef") ;; (and (and #\a "b") "cd" (and #\e 'f)) (:string) (test-parseq 'option-string-symbol '(#\a "b" "cd" #\e f) t "abcdeF") (test-parseq 'option-string-symbol #(#\a "b" "cd" #\e f) t "abcdeF") ;; (and (and 1 2) (and 3 4) (and 5 6)) (:vector) (test-parseq 'option-vector '(1 2 3 4 5 6) t #(1 2 3 4 5 6) nil #'equalp) (test-parseq 'option-vector #(1 2 3 4 5 6) t #(1 2 3 4 5 6) nil #'equalp) ;; number (:test (x) (= x 5)) (test-parseq 'option-test '(4) nil nil) (test-parseq 'option-test '(5) t 5) (test-parseq 'option-test '(6) nil nil) ;; number (:not (x) (= x 5)) (test-parseq 'option-not '(4) t 4) (test-parseq 'option-not '(5) nil nil) (test-parseq 'option-not '(6) t 6))) (define-test multiopt-test () (check ;; number (:lambda (x) (1+ x)) (:lambda (x) (1+ x))) (test-parseq 'multiopt-proc '(5) t 7) ;; number (:test (x) (= x 5)) (:lambda (x) (1+ x))) (test-parseq 'multiopt-test-a '(4) nil nil) (test-parseq 'multiopt-test-a '(5) t 6) ;; number (:lambda (x) (1+ x)) (:test (x) (= x 5))) (test-parseq 'multiopt-test-b '(4) t 5) (test-parseq 'multiopt-test-b '(5) nil nil))) (define-test nesting-test () (check ;; (or (and 'a 'b) (and 'a 'c) (and 'd 'e)) (test-parseq 'nest-or-and '(a) nil nil) (test-parseq 'nest-or-and '(a b) t '(a b)) (test-parseq 'nest-or-and '(a c) t '(a c)) (test-parseq 'nest-or-and '(a e) nil nil) (test-parseq 'nest-or-and '(d) nil nil) (test-parseq 'nest-or-and '(d e) t '(d e)) ;; (and (or 'a 'b) (or 'a 'c) (or 'd 'e)) (test-parseq 'nest-and-or '(a) nil nil) (test-parseq 'nest-and-or '(b) nil nil) (test-parseq 'nest-and-or '(a a) nil nil) (test-parseq 'nest-and-or '(b a) nil nil) (test-parseq 'nest-and-or '(a c) nil nil) (test-parseq 'nest-and-or '(b c) nil nil) (test-parseq 'nest-and-or '(a a d) t '(a a d)) (test-parseq 'nest-and-or '(b a d) t '(b a d)) (test-parseq 'nest-and-or '(a c d) t '(a c d)) (test-parseq 'nest-and-or '(b c d) t '(b c d)) (test-parseq 'nest-and-or '(a a e) t '(a a e)) (test-parseq 'nest-and-or '(b a e) t '(b a e)) (test-parseq 'nest-and-or '(a c e) t '(a c e)) (test-parseq 'nest-and-or '(b c e) t '(b c e)) ;; (* (and 'a 'b)) (test-parseq 'nest-*-and '() t nil) (test-parseq 'nest-*-and '(a) nil nil) (test-parseq 'nest-*-and '(a) t nil t) (test-parseq 'nest-*-and '(a b) t) (test-parseq 'nest-*-and '(a b a) nil nil) (test-parseq 'nest-*-and '(a b a) t '((a b)) t) (test-parseq 'nest-*-and '(a b a b) t) ;; (and (* 'a 'b)) (test-parseq 'nest-and-* '() t '(nil nil)) (test-parseq 'nest-and-* '(a) t '((a) nil)) (test-parseq 'nest-and-* '(a a) t '((a a) nil)) (test-parseq 'nest-and-* '(b) t '(nil (b))) (test-parseq 'nest-and-* '(b b) t '(nil (b b))) (test-parseq 'nest-and-* '(a b) t '((a) (b))) (test-parseq 'nest-and-* '(a a b) t '((a a) (b))) (test-parseq 'nest-and-* '(a b b) t '((a) (b b))) ;; (+ (and 'a 'b)) (test-parseq 'nest-+-and '() nil nil) (test-parseq 'nest-+-and '(a) nil nil) (test-parseq 'nest-+-and '(a b) t '((a b))) (test-parseq 'nest-+-and '(a b a) nil) (test-parseq 'nest-+-and '(a b a) t '((a b)) t) (test-parseq 'nest-+-and '(a b a b) t '((a b) (a b))) ;; (and (+ 'a 'b)) (test-parseq 'nest-and-+ '() nil nil) (test-parseq 'nest-and-+ '(a) nil nil) (test-parseq 'nest-and-+ '(a a) nil nil) (test-parseq 'nest-and-+ '(b) nil nil) (test-parseq 'nest-and-+ '(b b) nil nil) (test-parseq 'nest-and-+ '(a b) t '((a) (b))) (test-parseq 'nest-and-+ '(a a b) t '((a a) (b))) (test-parseq 'nest-and-+ '(a b b) t '((a) (b b))) (test-parseq 'nest-list-list '(((a))) t '((a))))) (define-test bind-test () (check (test-parseq 'bind-single '(4 a a a) nil nil) (test-parseq 'bind-single '(4 a a a a) t '(4 (a a a a))) (test-parseq 'bind-single '(4 a a a a a) nil nil) (test-parseq 'bind-nest '(3 3 a a a 2 a a 7 a a a a a a a 1 a) nil nil) (test-parseq 'bind-nest '(4 3 a a a 2 a a 7 a a a a a a a 1 a) t '(4 ((3 (a a a)) (2 (a a)) (7 (a a a a a a a)) (1 (a))))) (test-parseq 'bind-nest '(5 3 a a a 2 a a 7 a a a a a a a 1 a) nil nil) (test-parseq 'bind-nest '(4 3 a a a 2 a a 6 a a a a a a a 1 a) nil nil) (test-parseq 'bind-nest '(4 3 a a a 2 a a 8 a a a a a a a 1 a) nil nil))) (define-test namespace-test () (check-with-side-effects ;; Sanity check (test-parseq 'nonterminal-and '(a b c) t '(a b c)) ;; Local rules (with-local-rules (condition= (parseq 'nonterminal-and '(a b c)) unknown-rule-error)) (with-local-rules (defrule nonterminal-and () (and 'd 'e 'f)) (test-parseq 'nonterminal-and '(a b c) nil nil)) (with-local-rules (defrule nonterminal-and () (and 'd 'e 'f)) (test-parseq 'nonterminal-and '(d e f) t '(d e f))) ;; Saved rules (with-saved-rules (test-parseq 'nonterminal-and '(a b c) t '(a b c))) (with-saved-rules (defrule nonterminal-and () (and 'd 'e 'f)) (test-parseq 'nonterminal-and '(d e f) t '(d e f))) ;; Sanity check (test-parseq 'nonterminal-and '(a b c) t '(a b c)) (test-parseq 'nonterminal-and '(d e f) nil nil))) (define-test parse-error-test () (check ;; parse-match-error ;; (and terminal-symbol (or (and 'b (* 'd) (parameter-terminal 'e)) (and 'c (or 'g 'h)) (and 'b 'f))) (condition= (parseq 'parse-error '(v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 0)) (equal (parse-error-terminals obj) '(a))) (condition= (parseq 'parse-error '(a v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 1)) (equal (parse-error-terminals obj) '(b c))) (condition= (parseq 'parse-error '(a b v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 2)) (equal (parse-error-terminals obj) '(d e f))) (condition= (parseq 'parse-error '(a c v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 2)) (equal (parse-error-terminals obj) '(g h))) (condition= (parseq 'parse-error '(a b d v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 3)) (equal (parse-error-terminals obj) '(d e))) (condition= (parseq 'parse-error '(a b d d v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 4)) (equal (parse-error-terminals obj) '(d e))) (condition= (parseq 'parse-error '(a b d d d v) :parse-error t) parse-match-error obj (treepos= (parse-error-position obj) (make-treepos 5)) (equal (parse-error-terminals obj) '(d e))) ;; parse-junk-error (condition= (parseq 'parse-error '(a b f v) :parse-error t) parse-junk-error))) (define-test recursion-test () (check (test-parseq 'recursion '() nil nil) (test-parseq 'recursion '(a) t 'a) (test-parseq 'recursion '(a a) t '(a a)) (test-parseq 'recursion '(a a a) t '(a (a a))) (test-parseq 'recursion '(a a a a) t '(a (a (a a)))) (test-parseq 'recursion '(a a a a a) t '(a (a (a (a a))))))) (define-test left-recursion-test () (check (condition= (parseq 'left-recursion-indirect '(a a a)) left-recursion-error) (condition= (parseq 'left-recursion '(a a a)) left-recursion-error))) (define-test packrat-test () (check (test-parseq 'packrat-symbol-user '(a b c) t '(a b c)) (test-parseq 'packrat-abc-1 '(a b) t '((1 2 3 4 5 6) b)) (test-parseq 'packrat-abc-2 '(a b) t '((1 2 4 4 5 6) b)) (test-parseq 'packrat-abc-3 '(a b) t '((1 2 3 4 5 7) b)))) (define-test loop-test () (check (test-parseq 'loop '(named q for a from 0 below 10 by 10) t) (test-parseq 'loop '(named q for a from 0 above -10 by 10) t) (test-parseq 'loop '(named q for a downfrom 0 above 10 by 10) t) (test-parseq 'loop '(named q for a in lst by #'cdr) t) (test-parseq 'loop '(named q for a = 0 then (1+ a)) t) (test-parseq 'loop '(named q for a across vec) t) (test-parseq 'loop '(named q for k being the hash-key of (hsh) using (hash-value v)) t) (test-parseq 'loop '(named q for v being the hash-value of (hsh) using (hash-key v)) t) (test-parseq 'loop '(named q for k being the external-symbol of (pkg)) t) (test-parseq 'loop '(for i in lst initially a b c while d) t) (test-parseq 'loop '(for i in list repeat 5) t) (test-parseq 'loop '(for i in list thereis (> i 0)) t) (test-parseq 'loop '(for i across vec when (> i 0) collecting it into q and summing i into n else maximize i into m and return 5 end) t) (test-parseq 'loop '(for i across vec unless (minusp i) count i into q) t))) (define-test url-test () (check (test-parseq 'url "http://github.com:22/mrossini-ethz/parseq?foo+bar+baz" t '("http://" "github.com" 22 "mrossini-ethz/parseq" ("foo" "bar" "baz"))))) (define-test parseq-test () (check (treepos-test) (terminal-test) (and-test) (and~-test) (or-test) (not-test) (*-test) (+-test) (?-test) (&-test) (!-test) (rep-test) (list-test) (string-test) (string-type-test) (vector-test) (parse-test) (parameter-test) (option-test) (multiopt-test) (nesting-test) (bind-test) (namespace-test) (parse-error-test) (recursion-test) (left-recursion-test) (packrat-test) (loop-test) (url-test)))
46,441
Common Lisp
.lisp
842
50.946556
188
0.600022
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
341d2b965f196fb20af0928d7e4bfc9fe96d5d49d3e532d579ac7155ec3e04ec
7,182
[ -1 ]
7,183
email-address.lisp
mrossini-ethz_parseq/examples/email-address.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; This example demonstrates the parsing expression grammar for a simplified ;; e-mail address using parseq. Simplified e-mail addresses allow only the ;; special characters ".", "_" and "-" in the part before the "@" (local part). ;; This is not a standard, but the convention of many e-mail providers. Note ;; that despite the simplification, according to RFC5322, RFC5321 and RFC3696, ;; the character "." is not allowed at the beginning or the end of the local ;; part and may not be repeated consecutively. ;; Warning: This is an example that demonstrates the use of parseq. It does not ;; guarantee that the grammar rules described therein are implemented ;; correctly. ;; Parsing expression grammar ------------------------------------------------- ;; Return a list with the local part and the domain. (defrule email-address () (and local-part "@" domain) (:choose 0 2)) ;; The local part consists of multiple characters. The characters are ;; concatenated to a string by the (:string) directive. Test for special case ;; of the "." character (see above). (defrule local-part () (+ (char "a-zA-Z0-9._-")) (:string) (:not (str) (or (char= (elt str 0) #\.) (char= (elt str (1- (length str))) #\.) (search ".." str) (> (length str) 64)))) ;; The domain must not be longer than 253 characters (including dots). (defrule domain () (and label (* (and "." label))) (:string) (:test (x) (<= (length x) 253))) ;; A label may not start or end with with "-". The maximum number of ;; characters is 63. (defrule label () (rep (1 63) (char "a-zA-Z0-9-")) (:string) (:not (str) (or (char= (elt str 0) #\-) (char= (elt str (1- (length str))) #\-)))) ;; Application ---------------------------------------------------------------- ;; Trace the main rule recursively. (trace-rule 'email-address :recursive t) ;; Apply the parsing expression grammar to an example address. (parseq 'email-address "[email protected]")
2,107
Common Lisp
.lisp
43
45.790698
79
0.626095
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a7da5b2e69af44896325268db025bed593afe76068980e0cdf42b6571b12e04f
7,183
[ -1 ]
7,184
rfc-date.lisp
mrossini-ethz_parseq/examples/rfc-date.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; This example parses a date in RFC5322 format, e.g. "Thu, 13 Jul 2017 13:28:03 +0200". (defrule date-time () (and (? (and day-of-week ",")) date time) (:choose '(0 0) 1 2) (:flatten)) (defrule day-of-week () (or "Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun")) (defrule date () (and day month year)) (defrule day () (and (? FWS) (rep (1 2) digit) FWS) (:choose 1) (:string) (:function #'parse-integer)) (defrule month () (or "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec")) (defrule year () (and FWS (rep 4 digit) FWS) (:choose 1) (:string) (:function #'parse-integer)) (defrule time () (and time-of-day FWS zone) (:choose 0 2) (:flatten)) (defrule time-of-day () (and hour ":" minute (? (and ":" second))) (:choose 0 2 '(3 1))) (defrule hour () (rep 2 digit) (:string) (:function #'parse-integer)) (defrule minute () (rep 2 digit) (:string) (:function #'parse-integer)) (defrule second () (rep 2 digit) (:string) (:function #'parse-integer)) (defrule zone () (and (or "+" "-") (rep 4 digit)) (:string)) (defrule FWS () #\space) (trace-rule 'date-time :recursive t) (parseq 'date-time "Thu, 13 Jul 2017 13:28:03 +0200")
1,223
Common Lisp
.lisp
19
62.526316
102
0.627946
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
f4fd45674a32d826921c30c484c9ce60a3e61a393c010ac6b9d92157132812d2
7,184
[ -1 ]
7,185
url.lisp
mrossini-ethz_parseq/examples/url.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; This example demonstrates the parsing expression grammar for URLs ;; using parseq. ;; Warning: This is an example that demonstrates the use of parseq. It ;; does not guarantee that the grammar rules described therein are ;; implemented correctly. ;; The main parsing expression (defrule url () (and scheme (? authority) (? path) (? query) (? fragment)) (:flatten)) ;; The scheme must begin with an alphabetic character (defrule scheme () (and (+ (char "a-zA-Z0-9.+-")) ":") (:string) (:test (str) (alpha-char-p (elt str 0)))) (defrule authority () (and "//" (? (and user-info "@")) host (? (and ":" port))) (:choose '(1 0) 2 '(3 1))) ;; The user-info is not limited to user:pass, but can be almost anything (defrule user-info () (* (or %hex (char "a-zA-Z0-9._~!$&'()*+,;=:-"))) (:string)) ;; Escaped values are in hexadecimal, e.g. "%2F" (defrule %hex () (and #\% (rep 2 (char "0-9a-fA-F"))) (:string)) ;; The domain must not be longer than 253 characters (including dots) (defrule host () (and label (* (and "." label))) (:string) (:test (x) (<= (length x) 253))) ;; A label may not start or end with with "-". The maximum number of ;; characters is 63. (defrule label () (rep (1 63) (char "a-zA-Z0-9-")) (:string) (:not (str) (or (char= (elt str 0) #\-) (char= (elt str (1- (length str))) #\-)))) ;; The port is just a series of digits. This can be easily converted ;; to an integer. (defrule port () (* digit) (:string) (:function #'parse-integer)) ;; The path grammar is simplified here. (defrule path () (* (and "/" segment)) (:string)) ;; Path segment (defrule segment () (* (or %hex (char "a-zA-Z0-9._~!$&'()*+,;=:@-")))) ;; Query can be almost anything (defrule query () (and #\? (* (char "a-zA-Z0-9._~!$&'()*+,;=:@/?-"))) (:choose 1) (:string)) ;; Fragment can be almost anything (defrule fragment () (and #\# (* (char "a-zA-Z0-9._~!$&'()*+,;=:@/?-"))) (:choose 1) (:string)) (trace-rule 'url :recursive t) (parseq 'url "https://user:[email protected]:22/mrossini-ethz/parseq?foo+bar+baz#top" :parse-error t)
2,103
Common Lisp
.lisp
35
58.6
143
0.629937
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
9dc4d84907373dafc1d9aa6c70174d90deaad3ef045fba1a1d7b475fe03714ac
7,185
[ -1 ]
7,186
png.lisp
mrossini-ethz_parseq/examples/png.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; Parsing expression grammar example for binary data: PNG file ;; format. The PNG image file is not completely interpreted, just the ;; different chunks are identified and made available as data vectors. ;; Root parsing expression (defrule png () (and signature header-chunk (* chunk) end-chunk)) ;; Magic number for PNG files. Compare to literal vector. (defrule signature () #(137 80 78 71 13 10 26 10)) ;; Each chunk contains information about how long it is. Use a length ;; variable to store that information when read. (defrule chunk (&optional test-type) (and chunk-length chunk-type chunk-data chunk-crc) (:let (len 0)) (:test (len type data crc) (declare (ignore len data crc)) (if test-type (string= type test-type) (string/= type "IEND")))) ;; Data length is 4 bytes big endian. Convert and set the length ;; variable. (defrule chunk-length () (rep 4 byte) (:external len) (:lambda (b3 b2 b1 b0) (setf (ldb (byte 8 24) len) b3) (setf (ldb (byte 8 16) len) b2) (setf (ldb (byte 8 8) len) b1) (setf (ldb (byte 8 0) len) b0) len)) ;; Chunk type is 4 bytes ASCII. (defrule chunk-type () (rep 4 byte) (:string)) ;; Chunk data length is indicated by the length variable. Convert to ;; vector. (defrule chunk-data () (rep len byte) (:external len) (:function #'vector)) ;; Chunk CRC is 4 bytes. Convert to vector. CRC check would be ;; possible here. (defrule chunk-crc () (rep 4 byte) (:function #'vector)) ;; Header chunk is a normal chunk of type IHDR (defrule header-chunk () (chunk "IHDR")) ;; END chunk is a normal chunk of type IEND (defrule end-chunk () (chunk "IEND")) ;; Enable rule tracing. (trace-rule 'png :recursive t) ;; Parse a file. Substitute your sample file here. (with-open-file (f "image.png" :element-type '(unsigned-byte 8)) (let ((content (make-array (file-length f)))) (read-sequence content f) (parseq 'png content :parse-error t)))
2,004
Common Lisp
.lisp
48
39.208333
87
0.701132
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
584ad2fb9f3761fe52c8aae808e702fb17f75a54160db67c230fc479704a6c8c
7,186
[ -1 ]
7,187
exponential.lisp
mrossini-ethz_parseq/examples/exponential.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; Some parsing expression grammars lead to exponential processing time. ;; Here is an example of such a case: (with-local-rules (defrule a () "a") (defrule b () (or (and a "b") a)) (defrule c () (or (and b "c") b)) (defrule d () (or (and c "d") c)) (defrule e () (or (and d "e") d)) (defrule f () (or (and e "f") e)) (defrule g () (or (and f "g") f)) (defrule h () (or (and g "h") g)) (defrule i () (or (and h "i") h)) (defrule j () (or (and i "j") i)) (trace-rule 'j :recursive t) (format t "Without packrat parsing:~%") (parseq 'j "a")) ;; With packrat parsing enabled: (with-local-rules (defrule a () "a" (:packrat t)) (defrule b () (or (and a "b") a) (:packrat t)) (defrule c () (or (and b "c") b) (:packrat t)) (defrule d () (or (and c "d") c) (:packrat t)) (defrule e () (or (and d "e") d) (:packrat t)) (defrule f () (or (and e "f") e) (:packrat t)) (defrule g () (or (and f "g") f) (:packrat t)) (defrule h () (or (and g "h") g) (:packrat t)) (defrule i () (or (and h "i") h) (:packrat t)) (defrule j () (or (and i "j") i) (:packrat t)) (trace-rule 'j :recursive t) (format t "With packrat parsing:~%") (parseq 'j "a")) ;; From the tracing output it is clear, that packrat parsing is much faster. ;; Packrat parsing guarantees linear time at the cost of increased memory usage. ;; However, changing the parsing grammar expression yields an even better performance, ;; even without packrat parsing. It is unclear whether all such cases can be ;; simplified in this way. (with-local-rules (defrule a () "a") (defrule b () (? "b")) (defrule c () (? "c")) (defrule d () (? "d")) (defrule e () (? "e")) (defrule f () (? "f")) (defrule g () (? "g")) (defrule h () (? "h")) (defrule i () (? "i")) (defrule j () (? "j")) (defrule abcdefghij () (and a b c d e f g h i j)) (trace-rule 'abcdefghij :recursive t) (format t "Different parsing grammar expression, without packrat:~%") (parseq 'abcdefghij "a")) ;; Another example: The original rules, but packrat parsing is enabled only for every other rule. (with-local-rules (defrule a () "a" (:packrat t)) (defrule b () (or (and a "b") a) (:packrat nil)) (defrule c () (or (and b "c") b) (:packrat t)) (defrule d () (or (and c "d") c) (:packrat nil)) (defrule e () (or (and d "e") d) (:packrat t)) (defrule f () (or (and e "f") e) (:packrat nil)) (defrule g () (or (and f "g") f) (:packrat t)) (defrule h () (or (and g "h") g) (:packrat nil)) (defrule i () (or (and h "i") h) (:packrat t)) (defrule j () (or (and i "j") i) (:packrat nil)) (trace-rule 'j :recursive t) (format t "Original parsing grammar expression, with packrat parsing (every other rule):~%") (parseq 'j "a"))
2,806
Common Lisp
.lisp
69
38
97
0.594575
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4c296157b6156a1751e3d2fc3e9c7fe3ff6a1bab3271b08413a8656950e4652b
7,187
[ -1 ]
7,188
calculator.lisp
mrossini-ethz_parseq/examples/calculator.lisp
(require :asdf) (asdf:load-system :parseq) (use-package :parseq) ;; This file shows multiple examples involving the parsing of mathematical ;; expressions: The first example demonstrates the basics of rules and parses a ;; simple mathematical expression without changing anything in the parsing ;; result. The second example performs some basic transformations to simplify ;; the result. The third example performs more advanced transformations to ;; clean up the parsing result and make it human readable. The fourth example ;; (actually 3b) transforms the result into a valid lisp s-expression. You ;; could call that a compiler. In the fifth example, the mathematical ;; expression is evaluated during parsing and the parsing result is the ;; calculated result. ;; All examples parse the mathematical term ((12 - 3) * 4) ^ (1 / (5 + -3)) and ;; for each of them the result is different, because different processing ;; options are used. The grammar is always exactly the same way and the rules ;; are repeated for each example. ;; Example 1 - No transformations --------------------------------------------- ;; The 'space' rule matches zero or multiple space characters. (defrule space () (* #\Space)) ;; A value is an optional sign and a series of digits. Therefore, only integers ;; are supported here. (defrule value () (and (? #\-) (+ (char "0-9")))) ;; The 'bracket' rule allows recursion of the rules. It calls the toplelvel ;; rule 'sum'. This is sensible because expressions within brackets are ;; completely self-contained. Because of the bracket character, there is no ;; left recursion. (defrule bracket () (and #\( sum #\))) ;; Here, a term is either a value or a bracket expression. (defrule term () (or value bracket)) ;; We use the 'binary' rule to simplify subsequent rules by using rule ;; parameters. This is because each binary operator will allow some space ;; characters left and right and it would be tedious to repeat the same parsing ;; rule over and over. (defrule binary (symb) (and space symb space)) ;; The binary operators are defined using the 'binary' rule using the character ;; that they should match as a parameter. (defrule add () (binary #\+)) (defrule sub () (binary #\-)) (defrule mul () (binary #\*)) (defrule div () (binary #\/)) (defrule exp () (binary #\^)) ;; The 'power' rule processes a term (value or bracket expression), optionally ;; with an exponent which can again be a power. This is the operator with ;; highest precedence in this grammar. (defrule power () (and term (? (and exp power)))) ;; The 'product' rule processes one or more a power expressions, separated by ;; the multiply or division operator. (defrule product () (and power (* (and (or mul div) power)))) ;; The 'sum' rule processes one or more product expressions, separated by the ;; addition and subtraction operators. It is the operator with lowest ;; precedence and it represents the top rule for this grammar. (defrule sum () (and product (* (and (or add sub) product)))) ;; Turn on rule tracing to visualize the parsing process (trace-rule 'sum :recursive t) ;; The toplevel rule is 'sum'. The following expression uses the rule to ;; successfully parse a moderately complex mathematical expression. The result, ;; however, is a horrible mess of nested lists containing single characters and ;; NIL. (parseq 'sum "((12 - 3) * 4) ^ (1 / (5 + -3))") ;; Result of the previous expression: ;; ;; ((((#\( ;; ((((#\( ;; ((((NIL (#\1 #\2)) NIL) NIL) ;; ((((#\ ) #\- (#\ )) (((NIL (#\3)) NIL) NIL)))) ;; #\)) ;; NIL) ;; ((((#\ ) #\* (#\ )) ((NIL (#\4)) NIL)))) ;; NIL) ;; #\)) ;; (((#\ ) #\^ (#\ )) ;; ((#\( ;; ((((NIL (#\1)) NIL) ;; ((((#\ ) #\/ (#\ )) ;; ((#\( ;; ((((NIL (#\5)) NIL) NIL) ;; ((((#\ ) #\+ (#\ )) (((#\- (#\3)) NIL) NIL)))) ;; #\)) ;; NIL)))) ;; NIL) ;; #\)) ;; NIL))) ;; NIL) ;; NIL) ;; ;; There is excessive nesting because of the many rules that are applied and ;; each of them generates a level of nesting. There are also many NILs because ;; of optional parts in the parsing rules. But it shows you what the parser is ;; actually doing when processing the input. It would be nice to clean this up ;; to make it more usable. This could be done by using some elaborate post ;; processing code after parsing is finished or - much better - perform simple ;; processing during parsing. See the examples below. ;; Example 2 - Simple transformations ----------------------------------------- (defrule space () (* #\Space)) ;; Concatenate the characters of a number into a string. (defrule value () (and (? #\-) (+ (char "0-9"))) (:string)) ;; Discard the brackets in a bracket expression. (defrule bracket () (and #\( sum #\)) (:choose 1)) (defrule term () (or value bracket)) ;; Discard the spaces around binary operators. (defrule binary (symb) (and space symb space) (:choose 1)) ;; Use a lisp symbol instead of text characters for better readability. (defrule add () (binary #\+) (:constant '+)) (defrule sub () (binary #\-) (:constant '-)) (defrule mul () (binary #\*) (:constant '*)) (defrule div () (binary #\/) (:constant '/)) (defrule exp () (binary #\^) (:constant '^)) ;; Let's leave these as they are for now. (defrule power () (and term (? (and exp power)))) (defrule product () (and power (* (and (or mul div) power)))) (defrule sum () (and product (* (and (or add sub) product)))) ;; Parsing the same expression again, the result is now much simpler. (parseq 'sum "((12 - 3) * 4) ^ (1 / (5 + -3))") ;; Result of the previous expression: ;; ;; ((((((((("12" NIL) NIL) ((- (("3" NIL) NIL)))) NIL) ((* ("4" NIL)))) NIL) ;; (^ ;; (((("1" NIL) ((/ (((("5" NIL) NIL) ((+ (("-3" NIL) NIL)))) NIL)))) NIL) ;; NIL))) ;; NIL) ;; NIL) ;; ;; The characters have been converted to strings (e.g. '#\1 #\2' is now "12") ;; and symbols ('#\+' is now '+'). Whitespace and bracket characters have been ;; eliminated. The expression is still full of brackets (but not bracket ;; characters), because lisp uses brackets for the tree structure of the ;; result. The nesting of the tree structure is reduced because the rules ;; 'value', 'bracket' and 'binary' each remove one level with their processing ;; options. ;; Example 3a - Advanced transformations -------------------------------------- ;; Helper function that turns '(a ((b c) (d e) ...))' into '(a b c d e ...)' ;; and '(a nil)' into 'a'. (defun helper-1 (a rest) (if rest (apply #'concatenate `(list (,a) ,@rest)) a)) ;; Helper function that turns '(a (b c))' into '(a b c)' and '(a nil)' into ;; 'a'. (defun helper-2 (a bc) (if bc (helper-1 a (list bc)) a)) (defrule space () (* #\Space)) ;; Convert the string to an integer using common lisp's built-in function ;; 'parse-integer'. (defrule value () (and (? #\-) (+ (char "0-9"))) (:string) (:function #'parse-integer)) (defrule bracket () (and #\( sum #\)) (:choose 1)) (defrule term () (or value bracket)) (defrule binary (symb) (and space symb space) (:choose 1)) (defrule add () (binary #\+) (:constant '+)) (defrule sub () (binary #\-) (:constant '-)) (defrule mul () (binary #\*) (:constant '*)) (defrule div () (binary #\/) (:constant '/)) (defrule exp () (binary #\^) (:constant '^)) ;; Use a helper function to tranform the result of the 'power' rule. This turns ;; '(a (^ b))' into '(a ^ b)' and '(a NIL)' into 'a'. (defrule power () (and term (? (and exp power))) (:function #'helper-2)) ;; Use another helper function to tranform the result of 'product' and 'sum'. ;; For example, this turns '(a (+ b) (-c))' into '(a + b - c)'. (defrule product () (and power (* (and (or mul div) power))) (:function #'helper-1)) (defrule sum () (and product (* (and (or add sub) product))) (:function #'helper-1)) ;; Parsing the same expression again. (parseq 'sum "((12 - 3) * 4) ^ (1 / (5 + -3))") ;; The result is now '(((12 - 3) * 4) ^ (1 / (5 + -3)))' but this time it is ;; not a string anymore but a list of lisp integers and symbols! This is not ;; particularly useful, but looks nice - at least to humans. ;; Example 3b - Transform expression into a lisp form (compiler) -------------- ;; Note that example 3b is based on example 2 and not example 3a! The reason is ;; that lisp's syntax is different from normal mathematical syntax. (defrule space () (* #\Space)) ;; Convert the string to an integer using common lisp's built-in function ;; 'parse-integer'. (defrule value () (and (? #\-) (+ (char "0-9"))) (:string) (:function #'parse-integer)) (defrule bracket () (and #\( sum #\)) (:choose 1)) (defrule term () (or value bracket)) (defrule binary (symb) (and space symb space) (:choose 1)) (defrule add () (binary #\+) (:constant '+)) (defrule sub () (binary #\-) (:constant '-)) (defrule mul () (binary #\*) (:constant '*)) (defrule div () (binary #\/) (:constant '/)) (defrule exp () (binary #\^) (:constant '^)) ;; Because lisp's syntax is already like a parse tree, there is not much to do ;; for the 'power', 'product' and 'sum' rules. We essentially only have to make ;; a list and put the operator in front. Of course we discard the optional ;; parts if they are not present. (defrule power () (and term (? (and exp power))) (:lambda (term exp+power) (if exp+power `(expt ,term ,(second exp+power)) term))) (defrule product () (and power (* (and (or mul div) power))) (:lambda (first rest) (if rest `(* ,first ,@rest) first))) (defrule sum () (and product (* (and (or add sub) product))) (:lambda (first rest) (if rest `(+ ,first ,@rest) first))) ;; Parsing the same expression again: (parseq 'sum "((12 - 3) * 4) ^ (1 / (5 + -3))") ;; This is the result: ;; (EXPT (* (+ 12 (- 3)) (* 4)) (* 1 (/ (+ 5 (+ -3))))) ;; ;; It's a valid lisp expression with only few extraneous operations that would ;; require a bit more work to remove. We just turned human readable code into ;; machine readable code! ;; We can use this to create a lisp macro if we like to save us from having to ;; write complicated lisp expressions: (defmacro easy-math (math-string) (parseq 'sum math-string :parse-error t)) (easy-math "3+4^2") ;; As an exercise, the reader could change the parsing rules to allow variables ;; in the math expressions. That's actually really easy. Then, we could do ;; actual math on variables in lisp by using this macro! ;; Example 3c - Calculate the result while parsing (calculator) --------------- ;; Note that example 3c is based on example 2 and not example 3a or 3b! This is ;; because in example 3a, the results from the 'power', 'product' and 'sum' ;; rules are processed in a way that is not particularly suitable for ;; evaluation - the intent was a nice visual representation. We could of course ;; just eval the result of example 3b, but that would be cheating! (defrule space () (* #\Space)) ;; Convert the string to an integer using common lisp's built-in function ;; 'parse-integer'. (defrule value () (and (? #\-) (+ (char "0-9"))) (:string) (:function #'parse-integer)) (defrule bracket () (and #\( sum #\)) (:choose 1)) (defrule term () (or value bracket)) (defrule binary (symb) (and space symb space) (:choose 1)) (defrule add () (binary #\+) (:constant '+)) (defrule sub () (binary #\-) (:constant '-)) (defrule mul () (binary #\*) (:constant '*)) (defrule div () (binary #\/) (:constant '/)) (defrule exp () (binary #\^) (:constant '^)) ;; Use a lambda function to calculate the power if an exponent is given and ;; return the value of 'term' if there is no exponent. (defrule power () (and term (? (and exp power))) (:lambda (term exp+power) (if exp+power (expt term (second exp+power)) term))) ;; The direct output of 'product' and 'sum' is something like (a (+ b) (- c) ;; ...). Conveniently, the symbols '+', '-', '*' and '/' already denote lisp ;; functions. Except for the first, the items in the list (e.g. '(+ b)' and '(- ;; c') can therefore be funcalled. The results can then be added together. This ;; is achieve with a lambda function that acts on the parsing result. (defrule product () (and power (* (and (or mul div) power))) (:lambda (first rest) (apply #'* first (mapcar (lambda (ab) (funcall (first ab) (second ab))) rest)))) (defrule sum () (and product (* (and (or add sub) product))) (:lambda (first rest) (apply #'+ first (mapcar (lambda (ab) (funcall (first ab) (second ab))) rest)))) ;; Parsing the same expression again, the result is now '6.0'. The value is ;; floating point, because a square root was calculated (due to the exponent ;; being '1/2'). (parseq 'sum "((12 - 3) * 4) ^ (1 / (5 + -3))") ;; As an exercise, the reader could change the parsing rules to allow floating ;; point numbers in the input. In a second step, it would be nice to have ;; functions such as 'sin(...)' and 'cos(...)' and so on. That is not too much ;; work, actually.
13,121
Common Lisp
.lisp
245
52.306122
104
0.637844
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
e2dbfb129f570882c9c1f4adb07639938c4a9b9a205bf7f42719f3c53de7f99f
7,188
[ -1 ]
7,189
parseq.asd
mrossini-ethz_parseq/parseq.asd
(defsystem "parseq" :description "A library for parsing sequences such as strings and lists using parsing expression grammars." :version "0.5.0" :author "Marco Rossini" :license "GPLv2" :serial t :components ((:file "package") (:file "conditions") (:file "utils") (:file "defrule")) :in-order-to ((test-op (test-op :parseq/test)))) (defsystem "parseq/test" :description "Unit testing for parseq." :author "Marco Rossini" :license "GPLv2" :depends-on (:parseq) :serial t :components ((:file "test/unit-test") (:file "test/test"))) (defmethod perform ((operation test-op) (system (eql (find-system :parseq/test)))) (funcall (intern "PARSEQ-TEST" :parseq)))
745
Common Lisp
.asd
21
30.190476
109
0.645429
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
611b6c4dd7cd4d5fe49c8c551720b74b031f278c8f5c035a32221b10540015a1
7,189
[ -1 ]
7,194
compile-test.sh
mrossini-ethz_parseq/test/compile-test.sh
#!/bin/bash if [[ $# != 1 ]] then echo "Argument error!" echo "Usage: $0 <sbcl|cmucl|ecl|clisp|all>" exit 1 fi if [[ "$1" == "sbcl" ]] || ([[ "$1" == "all" ]] && which sbcl) then sbcl --noinform \ --disable-ldb \ --lose-on-corruption \ --end-runtime-options \ --no-sysinit \ --no-userinit \ --disable-debugger \ --eval '(require :asdf)' \ --eval '(asdf:load-system :parseq :force t)' \ --quit \ --end-toplevel-options fi if [[ "$1" == "cmucl" ]] || ([[ "$1" == "all" ]] && which lisp) then lisp -batch \ -eval '(require :asdf)' \ -eval '(asdf:load-system :parseq :force t)' \ -eval '(quit)' fi if [[ "$1" == "ecl" ]] || ([[ "$1" == "all" ]] && which ecl) then ecl -q \ -eval '(require :asdf)' \ -eval '(asdf:load-system :parseq :force t)' \ -eval '(quit)' fi if [[ "$1" == "clisp" ]] || ([[ "$1" == "all" ]] && which clisp) then clisp -q \ -x '(require :asdf)' \ -x '(asdf:load-system :parseq :force t)' fi
955
Common Lisp
.l
41
21.121951
64
0.542354
mrossini-ethz/parseq
28
3
3
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a66ee0956619f527685ad7c5900ab2338f40d43e16f228a40a6ca808d5575918
7,194
[ -1 ]
7,216
package.lisp
VincentToups_shadchen/package.lisp
;;;; package.lisp (defpackage #:shadchen (:nicknames :s?) (:export :? :bq :p :list-rest :hash-table :struct :let1 :must-match :! :defun-match :defun-match- :match :match-lambda :defpattern :match-let :match-let* :match-loop :tail :number :symbol :string :keyword :_ :-ignore- :ignore :list*) (:use #:cl))
342
Common Lisp
.lisp
10
29.5
58
0.626911
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c911848d452a4a614a3d5cf4be688e43ce0e275016db8fcf3f3549054f13997e
7,216
[ -1 ]
7,217
scratch.lisp
VincentToups_shadchen/scratch.lisp
;;;; shadchen.lisp ;;; Copyright 2012, Vincent Toups ;;; This program is distributed under the terms of the GNU Lesser ;;; General Public License (see license.txt). (in-package #:shadchen) (defun non-nil (x) x) (eval-when (:compile-toplevel :load-toplevel :execute) (defpattern cons* (car cdr) `(? #'non-nil (cons ,car ,cdr)))) (match (cons 10 11) ((cons* a b) a))
377
Common Lisp
.lisp
11
32.181818
66
0.693593
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
05452df08784fd0afe87e50e1f7abda5f2b0d64bea6a7e096ccf67b8149f65a1
7,217
[ -1 ]
7,218
tests.lisp
VincentToups_shadchen/tests.lisp
;;;; tests.lisp (in-package #:shadchen) (eos:test list1 (eos:is (equal (list :q :r :s) (match (list :s :r :q) ((list x y z) (list z y x)))))) (eos:test list2 (eos:is (equal (* 1 2 3) (match (list 1 2 3) ((list x y z) (* x y z)))))) (eos:test list-tail (eos:is (equal '(x y z) (match '(q r s t u v w x y z) ((list _ _ _ _ _ _ _ (tail the-tail)) the-tail))))) (eos:test numeric-literal (eos:is (equal :matched (match 10 (11 :did-not-match) (10 :matched))))) (eos:test string-literal (eos:is (equal :matched (match "cat" (15 :did-not-match) ("cat" :matched))))) (eos:test keyword-literal (eos:is (equal :matched (match :x (15 :did-not-match) (:x :matched))))) (eos:test cons (eos:is (equal '(b c) (match '(a b c) (15 :did-not-match) ((cons -ignore- tail) tail))))) (eos:test quote (eos:is (equal :matched (match 'x ((cons _ _) :did-not-match) ('x :matched))))) (eos:test number1 (eos:is (equal :matched (match 10 ((symbol) :did-not-match) ((number) :matched))))) (eos:test number2 (eos:is (equal :matched (match 10 ((number (p #'(lambda (x) (< x 9)))) :did-not-match) ((number (p #'(lambda (x) (> x 9)))) :matched))))) (eos:test string1 (eos:is (equal :matched (match "x" ((symbol) :did-not-match) ((string) :matched))))) (eos:test string2 (eos:is (equal :matched (match "cat" ((string (p #'(lambda (x) (= 7 (length x))))) :did-not-match) ((string (p #'(lambda (x) (= (length x) 3)))) :matched))))) (eos:test keyword1 (eos:is (equal :matched (match :x ((non-kw-symbol) :did-not-match) ((keyword) :matched))))) (eos:test keyword2 (eos:is (equal :matched (match :cat ((keyword (p #'(lambda (x) (= 7 (length (symbol-name x)))))) :did-not-match) ((keyword (p #'(lambda (x) (= (length (symbol-name x)) 3)))) :matched))))) (eos:test p (eos:is (equal 10 (match 10 ((p #'numberp n) n))))) (eos:test funcall (eos:is (equal 11 (match 10 (:x :did-not-match) ((funcall #'(lambda (x) (+ x 1)) r) r))))) (eos:test or (eos:is (equal :matched (match 10 ((or 14 :x) :did-not-match) ((or 10 11) :matched))))) (eos:test bq (eos:is (equal 'b (match '(a b c) ((bq (a (uq x) c)) x))))) (eos:test let (eos:is (equal '(a b c) (match (list) ((let (x 'a) (y 'b) (z 'c)) (list x y z)))))) (eos:test must-match-succeed-case (eos:is (equal 10 (match 10 ((must-match (number x)) x))))) (eos:test must-match-fail-case (eos:signals (simple-error) (equal :x (match :x ((must-match (number x)) x))))) (defpackage shadchen-tests) (defun-match- shadchen-tests::product (nil acc) acc) (defun-match shadchen-tests::product ((list (! (number x)) (tail rest)) acc) (shadchen-tests::product rest (* x acc))) (defun-match shadchen-tests::product (anything) (shadchen-tests::product anything 1)) (eos:test defun-match (eos:is (equal 24 (shadchen-tests::product '(1 2 3 4))))) (eos:test defun-match-with-fail (eos:signals (simple-error) (shadchen-tests::product '(1 a 3 4)))) (eos:run!)
3,400
Common Lisp
.lisp
163
16.423313
58
0.5467
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
c3139693a210ec3e28c712c936c5dc3df285ef72ac049cf38bb3b42167848ff3
7,218
[ -1 ]
7,219
shadchen.lisp
VincentToups_shadchen/shadchen.lisp
;;;; shadchen.lisp ;;; Copyright 2012, Vincent Toups ;;; This program is distributed under the terms of the GNU Lesser ;;; General Public License (see license.txt). (in-package #:shadchen) (defstruct match-fail-struct) (defvar *match-fail* (make-match-fail-struct)) (eval-when (:compile-toplevel :load-toplevel :execute) (defun non-keyword-symbol (o) (and o (symbolp o) (not (keywordp o)))) (defun match-list-expander* (sub-expressions match-value body) (cond ((not sub-expressions) `(if (not ,match-value) (progn ,@body) *match-fail*)) ((and (listp sub-expressions) (= 1 (length sub-expressions)) (listp (car sub-expressions)) (= 2 (length (car sub-expressions))) (eq 'tail (car (car sub-expressions)))) (let ((pattern (cadr (car sub-expressions)))) `(match1 ,pattern ,match-value ,@body))) (:otherwise (let ((first-expression (car sub-expressions)) (list-name (gensym "MATCH-LIST-EXPANDER*-"))) `(let ((,list-name ,match-value)) (if (and (listp ,list-name) ,list-name) (match1 ,first-expression (car ,list-name) (match1 (list ,@(cdr sub-expressions)) (cdr ,list-name) ,@body)) *match-fail*)))))) (defun match-list-expander (match-expression match-value body) (match-list-expander* (cdr match-expression) match-value body)) (defun match-cons-expander (match-expression match-value body) (let ((car-match (elt match-expression 1)) (cdr-match (elt match-expression 2)) (name (gensym "MATCH-CONS-EXPANDER-"))) `(let ((,name ,match-value)) (if (listp ,name) (match1 ,car-match (car ,name) (match1 ,cdr-match (cdr ,name) ,@body)) *match-fail*)))) (defun match-quote-expander (match-expression match-value body) `(if (equalp ,match-expression ,match-value) (progn ,@body) *match-fail*)) (defun uq? (e) (and (listp e) (eq (car e) 'uq))) (defun bq->regular-match (bq-expression) (let ((sub-expr (cadr bq-expression))) (cond ((uq? sub-expr) `(quote ,(cadr sub-expr))) ((listp sub-expr) `(list ,@(mapcar (lambda (expr) (cond ((uq? expr) (cadr expr)) (t `(quote ,expr)))) sub-expr))) (t sub-expr)))) (defun match-backquote-expander (match-expression match-value body) `(match1 ,(bq->regular-match match-expression) ,match-value ,@body)) (defun match-and-expander* (sub-expressions match-name body) (cond ((equal sub-expressions '(and*)) `(progn ,@body)) (:otherwise (let ((s1 (cadr sub-expressions))) `(match1 ,s1 ,match-name (match1 (and* ,@(cddr sub-expressions)) ,match-name ,@body)))))) (defun match-and-expander (match-expression match-value body) (let ((name (gensym "MATCH-AND-EXPANDER-"))) `(let ((,name ,match-value)) (match1 (and* ,@(cdr match-expression)) ,name ,@body)))) (defun match-?-expander (match-expression match-value body) (let ((name (gensym "MATCH-?-EXPANDER-NAME-")) (f-name (gensym "MATCH-?-EXPANDER-FUNCTION-"))) (case (length (cdr match-expression)) (0 (error "MATCH1: MATCH-?-EXPANDER: zero arguments to MATCH-?-EXPANDER. Needs 1 or 2.")) (1 `(let ((,name ,match-value) (,f-name ,(cadr match-expression))) (if (funcall ,f-name ,name) (progn ,@body) *match-fail*))) (2 `(let ((,name ,match-value) (,f-name ,(cadr match-expression))) (if (funcall ,f-name ,name) (match1 ,(elt match-expression 2) ,name ,@body) *match-fail*))) (otherwise (error "MATCH-?-EXPANDER: MATCH-?-EXPANDER takes only 1 or 2 arguments."))))) (defun match-values-expander (match-expression match-value body) (let ((name (gensym "MATCH-VALUES-EXPANDER-"))) `(let ((,name (multiple-value-list ,match-value))) (match1 (list ,@(cdr match-expression)) ,name ,@body)))) (defun match-funcall-expander (match-expression match-value body) (assert (and (listp match-expression) (= 3 (length match-expression))) (match-expression) "MATCH-FUNCALL-EXPANDER: FUNCALL match expression must have two terms, a function and a match against the result. Got ~a." match-expression) (let ((name (gensym "MATCH-FUNCALL-EXPANDER-NAME-")) (fun-name (gensym "MATCH-FUNCALL-EXPANDER-FUN-NAME-")) (result-name (gensym "MATCH-FUNCALL-EXPANDER-RESULT-NAME-"))) `(let* ((,name ,match-value) (,fun-name ,(cadr match-expression)) (,result-name (funcall ,fun-name ,name))) (match1 ,(caddr match-expression) ,result-name ,@body)))) (defvar *extended-patterns* (make-hash-table) "Holds user declared patterns.") (defun extended-patternp (pattern-head) "Return T if PATTERN-HEAD indicates a user provided pattern." (multiple-value-bind (val in) (gethash pattern-head *extended-patterns*) (declare (ignore val)) in)) (defun match-extended-pattern-expander (match-expression match-value body) (let* ((pattern-args (cdr match-expression)) (pattern-fun (gethash (car match-expression) *extended-patterns*)) (expansion (apply pattern-fun pattern-args))) `(match1 ,expansion ,match-value ,@body))) (defmacro defpattern (name args &body body) `(setf (gethash ',name *extended-patterns*) #'(lambda ,args ,@body))) (defun match-literal-string (match-expression match-value body) `(if (equalp ,match-expression ,match-value) (progn ,@body) *match-fail*)) (defun match-literal-number (match-expression match-value body) `(if (equalp ,match-expression ,match-value) (progn ,@body) *match-fail*)) (defun match-literal-character (match-expression match-value body) `(if (equalp ,match-expression ,match-value) (progn ,@body) *match-fail*)) (defun match-literal-keyword (match-expression match-value body) `(if (equalp ,match-expression ,match-value) (progn ,@body) *match-fail*)) (defun match-let-expander (match-expression match-value body) (declare (ignore match-value)) `(let ,(cdr match-expression) ,@body)) (defun match-or-expander-unsafe (match-expression match-value body) (cond ((length=1 (cdr match-expression)) `(match1 ,(cadr match-expression) ,match-value ,@body)) (:otherwise (let* ((forms (cdr match-expression)) (form (car forms)) (rest (cdr forms)) (nm (gensym "MATCH-OR-EXPANDER-NM-")) (result-values-list (gensym "result-values-list-")) (result (gensym "result"))) `(let* ((,nm ,match-value)) (let* ((,result-values-list (multiple-value-list (match1 ,form ,nm ,@body))) (,result (car ,result-values-list))) (if (not (eq *match-fail* ,result)) (apply #'values ,result-values-list) (match1 (or ,@rest) ,nm ,@body)))))))) (defun match-or-expander (match-expression match-value body) (assert (apply #'equal-by-binding (cdr match-expression)) (match-expression) "Or sub-expressions ~S contains sub-forms which do not bind identical sets of symbols." match-expression) (match-or-expander-unsafe match-expression match-value body)) ;;; (defun mapcat (f lst) (loop for item in lst append (funcall f item))) (defun calc-pattern-bindings-extended (expr) "Calculate the bound symbols of a user defined pattern." (let* ((pattern-args (cdr expr)) (pattern-fun (gethash (car expr) *extended-patterns*)) (expansion (apply pattern-fun pattern-args))) (calc-pattern-bindings expansion))) (defun calc-backquote-bindings (expr) "Calculate the bindings for a backquote expression." (loop for sub in (cdr expr) when (and (listp sub) (eq (car sub) 'uq)) append (calc-pattern-bindings (cadr sub)))) (defun calc-pattern-bindings-list (expr &optional acc) (cond ((null expr) acc) ((and (listp expr) (listp (car expr)) (eq 'tail (car (car expr)))) (append acc (calc-pattern-bindings (cadr (car expr))))) (t (calc-pattern-bindings-list (cdr expr) (append (calc-pattern-bindings (car expr)) acc))))) (defun calc-pattern-bindings (expr) "Given a shadchen pattern EXPR return a list of symbols bound by that expression." (cond ((non-keyword-symbol expr) (list expr)) ((vectorp expr) (calc-pattern-bindings `(list ,@(coerce expr 'list)))) ((or (not expr) (symbolp expr) (numberp expr) (stringp expr) (characterp expr)) nil) ((extended-patternp (car expr)) (calc-pattern-bindings-extended expr)) ((listp expr) (case (car expr) (quote nil) ((and values) (mapcat #'calc-pattern-bindings (cdr expr))) (list (calc-pattern-bindings-list (cdr expr))) (cons (append (calc-pattern-bindings (car expr)) (calc-pattern-bindings (cdr expr)))) ((? p funcall) (if (= 2 (length expr)) nil (calc-pattern-bindings (elt expr 2)))) (or (calc-pattern-bindings (cadr expr))) (bq (calc-backquote-bindings expr)) ((! must-match string number keyword non-keyword-symbol) (calc-pattern-bindings (cadr expr))) (one-of (calc-pattern-bindings (cadr expr))) (let (mapcar #'car (cdr expr))) (ignore (list)) (t (error "calc-pattern-bindings: unrecognized pattern ~S." expr)))))) (defun package-name* (p) (if p (package-name p) "no-package-66b73c7f8e8bfa094fa23b4264978ed1")) (defun symbol< (s1 s2) (let ((p1 (package-name* (symbol-package s1))) (n1 (symbol-name s1)) (p2 (package-name* (symbol-package s2))) (n2 (symbol-name s2))) (if (equal p1 p2) (string< n1 n2) (string< p1 p2)))) (defun canonical-binding-list (l) (sort l #'symbol<)) (defun equal-by-binding2 (p1 p2) (equal (canonical-binding-list (calc-pattern-bindings p1)) (canonical-binding-list (calc-pattern-bindings p2)))) (defun equal-by-binding (&rest patterns) (cond ((= 1 (length patterns)) t) ((= 2 (length patterns)) (equal-by-binding2 (car patterns) (cadr patterns))) (t (and (equal-by-binding2 (car patterns) (cadr patterns)) (apply #'equal-by-binding (cdr patterns)))))) ;;; (defun must-match-case (match-expr) (cond ((and (listp match-expr) (= 2 (length match-expr))) :pattern-only) ((and (listp match-expr) (= 4 (length match-expr))) :pattern+) (t :unrecognized))) (defun match-must-match-expander (match-expr val-expr body) (case (must-match-case match-expr) (:pattern-only (destructuring-bind (_ pattern) match-expr (declare (ignore _)) (let ((sym (gensym "must-match-failed-value-"))) (match-must-match-expander `(must-match ,pattern ,sym (format nil ,(format nil "must-match pattern (~S) failed to match ~~S" pattern) ,sym)) val-expr body)))) (:pattern+ (destructuring-bind (_ pattern fail-pattern message-expression) match-expr (declare (ignore _)) (let ((bound-symbols (calc-pattern-bindings pattern)) (value (gensym "must-match-value-")) (result (gensym "must-match-result-"))) `(match1 (funcall (lambda (,value) (let ((,result (match1 ,pattern ,value (list ,@bound-symbols)))) (if (eq *match-fail* ,result) (match ,value (,fail-pattern (let ((,value ,message-expression)) (if (stringp ,value) (error ,value) (error "~S" ,value)))) (_ (error (format nil ,(format nil "must-match pattern (~S) failed and then the failed-value pattern (~S) also failed on value ~~S" pattern fail-pattern) ,value)))) ,result))) (list ,@bound-symbols)) ,val-expr ,@body)))) (t (error "Unrecognized must-match pattern form ~S" match-expr)))) ;;; (defmacro match1 (match-expression match-value &body body) (cond ((not match-expression) `(if (not ,match-value) (progn ,@body) *match-fail*)) ((or (non-keyword-symbol match-expression) (and (listp match-expression) (eq (car match-expression) 'ignore))) (if (or (eq match-expression '_) (eq match-expression '-ignore-) (and (listp match-expression) (eq (car match-expression) 'ignore))) `(progn ,match-value ,@body) `(let ((,match-expression ,match-value)) ,@body))) ((keywordp match-expression) (match-literal-keyword match-expression match-value body)) ((stringp match-expression) (match-literal-string match-expression match-value body)) ((numberp match-expression) (match-literal-number match-expression match-value body)) ((characterp match-expression) (match-literal-character match-expression match-value body)) ((extended-patternp (car match-expression)) (match-extended-pattern-expander match-expression match-value body)) ((listp match-expression) (case (car match-expression) ((! must-match) (match-must-match-expander match-expression match-value body)) (list (match-list-expander match-expression match-value body)) (cons (match-cons-expander match-expression match-value body)) (quote (match-quote-expander match-expression match-value body)) (and (match-and-expander match-expression match-value body)) (and* (match-and-expander* match-expression match-value body)) ((? p) (match-?-expander match-expression match-value body)) (funcall (match-funcall-expander match-expression match-value body)) (or (match-or-expander match-expression match-value body)) (bq (match-backquote-expander match-expression match-value body)) (values (match-values-expander match-expression match-value body)) (let (match-let-expander match-expression match-value body)) (otherwise (error "MATCH1: Unrecognized match-expression ~a" match-expression)))) (:otherwise (error "MATCH1: Unrecognized match-expression ~a" match-expression)))) (defmacro match-helper (value &body forms) (assert (symbolp value) (value) "MATCH-HELPER: VALUE must be a symbol. Got ~a." value) (cond ((not forms) `(error "No Match for ~s." ,value)) ((listp forms) (let ((first-form (car forms))) (assert (and (listp first-form) (> (length first-form) 1)) (first-form) "Each MATCH SUB-FORM must be at least two elements long, a matcher and an expression to evaluate on match. Got ~a instead." first-form) (let ((match-expression (car first-form)) (match-body-exprs (cdr first-form)) (result-name (gensym "MATCH-HELPER-RESULT-NAME-")) (result-values-name (gensym "MATCH-HELPER-RESULT-VALUES-NAME-"))) `(let* ((,result-values-name (multiple-value-list (match1 ,match-expression ,value ,@match-body-exprs))) (,result-name (car ,result-values-name))) (if (not (eq *match-fail* ,result-name)) (apply #'values ,result-values-name) (match-helper ,value ,@(cdr forms))))))))) (defmacro match (value &body forms) "Attempt to match VALUE against each of the patterns in the CAR of FORMS. When a match is detected, its subsequent forms are executed as in a PROGN where the bindings implied by the match are in effect. An error is thrown when no matches are found." (let ((name (gensym "MATCH-VALUE-NAME-"))) `(let ((,name ,value)) (match-helper ,name ,@forms)))) (defmacro match-lambda (&body forms) "Like MATCH except the VALUE is curried." (let ((name (gensym "MATCH-LAMBDA-NAME-"))) `(function (lambda (,name) (match ,name ,@forms))))) (defun length=1 (lst) "Returns T when LST has one element." (and (consp lst) (not (cdr lst))))) (defpattern list-rest (&rest patterns) (let ((n (length patterns))) (cond ((= n 0) '(list)) ((= n 1) `(list (tail ,(car patterns)))) (:otherwise `(list ,@(reverse (cdr (reverse (copy-list patterns)))) (tail ,(car (reverse patterns)))))))) (defpattern list* (&rest patterns) `(list-rest ,@patterns)) (defpattern number (&optional (pattern '_)) `(p #'numberp ,pattern)) (defpattern symbol (&optional (pattern '_)) `(p #'symbolp ,pattern)) (defpattern string (&optional (pattern '_)) `(p #'stringp ,pattern)) (defpattern non-kw-symbol (&optional (pattern '_)) (let ((val (gensym))) `(p #'(lambda (,val) (and (symbolp ,val) (not (keywordp ,val)))) ,pattern))) (defpattern keyword (&optional (pattern '_)) `(p #'keywordp ,pattern)) (defun htbl-fetcher (key) #'(lambda (htbl) (gethash key htbl))) (defmacro named-let (name binders &body body) `(labels ((,name ,(mapcar #'car binders) ,@body)) (,name ,@(mapcar #'cadr binders)))) (defpattern struct (struct-name &rest fields) `(and (? #'(lambda (o) (typep o ',struct-name))) ,@(loop for f in fields collect `(funcall #'(lambda (o) (slot-value o ',(car f))) ,(cadr f))))) (defpattern hash-table (&rest key/pat-pairs) `(and (? #'hash-table-p) ,@(named-let recur ((pairs key/pat-pairs) (acc nil)) (match pairs (nil (reverse acc)) ((cons key (cons pat rest)) (recur rest (cons `(funcall (htbl-fetcher ,key) ,pat) acc))))))) (defpattern let1 (name value) `(let (,name ,value))) (defmacro match-let* (bindings &body body) "Just like let* but each symbol part of each binding can be a match expression of arbitrary complexity." (match bindings ((list) `(progn ,@body)) ((cons (list pattern value) rest-bindings) `(match ,value (,pattern (match-let* ,rest-bindings ,@body)))))) (defmacro match-let (bindings &body body) "Just like let* but each symbol part of each binding can be a match expression of arbitrary complexity." (let ((patterns (mapcar #'car bindings)) (values (mapcar #'cadr bindings))) `(match (list ,@values) ((list ,@patterns) ,@body)))) (defmacro match-loop (recur-point bindings &body body) "Like match-let but the binding form can be re-entered by calling a local function indicated by `recur-point` with the same number of arguments as bindings expressions in BINDINGS." (let ((args (loop for i from 1 to (length bindings) collect (gensym "match-loop-arg-"))) (patterns (mapcar #'car bindings)) (initial-values (mapcar #'cadr bindings))) `(labels ((,recur-point ,args (match (list ,@args) ((list ,@patterns) ,@body)))) (,recur-point ,@initial-values)))) (defvar *match-function-table* (make-hash-table)) (defun extend-defun-match-table (name lexpr) (let ((c (reverse (gethash name *match-function-table*)))) (setf (gethash name *match-function-table*) (reverse (cons lexpr c))))) (defmacro defun-match- (name patterns &body body) (let ((args (gensym)) (funs (gensym)) (fun (gensym)) (rval (gensym)) (loopf (gensym)) (compound-name (intern (format nil "~S (~S)" name patterns))) (doc-string (if (stringp (car body)) (car body) ""))) `(progn (defun ,name (&rest ,args) (named-let ,loopf ((,funs (gethash ',name *match-function-table*))) (if (null ,funs) (error "~S: match fail for ~S." ',name ,args) (let* ((,fun (car ,funs)) (,funs (cdr ,funs)) (,rval (apply ,fun ,args))) (if (eq *match-fail* ,rval) (,loopf ,funs) ,rval))))) (defun ,compound-name (&rest ,args) ,doc-string (match1 (list ,@patterns) ,args ,@body)) (setf (gethash ',name *match-function-table*) (list #',compound-name))))) (defmacro defun-match (name patterns &body body) (let ((compound-name (intern (format nil "~S (~S)" name patterns))) (args (gensym)) (doc-string (if (stringp (car body)) (car body) ""))) `(progn (defun ,compound-name (&rest ,args) ,doc-string (match1 (list ,@patterns) ,args ,@body)) (extend-defun-match-table ',name #',compound-name)))) #| (match 'y ((and (symbol x) (must-match 'z a (format nil "Failed, but got ~S" a))) :hey)) (defun-match- my-prod (anything) (my-prod anything 1)) (defun-match my-prod (nil acc) acc) (defun-match my-prod ((list (must-match x f (format nil "failed on ~s" f)) (tail rest)) acc) (my-prod rest (* acc x))) (my-prod '(1 2 3 4)) (match1 (list (must-match (number x)) (tail tl)) '(1 2 3) tl) (match-loop rec (((list x y) (list 0 0))) (if (< (+ x y) 100) (rec (list (+ x 1) (+ y x))) (list x y))) (match 10 ((or (number val) (string s)) val)) (match (list 1 2) (x x)) (match (list 1 2 3 4) ((list a b (tail c)) c)) (calc-pattern-bindings '(and a b c)) |# ;; (let ((ht (make-hash-table :test #'equal))) ;; (labels ((add (key val) (setf (gethash key ht) val))) ;; (add :x 10) ;; (add :y (list 1 2)) ;; (add :z 'a-value) ;; (match ht ;; ((hash-table ;; :x x ;; :y (list y z)) ;; (list x y z))))) ;;; "shadchen" goes here. Hacks and glory await!
20,438
Common Lisp
.lisp
530
34.133962
123
0.655129
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
daa28b10e168f47dd83afcbd9b20874e740eb0ebfb1d4503ee9b523ae07d4039
7,219
[ -1 ]
7,220
shadchen.asd
VincentToups_shadchen/shadchen.asd
;;;; shadchen.asd ;;; Copyright 2012, Vincent Toups ;;; This program is distributed under the terms of the GNU Lesser ;;; General Public License (see license.txt). (asdf:defsystem #:shadchen :serial t :author "Vincent Toups" :maintainer "Vincent Toups" :description "A pattern matching library." :long-description "Shadchen (matchmaker) is a Racket-inspired pattern matching library." :components ((:file "package") (:file "shadchen")))
451
Common Lisp
.asd
12
35.416667
89
0.748284
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
41709e983ce8cc6eb865efd38ef265a6ca6c864f34dac468fb321011515284d9
7,220
[ -1 ]
7,221
shadchen.asd~
VincentToups_shadchen/shadchen.asd~
;;;; shadchen.asd ;;; Copyright 2012, Vincent Toups ;;; This program is distributed under the terms of the GNU Lesser ;;; General Public License (see license.txt). (asdf:defsystem #:shadchen :serial t :depends-on (#:lisp-unit) :author "Vincent Toups" :maintainer "Vincent Toups" :description "A pattern matching library." :long-description "Shadchen (matchmaker) is a Racket-inspired pattern matching library." :components ((:file "package") (:file "shadchen")))
481
Common Lisp
.asd
13
34.615385
89
0.739785
VincentToups/shadchen
22
0
1
LGPL-3.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
4df49c695e845c747191369d7aac08b5cf6af3be1bfca6248b660a7b233f512c
7,221
[ -1 ]
7,241
group.lisp
blitz_stumpwm/group.lisp
;; Copyright (C) 2003-2008 Shawn Betts ;; ;; This file is part of stumpwm. ;; ;; stumpwm is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; stumpwm is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this software; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ;; Boston, MA 02111-1307 USA ;; Commentary: ;; ;; All group related code resides here ;; ;; Code: (in-package #:stumpwm) (export '(current-group)) (defvar *default-group-type* 'tile-group "The type of group that should be created by default.") (defclass group () ((screen :initarg :screen :accessor group-screen) (windows :initform nil :accessor group-windows) (number :initarg :number :accessor group-number) (name :initarg :name :accessor group-name))) ;;; The group API (defgeneric group-add-window (group window &key &allow-other-keys) (:documentation "Called when a window is added to the group. All house keeping is already taken care of. Only the group's specific window managing housekeeping need be done. This function accepts keys to inform the group on how to place the window.")) (defgeneric group-delete-window (group window) (:documentation "Called when a window is removed from thegroup. All house keeping is already taken care of. Only the group's specific window managing housekeeping need be done.")) (defgeneric group-wake-up (group) (:documentation "When the group becomes the current group, this function is called. This call is expected to set the focus.")) (defgeneric group-suspend (group) (:documentation "When the group is no longer the current group, this function is called.")) (defgeneric group-current-window (group) (:documentation "The group is asked to return its focused window.")) (defgeneric group-current-head (group) (:documentation "The group is asked to return its current head.")) (defgeneric group-resize-request (group window width height) (:documentation "The window requested a width and/or height change.")) (defgeneric group-move-request (group window x y relative-to) (:documentation "The window requested a position change.")) (defgeneric group-raise-request (group window type) (:documentation "A request has been made to raise the window. TYPE is the type of raise request being made. :MAP means the window has made requested to be mapped. :above means the window has requested to to be placed above its siblings.")) (defgeneric group-lost-focus (group) (:documentation "The current window was hidden or destroyed or something happened to it. So the group is asked to do something smart about it.")) (defgeneric group-indicate-focus (group) (:documentation "The group is asked to in some way show the user where the keyboard focus is.")) (defgeneric group-focus-window (group win) (:documentation "The group is asked to focus the specified window wherever it is.")) (defgeneric group-button-press (group x y child) (:documentation "The user clicked somewhere in the group.")) (defgeneric group-root-exposure (group) (:documentation "The root window got an exposure event. If the group needs to redraw anything on it, this is where it should do it.")) (defgeneric group-add-head (group) (:documentation "A new head was added.")) (defgeneric group-sync-head (group head) (:documentation "When a head or its usable area is resized, this is called. When the modeline size changes, this is called.")) (defun current-group (&optional (screen (current-screen))) "Return the current group for the current screen, unless otherwise specified." (screen-current-group screen)) (defun move-group-to-head (screen group) "Move window to the head of the group's window list." ;(assert (member window (screen-mapped-windows screen))) (move-to-head (screen-groups screen) group)) (defun sort-groups (screen) "Return a copy of the screen's group list sorted by number." (sort1 (screen-groups screen) '< :key 'group-number)) (defun fmt-group-status (group) (let ((screen (group-screen group))) (cond ((eq group (screen-current-group screen)) #\*) ((and (typep (second (screen-groups screen)) 'group) (eq group (second (screen-groups screen)))) #\+) (t #\-)))) (defun find-free-group-number (screen) "Return a free group number in SCREEN." (find-free-number (mapcar 'group-number (screen-groups screen)) 1)) (defun find-free-hidden-group-number (screen) "Return a free hidden group number for SCREEN. Hidden group numbers start at -1 and go down." (find-free-number (mapcar 'group-number (screen-groups screen)) -1 :negative)) (defun non-hidden-groups (groups) "Return only those groups that are not hidden." (remove-if (lambda (g) (< (group-number g) 1)) groups)) (defun netwm-group-id (group) "netwm specifies that desktop/group numbers are contiguous and start at 0. Return a netwm compliant group id." (let ((screen (group-screen group))) (position group (sort-groups screen)))) (defun switch-to-group (new-group) (let* ((screen (group-screen new-group)) (old-group (screen-current-group screen))) (unless (eq new-group old-group) ;; restore the visible windows (dolist (w (group-windows new-group)) (when (eq (window-state w) +normal-state+) (xwin-unhide (window-xwin w) (window-parent w)))) (dolist (w (reverse (group-windows old-group))) (when (eq (window-state w) +normal-state+) (xwin-hide w))) (setf (screen-current-group screen) new-group) (move-group-to-head screen new-group) ;; restore the focus (setf (screen-focus screen) nil) (group-wake-up new-group) (xlib:change-property (screen-root screen) :_NET_CURRENT_DESKTOP (list (netwm-group-id new-group)) :cardinal 32) (update-all-mode-lines) (run-hook-with-args *focus-group-hook* new-group old-group)))) (defun move-window-to-group (window to-group) (labels ((really-move-window (window to-group) (unless (eq (window-group window) to-group) (hide-window window) ;; house keeping (setf (group-windows (window-group window)) (remove window (group-windows (window-group window)))) (group-delete-window (window-group window) window) (setf (window-group window) to-group (window-number window) (find-free-window-number to-group)) (push window (group-windows to-group)) (xlib:change-property (window-xwin window) :_NET_WM_DESKTOP (list (netwm-group-id to-group)) :cardinal 32) (group-add-window to-group window)))) ;; When a modal window is moved, all the windows it shadows must be moved ;; as well. When a shadowed window is moved, the modal shadowing it must ;; be moved. (cond ((window-modal-p window) (mapc (lambda (w) (really-move-window w to-group)) (append (list window) (shadows-of window)))) ((modals-of window) (mapc (lambda (w) (move-window-to-group w to-group)) (modals-of window))) (t (really-move-window window to-group))))) (defun next-group (current &optional (groups (non-hidden-groups (screen-groups (group-screen current))))) "Return the group following @var{current} in @var{groups}. If none are found return @code{NIL}." (let* ((matches (member current groups)) (next-group (if (null (cdr matches)) ;; If the last one in the list is current, then ;; use the first one. (car groups) ;; Otherwise, use the next one in the list. (cadr matches)))) (if (eq next-group current) nil next-group))) (defun merge-groups (from-group to-group) "Merge all windows in FROM-GROUP into TO-GROUP." (dolist (window (group-windows from-group)) (move-window-to-group window to-group))) (defun netwm-group (window &optional (screen (window-screen window))) "Get the window's desktop property and return a matching group, if there exists one." (let ((id (first (xlib:get-property (window-xwin window) :_NET_WM_DESKTOP)))) (when (and id (< id (length (screen-groups screen)))) (elt (sort-groups screen) id)))) (defun netwm-set-group (window) "Set the desktop property for the given window." (xlib:change-property (window-xwin window) :_NET_WM_DESKTOP (list (netwm-group-id (window-group window))) :cardinal 32)) (defun netwm-set-allowed-actions (window) (xlib:change-property (window-xwin window) :_NET_WM_ALLOWED_ACTIONS (mapcar (lambda (a) (xlib:intern-atom *display* a)) +netwm-allowed-actions+) :atom 32)) (defun netwm-update-groups (screen) "update all windows to reflect a change in the group list." ;; FIXME: This could be optimized only to update windows when there ;; is a need. (loop for i from 0 for group in (sort-groups screen) do (dolist (w (group-windows group)) (xlib:change-property (window-xwin w) :_NET_WM_DESKTOP (list i) :cardinal 32)))) (defun netwm-set-group-properties (screen) "Set NETWM properties regarding groups of SCREEN. Groups are known as \"virtual desktops\" in the NETWM standard." (let ((root (screen-root screen))) ;; _NET_NUMBER_OF_DESKTOPS (xlib:change-property root :_NET_NUMBER_OF_DESKTOPS (list (length (screen-groups screen))) :cardinal 32) (unless *initializing* ;; _NET_CURRENT_DESKTOP (xlib:change-property root :_NET_CURRENT_DESKTOP (list (netwm-group-id (screen-current-group screen))) :cardinal 32)) ;; _NET_DESKTOP_NAMES (xlib:change-property root :_NET_DESKTOP_NAMES (let ((names (mapcan (lambda (group) (list (string-to-utf8 (group-name group)) '(0))) (sort-groups screen)))) (apply #'concatenate 'list names)) :UTF8_STRING 8))) (defun kill-group (group to-group) (unless (eq group to-group) (let ((screen (group-screen group))) (merge-groups group to-group) (setf (screen-groups screen) (remove group (screen-groups screen))) (netwm-update-groups screen) (netwm-set-group-properties screen)))) (defun add-group (screen name &key background (type *default-group-type*)) "Create a new group in SCREEN with the supplied name. group names starting with a . are considered hidden groups. Hidden groups are skipped by gprev and gnext and do not show up in the group listings (unless *list-hidden-groups* is T). They also use negative numbers." (check-type screen screen) (check-type name string) (if (or (string= name "") (string= name ".")) (error "Groups must have a name.") (let ((ng (or (find-group screen name) (let ((ng (make-instance type :screen screen :number (if (char= (char name 0) #\.) (find-free-hidden-group-number screen) (find-free-group-number screen)) :name name))) (setf (screen-groups screen) (append (screen-groups screen) (list ng))) (netwm-set-group-properties screen) (netwm-update-groups screen) ng)))) (unless background (switch-to-group ng)) ng))) (defun find-group (screen name) "Return the group with the name, NAME. Or NIL if none exists." (find name (screen-groups screen) :key 'group-name :test 'string=)) ;;; Group commands ;; FIXME: groups are to screens exactly as windows are to ;; groups. There is a lot of duplicate code that could be globbed ;; together. (defun group-forward (current list) "Switch to the next non-hidden-group in the list, if one exists. Returns the new group." (let ((ng (next-group current (non-hidden-groups list)))) (when ng (switch-to-group ng) ng))) (defun group-forward-with-window (current list) "Switch to the next group in the list, if one exists, and moves the current window of the current group to the new one." (let ((next (group-forward current list)) (win (group-current-window current))) (when (and next win) (move-window-to-group win next) (really-raise-window win)))) (defcommand gnew (name) ((:string "Group Name: ")) "Create a new group with the specified name. The new group becomes the current group. If @var{name} begins with a dot (``.'') the group new group will be created in the hidden state. Hidden groups have group numbers less than one and are invisible to from gprev, gnext, and, optionally, groups and vgroups commands." (add-group (current-screen) name)) (defcommand gnewbg (name) ((:string "Group Name: ")) "Create a new group but do not switch to it." (add-group (current-screen) name :background t)) (defcommand gnext () () "Cycle to the next group in the group list." (group-forward (current-group) (sort-groups (current-screen)))) (defcommand gprev () () "Cycle to the previous group in the group list." (group-forward (current-group) (reverse (sort-groups (current-screen))))) (defcommand gnext-with-window () () "Cycle to the next group in the group list, taking the current window along." (group-forward-with-window (current-group) (sort-groups (current-screen)))) (defcommand gprev-with-window () () "Cycle to the previous group in the group list, taking the current window along." (group-forward-with-window (current-group) (reverse (sort-groups (current-screen))))) (defcommand gother () () "Go back to the last group." (let ((groups (screen-groups (current-screen)))) (when (> (length groups) 1) (switch-to-group (second groups))))) (defcommand grename (name) ((:string "New name for group: ")) "Rename the current group." (let ((group (current-group))) (cond ((find-group (current-screen) name) (message "^1*^BError: Name already exists")) ((or (zerop (length name)) (string= name ".")) (message "^1*^BError: empty name")) (t (cond ((and (char= (char name 0) #\.) ;change to hidden group (not (char= (char (group-name group) 0) #\.))) (setf (group-number group) (find-free-hidden-group-number (current-screen)))) ((and (not (char= (char name 0) #\.)) ;change from hidden group (char= (char (group-name group) 0) #\.)) (setf (group-number group) (find-free-group-number (current-screen))))) (setf (group-name group) name))))) (defun echo-groups (screen fmt &optional verbose (wfmt *window-format*)) "Print a list of the windows to the screen." (let* ((groups (sort-groups screen)) (names (mapcan (lambda (g) (list* (format-expand *group-formatters* fmt g) (when verbose (mapcar (lambda (w) (format-expand *window-formatters* (concatenate 'string " " wfmt) w)) (sort-windows g))))) (if *list-hidden-groups* groups (non-hidden-groups groups))))) (echo-string-list screen names))) (defcommand groups (&optional (fmt *group-format*)) (:rest) "Display the list of groups with their number and name. @var{*group-format*} controls the formatting. The optional argument @var{fmt} can be used to override the default group formatting." (echo-groups (current-screen) fmt)) (defcommand vgroups (&optional gfmt wfmt) (:string :rest) "Like @command{groups} but also display the windows in each group. The optional arguments @var{gfmt} and @var{wfmt} can be used to override the default group formatting and window formatting, respectively." (echo-groups (current-screen) (or gfmt *group-format*) t (or wfmt *window-format*))) (defcommand gselect (to-group) ((:group "Select Group: ")) "Select the first group that starts with @var{substring}. @var{substring} can also be a number, in which case @command{gselect} selects the group with that number." (when to-group (switch-to-group to-group))) (defcommand grouplist (&optional (fmt *group-format*)) (:rest) "Allow the user to select a group from a list, like windowlist but for groups" (let ((group (second (select-from-menu (current-screen) (mapcar (lambda (g) (list (format-expand *group-formatters* fmt g) g)) (screen-groups (current-screen))))))) (when group (switch-to-group group)))) (defcommand gmove (to-group) ((:group "To Group: ")) "Move the current window to the specified group." (when (and to-group (current-window)) (move-window-to-group (current-window) to-group))) (defcommand gmove-marked (to-group) ((:group "To Group: ")) "move the marked windows to the specified group." (when to-group (let ((group (current-group))) (dolist (i (marked-windows group)) (setf (window-marked i) nil) (move-window-to-group i to-group))))) (defcommand gkill () () "Kill the current group. All windows in the current group are migrated to the next group." (let* ((dead-group (current-group)) (groups (screen-groups (current-screen))) ;; If no "visible" group is found, try with all groups (to-group (or (next-group dead-group (non-hidden-groups groups)) (next-group dead-group groups)))) (if to-group (if (or (not %interactivep%) (not (group-windows dead-group)) (y-or-n-p (format nil "You are about to kill non-empty group \"^B^3*~a^n\" The windows will be moved to group \"^B^2*~a^n\" ^B^6*Confirm?^n " (group-name dead-group) (group-name to-group)))) (progn (switch-to-group to-group) (kill-group dead-group to-group) (message "Deleted")) (message "Canceled")) (message "There's only one group left")))) (defcommand gmerge (from) ((:group "From Group: ")) "Merge @var{from} into the current group. @var{from} is not deleted." (if (eq from (current-group)) (message "^B^3*Cannot merge group with itself!") (merge-groups from (current-group))))
19,952
Common Lisp
.lisp
415
39.436145
98
0.630285
blitz/stumpwm
27
1
2
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
a0697ec17edce928516b0b2701d1c889d571627a15e6ad77427e0cdb8fb13ad1
7,241
[ -1 ]
7,242
fdump.lisp
blitz_stumpwm/fdump.lisp
;; fdump.lisp -- Layout save and restore routines. ;; Copyright (C) 2007-2008 Jonathan Liles, Shawn Betts ;; ;; This file is part of stumpwm. ;; ;; stumpwm is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 2, or (at your option) ;; any later version. ;; stumpwm is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this software; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 59 Temple Place, Suite 330, ;; Boston, MA 02111-1307 USA ;; Commentary: ;; Code: (in-package #:stumpwm) (export '(ddump ddump-current ddump-screens dump-desktop-to-file dump-group-to-file dump-screen-to-file fdump fdump-current fdump-height fdump-number fdump-width fdump-windows fdump-x fdump-y gdump gdump-current gdump-name gdump-number gdump-tree place-existing-windows restore sdump sdump-current sdump-groups sdump-number)) (defstruct fdump number x y width height windows current) ;; group dump (defstruct gdump number name tree current) ;; screen dump (defstruct sdump number groups current) ;; desktop dump (defstruct ddump screens current) (defun dump-group (group &optional (window-dump-fn 'window-id)) (labels ((dump (f) (make-fdump :windows (mapcar window-dump-fn (frame-windows group f)) :current (and (frame-window f) (funcall window-dump-fn (frame-window f))) :number (frame-number f) :x (frame-x f) :y (frame-y f) :width (frame-width f) :height (frame-height f))) (copy (tree) (cond ((null tree) tree) ((typep tree 'frame) (dump tree)) (t (mapcar #'copy tree))))) (make-gdump ;; we only use the name and number for screen and desktop restores :number (group-number group) :name (group-name group) :tree (copy (tile-group-frame-tree group)) :current (frame-number (tile-group-current-frame group))))) (defun dump-screen (screen) (make-sdump :number (screen-id screen) :current (group-number (screen-current-group screen)) :groups (mapcar 'dump-group (sort-groups screen)))) (defun dump-desktop () (make-ddump :screens (mapcar 'dump-screen *screen-list*) :current (screen-id (current-screen)))) (defun dump-to-file (foo name) (with-open-file (fp name :direction :output :if-exists :supersede) (with-standard-io-syntax (let ((*package* (find-package :stumpwm)) (*print-pretty* t)) (prin1 foo fp))))) (defcommand dump-group-to-file (file) ((:rest "Dump To File: ")) "Dumps the frames of the current group of the current screen to the named file." (dump-to-file (dump-group (current-group)) file) (message "Group dumped")) (defcommand-alias dump-group dump-group-to-file) (defcommand dump-screen-to-file (file) ((:rest "Dump To File: ")) "Dumps the frames of all groups of the current screen to the named file" (dump-to-file (dump-screen (current-screen)) file) (message "Screen dumped")) (defcommand-alias dump-screen dump-screen-to-file) (defcommand dump-desktop-to-file (file) ((:rest "Dump To File: ")) "Dumps the frames of all groups of all screens to the named file" (dump-to-file (dump-desktop) file) (message "Desktop dumped")) (defcommand-alias dump-desktop dump-desktop-to-file) ;;; (defun read-dump-from-file (file) (with-open-file (fp file :direction :input) (with-standard-io-syntax (let ((*package* (find-package :stumpwm))) (read fp))))) (defun restore-group (group gdump &optional auto-populate (window-dump-fn 'window-id)) (let ((windows (group-windows group))) (labels ((give-frame-a-window (f) (unless (frame-window f) (setf (frame-window f) (find f windows :key 'window-frame)))) (restore (fd) (let ((f (make-frame :number (fdump-number fd) :x (fdump-x fd) :y (fdump-y fd) :width (fdump-width fd) :height (fdump-height fd)))) ;; import matching windows (if auto-populate (choose-new-frame-window f group) (progn (dolist (w windows) (when (equal (fdump-current fd) (funcall window-dump-fn w)) (setf (frame-window f) w)) (when (find (funcall window-dump-fn w) (fdump-windows fd) :test 'equal) (setf (window-frame w) f))))) (when (fdump-current fd) (give-frame-a-window f)) f)) (copy (tree) (cond ((null tree) tree) ((typep tree 'fdump) (restore tree)) (t (mapcar #'copy tree))))) ;; clear references to old frames (dolist (w windows) (setf (window-frame w) nil)) (setf (tile-group-frame-tree group) (copy (gdump-tree gdump)) (tile-group-current-frame group) (find (gdump-current gdump) (group-frames group) :key 'frame-number)) ;; give any windows still not in a frame a frame (dolist (w windows) (unless (window-frame w) (setf (window-frame w) (tile-group-current-frame group)))) ;; FIXME: if the current window was blank in the dump, this does not honour that. (give-frame-a-window (tile-group-current-frame group)) ;; raise the curtains (dolist (w windows) (if (eq (frame-window (window-frame w)) w) (unhide-window w) (hide-window w))) (sync-all-frame-windows group) (focus-frame group (tile-group-current-frame group))))) (defun restore-screen (screen sdump) "Restore all frames in all groups of given screen. Create groups if they don't already exist." (dolist (gdump (sdump-groups sdump)) (restore-group (or (find-group screen (gdump-name gdump)) ;; FIXME: if the group doesn't exist then ;; windows won't be migrated from existing ;; groups (add-group screen (gdump-name gdump))) gdump))) (defun restore-desktop (ddump) "Restore all frames, all groups, and all screens." (dolist (sdump (ddump-screens ddump)) (let ((screen (find (sdump-number sdump) *screen-list* :key 'screen-id :test '=))) (when screen (restore-screen screen sdump))))) (defcommand restore-from-file (file) ((:rest "Restore From File: ")) "Restores screen, groups, or frames from named file, depending on file's contents." (let ((dump (read-dump-from-file file))) (typecase dump (gdump (restore-group (current-group) dump) (message "Group restored.")) (sdump (restore-screen (current-screen) dump) (message "Screen restored.")) (ddump (restore-desktop dump) (message "Desktop restored.")) (t (message "Don't know how to restore ~a" dump))))) (defcommand-alias restore restore-from-file) (defcommand place-existing-windows () () "Re-arrange existing windows according to placement rules." (sync-window-placement))
8,029
Common Lisp
.lisp
197
31.563452
114
0.598821
blitz/stumpwm
27
1
2
GPL-2.0
9/19/2024, 11:26:28 AM (Europe/Amsterdam)
afc902c0ca01f7f99f35bb31840673ba4db9a87a16776e7623ab8a324f825ed9
7,242
[ -1 ]