/
engine.lisp
7165 lines (6385 loc) · 253 KB
/
engine.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; -*- Mode:Lisp -*-
;;; ***************************************************************************
;;; Engine for the Scone Knowledge Representation System
;;;
;;; Author & Maintainer: Scott E. Fahlman
;;; ***************************************************************************
;;; Copyright (C) 2003-2014, Carnegie Mellon University.
;;;
;;; The Scone software is made available to the public under the
;;; Apache 2.0 open source license. A copy of this license is
;;; distributed with the software. The license can also be found 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.
;;;
;;; Development since February 2013 has been supported in part by the
;;; U.S. Office of Naval Research under award number N000141310224.
;;;
;;; Development of Scone from January, 2012, through August 2013 was
;;; supported in part by the Intelligence Advanced Research Projects
;;; Activity (IARPA) via Department of Defense US Army Research
;;; Laboratory contract number W911NF-12-C-0020.
;;;
;;; Development of Scone from 2003 through 2008 was supported in part
;;; by the Defense Advanced Research Projects Agency (DARPA) under
;;; contract numbers NBCHD030010 and FA8750-07-D-0185.
;;;
;;; Additional support for Scone development has been provided by
;;; research grants from Cisco Systems Inc. and from Google Inc.
;;;
;;; The U.S. Government is authorized to reproduce and distribute
;;; reprints for Governmental purposes notwithstanding any copyright
;;; annotation thereon.
;;;
;;; Disclaimer: The views and conclusions contained herein are those
;;; of the authors and should not be interpreted as necessarily
;;; representing the official policies or endorsements, either
;;; expressed or implied, of IARPA, DoD/ARL, ONR, DARPA, the
;;; U.S. Government, or any of our other sponsors.
;;; ***************************************************************************
;;; GENERAL STYLE NOTE: We want the runtime marker-scanning operations
;;; to be as fast as possible and to be non-consing. So that code is
;;; optimized for performance first and for clarity second. Code that
;;; builds or modifies the KB, or that does higher-level setup for
;;; marker ops, can be slower, so I have tried to optimize that for
;;; clarity and ease of maintenance.
;;; ***************************************************************************
;;; TABLE OF CONTENTS:
;;; Global Variables, Constants, and Macros
;;; Variables That Control KB Input and Loading
;;; Variables That Control Printing and Naming
;;; Variables That Control Scans
;;; Element-Related Variables
;;; Variables Linking to Essential Scone Elements
;;; Variables and Macros Related to Marker Bits
;;; Define the Range of Legal Markers
;;; Marker Pairs
;;; Marker Predicates
;;; Marker Allocation
;;; Context and Activation Markers
;;; Marker Implementation
;;; Definitions Related to Flag Bits
;;; Variables Related to Element Names
;;; Scone Elements
;;; Definition of the SCONE Element Structure
;;; Low-Level Element Operations
;;; Element Properties
;;; Marker Operations
;;; Low-Level Marker Operations
;;; User-Level Marker Operations
;;; Accessing, Connecting, and Disconnecting Wires
;;; Definition of the SCONE Element Types
;;; Indv Nodes
;;; Primitive Nodes
;;; Type Nodes
;;; Map Nodes
;;; Is-A Links
;;; EQ Links
;;; Has Links
;;; Cancel Links
;;; Splits
;;; Relations
;;; Statements
;;; Creating Roles
;;; Printing Elements
;;; Adding Sets of Subtypes and Instances
;;; Defined Types
;;; Functions to Maintain a Well-Formed Network
;;; Marker Scans
;;; Is-A Hierarchy Scans
;;; Uppermost/Lowermost Scans
;;; Boolean Operations Over Marked Elements
;;; Marker Scans For Roles, Relations, and Statements
;;; Context Activation
;;; Queries and Predicates
;;; Mark, List, and Show Functions
;;; Basic List and Show Machinery
;;; Mark, List, Show Operations on the Is-A Hierarchy
;;; Miscellaneous Show Functions
;;; Operations on Roles, Relations, and Statements
;;; Access Functions
;;; Predicates
;;; Adding New Roles or Fillers
;;; List and Show Functions
;;; Cardinality Functions
;;; Internal Element Names and Namespace
;;; External Names for Elements
;;; Basic Machinery for English Names
;;; List and Show Functions on External Names
;;; Loading KB Files
;;; KB Checkpointing and Persistence
;;; Removing Elements from the KB
;;; ***************************************************************************
;;; HERE BEGINS THE ACTUAL CODE
;;; ***************************************************************************
;;; Define forms for section headings and other comments that will affect
;;; auto-generated documentation.
(defun section (&rest rest) (declare (ignore rest)))
(defun subsection (&rest rest) (declare (ignore rest)))
(defun subsubsection (&rest rest) (declare (ignore rest)))
(defun to-do (&rest rest) (declare (ignore rest)))
;;; ***************************************************************************
(section "Global Variables, Constants, and Macros"
"This section contains global variables, constants, and macros used
by the Scone engine.")
;;; The operations beyond this point must be as fast as possible.
(declaim (optimize (speed 3) (space 0) (safety 0)))
;;; ========================================================================
(subsection "Variables That Control KB Input and Loading")
;;; Default pathname for various load-store operations.
;;; NOTE: Customize this for your own site.
(defvar *default-kb-pathname*
(pathname "/afs/cs.cmu.edu/project/scone/current/kb/anonymous")
"Default location for text-format KB files.")
(defvar *load-kb-stream* nil
"Stream used for loading the current KB file.")
(defvar *loading-kb-file* nil
"If reading a KB file, this wil be set. Certain interactive dialogues
are suppressed, etc.")
(defvar *loaded-files* nil
"A list of files loaded in the current KB. The head of the list is
the file loaded most recently. Files go on this list when they
have been loaded completely.")
(defvar *last-loaded-elements* nil
"Every time we load a file, we push the value of the last loaded element
onto this list. The first element of the list is therefore the last
element we loaded. Any elements created after this in the element chain
must be newly created. The structure of this list parallels that of
*LOADED-FILES*: for each file name in one list, we have its last element
in the other list.")
(defvar *currently-loading-files* nil
"A list of the files currently being loaded. One file may load another,
and so on, so there many be a number of files on this list. The first
file on the list is the most recently started (i.e. the load that is
most deeply nested), while the last file is generally the one for which
the user called LOAD-KB.")
(defvar *last-bootstrap-element* nil
"Last element created by the BOOTSTRAP.LISP file.")
(defvar *verbose-loading* nil
"If set, loading files will produce printout showing progress.
Normally set by the :verbose keyword arg in various load
functions.")
(defvar *disambiguate-policy* :ask
"This global var controls what happens when an ambiguous element
name is encountered during input. :ERROR says to signal an error.
:ASK says to ask the user. :FIRST says just return the first
meaning.")
(defvar *defer-unknown-connections* nil
"Normally when we see a reference to an unknown element, an error is
signalled. If this variable is set, save the known connection on
the *deferred-connections* list and try to fix it later. This
allows for forward or circular references when these are
necessary.")
(defvar *deferred-connections* nil
"When loading a KB file, we may find references to elements not yet
loaded or defined. When we do, push a triplet onto this list and try to
create the connection later.")
;;; ========================================================================
(subsection "Variables That Control Load-Time Inference")
(defvar *no-kb-error-checking* nil
"If T, suppress most checking when creating KB elements. Use this only
when loading a file that you've loaded successfully before.")
(defvar *check-defined-types* t
"If T, check whether newly defined elements fit the definition of
some defined type. If NIL, don't bother.")
(defvar *create-undefined-elements* t
"If non-nil, when we encounter a reference to a node that is not yet
defined, we create a new type node with parent {thing} to represent
that element. If nil, signal an error in this case. Note that
*DEFER-UNKNOWN-CONNECTIONS* takes precedence.")
(defvar *deduce-owner-type-from-role* t
"If NIL, we signal an error if we call X-IS-THE-Y-OF-Z (or a variant)
and Z does not have or inherit a Y role. But if this switch is on,
we try to create an is-a link from Z to the owner of Y. If successful,
we create and return the link. If not, we return NIL, and the operation
will be aborted.")
(defvar *comment-on-element-creation* t
"When Scone creates a new element not specificially defined by the
user, usually because the element is referred to before it is
defined, comment on this via COMMENTARY.")
(defvar *comment-on-defined-types* nil
"When Scone detects that some element satisfies the definition of a
defined type and adds the element to that type, comment on this via
COMMENTARY.")
;;; ========================================================================
(subsection "Variables That Control Printing and Naming")
(defvar *print-namespace-in-elements* :maybe
"If T, always include the namespace, followed by a colon, in element
inames. This ensures that what we print can be read back in without
any namespace ambiguity. If NIL, do not include the namespace. This
is better for human readabilty. If :MAYBE, print the namespace if it
differs from the current *NAMESPACE*. This is usually safe.")
(defvar *generate-long-element-names* nil
"If T, generate long names for certain element types. For example,
a statement link will have an internal name that is an English
description of arguments and the relation. This is good for
development, but significantly increases the storage requirement for
large knowledge bases.")
(defvar *print-keylist* t
"If T, dumping an element pattern includes the list of keyword/value
pairs as part of the pattern. That is necessary if we want to read
that pattern back in, but set this to NIL for some human-readable
dumps.")
(defvar *show-ontology-counter* 0
"Counter used only by SHOW-ONTOLOGY.")
(declaim (type integer *show-ontology-counter*))
(defvar *show-ontology-indent* 3
"An integer, the number of spaces to indent each level in
SHOW-ONTOLOGY.")
(declaim (type integer *show-ontology-counter*))
(defvar *show-stream* *standard-output*
"Stream to which we print the output of SHOW functions. If NIL,
don't print these at all.")
(declaim (type stream *show-stream*))
(defvar *commentary-stream* *standard-output*
"Stream to which we print commentary about Scone's actions. For example,
if Scone makes a deduction and adds something to the KB as a result of
that, we note that here. If NIL, don't print this stuff at all.")
(declaim (type stream *commentary-stream*))
(defun commentary (&rest args)
"Just like FORMAT but with no STREAM arg. Printing goes to the
*COMMENTARY-STREAM*, if any. Each call to COMMENTARY is put on its
own line, so the caller doesn't ahve to do that."
(when *commentary-stream*
(format *commentary-stream* "~&")
(apply #'format (cons *commentary-stream* args))
(terpri *commentary-stream*)))
(defvar *kb-logging-stream* nil
"If non-nil, every KB alteration is reflected by an entry to this stream,
so that the resulting file can be read back in with RELOAD-KB.")
(declaim (type stream *logging-stream*))
(defun kb-log (&rest args)
"Syntax is just like FORMAT with no stream arg. If *KB-LOGGING-STREAM*
is non-null, execute the format call, writing the resulting string out
to the KB logging stream."
(when *kb-logging-stream*
(apply #'format *kb-logging-stream* args)
(force-output *kb-logging-stream*)))
;;; ========================================================================
(subsection "Variables Related to Element Names")
(defvar *namespace* nil
"The structure representing the current default namespace.")
(defvar *namespaces* (make-hash-table :test #'equal)
"A hash table containing an entry for each namespace currently loaded in
the KB. Associates a string (the name of the namespace) with a
namespace structure.")
(defun list-namespaces ()
"Return a list of all the Scone namespaces that are currently loaded."
(let ((namespace-list nil))
(maphash #'(lambda (key entry)
(declare (ignore entry))
(push key namespace-list))
*namespaces*)
namespace-list))
(defvar *number-hashtable*
(make-hash-table :test #'eql)
"A hashtable associating numbers (integer, ratio, or float) with existing
elements.")
(defvar *string-hashtable*
(Make-hash-table :test #'equal)
"A hashtable associating strings with existing string-nodes. Lookup is
case-sensitive")
(defvar *function-hashtable*
(make-hash-table :test #'eq)
"A hashtable associating Common Lisp functions with existing
function-nodes. This works only for named functions, as in #'foo. It
does not work for lambda expressions, even if they are equal.")
(defvar *struct-hashtable*
(make-hash-table :test #'eq)
"A hashtable associating Common Lisp desfstruct objects with existing
primitive elements.")
(defvar *iname-counter* 0
"Counter used by GEN-INAME to create unique internal names for elements.
Increment this counter each time it is used.")
(declaim (type fixnum *iname-counter*))
(defvar *iname-prefix* 0
"Increment this to start a whole new series of unique internal inames.")
(declaim (type fixnum *iname-prefix*))
;;; NOTE: English names are distinct from internal names. See the
;;; commentary at the start of the English Names section.
(defvar *english-dictionary*
(make-hash-table :test #'equal)
"Hash table associating English words and phrases (strings in Lisp) with
Scone elements. A given string may be associated with many elements, so
the hash-table value is a list if it exists at all. Each element in the
list is a pair (element . syntax-tag).")
(defvar *legal-syntax-tags*
'(:noun :adj :adj-noun :role :inverse-role :relation :inverse-relation
:verb :adverb)
"Each external name has an associated syntax-tag. The tags currently
defined are stored in this constant.")
;;; ========================================================================
(subsection "Variables That Control Scans")
(defvar *ignore-context* nil
"If T, marker-propagations pay no attention to whether or not the nodes and links
are in an active context. This variable is used for upscanning while
activating a context, and may also be useful finding whether some entity
exists in ANY context.")
(defvar *one-step* nil
"If T, marker propagations go only one level in the desired
direction. Used in functions such as MARK-PARENTS, where you don't
want the full transitive closure.")
(defvar *default-recursion-allowance* 2
"In functions such as MARK-REL, we must individually activate and
explore each description instance in which the source node plays a
role, and this process may recurse. This is the default allowance
for recursion depth that we will explore.")
;;; ========================================================================
(subsection "Element-Related Variables")
(defvar *n-elements* 0
"The number of elements currently in use in the KB.")
(declaim (type fixnum *n-elements*))
;;; There is a chain of pointers running through all the elements in the
;;; KB. This starts at *FIRST-ELEMENT*. Each element has a NEXT-ELEMENT
;;; slot pointing to the next element in the chain. We keep hold of
;;; *LAST-ELEMENT* so that we can extend the chain at the end.
(defvar *first-element* nil
"First element in the chain of all elements in the KB.")
(defvar *last-element* nil
"Last element in the chain of all elements in the KB.")
;;; ========================================================================
(subsection "Variables Linking to Essential Scone Elements")
;;; These variables hold a few special KB elements referred to by
;;; the engine code. These are created in the BOOTSTRAP file and the
;;; elements, once created, are saved into these variables.
;;; We can't just refer to these elements by their curly-brace names
;;; because the curly braces may confuse the compiler.
;;; Nodes of general importance.
(defvar *thing* nil)
(defvar *undefined-thing*)
(defvar *universal* nil)
(defvar *general* nil)
(defvar *set* nil)
(defvar *empty-set* nil)
(defvar *non-empty-set* nil)
(defvar *cardinality* nil)
(defvar *zero* nil)
(defvar *one* nil)
(defvar *two* nil)
(defvar *event* nil)
(defvar *action* nil)
(defvar *potential-agent* nil)
(defvar *action-agent* nil)
(defvar *action-object* nil)
(defvar *action-recipient* nil)
;;; Parent nodes for various built-in Scone element types.
(defvar *number* nil)
(defvar *integer* nil)
(defvar *ratio* nil)
(defvar *float* nil)
(defvar *string* nil)
(defvar *function* nil)
(defvar *struct* nil)
(defvar *relation* nil)
(defvar *link* nil)
(defvar *is-a-link* nil)
(defvar *is-not-a-link* nil)
(defvar *eq-link* nil)
(defvar *not-eq-link* nil)
(defvar *cancel-link* nil)
(defvar *has-link* nil)
(defvar *has-no-link* nil)
(defvar *split* nil)
(defvar *complete-split* nil)
(defvar *statement-link* nil)
(defvar *not-statement-link* nil)
;;; ========================================================================
(section "Variables and Macros Related to Marker Bits")
;;; These macros are hacked for maximum spped in Common Lisp. These
;;; have lots of declarations to ensure that array access and other
;;; ops will be coded inline.
;;; The Scone system supports a fixed number of markers, designated by
;;; an integers greater than or equal to zero and less than N-MARKERS.
;;; ---------------------------------------------------------------------
(subsubsection "Define the Range of Legal Markers")
;;; Sense how many bits we have to work with in a fixnum in the Lisp
;;; system we are using. Use that as the maximum number of marker
;;; bits. This varies from Lisp to Lisp, and of course will be large
;;; in a 64-bit Common Lisp.
(eval-when (:execute :load-toplevel :compile-toplevel)
(defconstant max-marker-bits (- (logcount most-positive-fixnum) 1)
"This is the maximum number of marker bits the Lisp implementation
can support.")
(defconstant desired-marker-bits 24
"This is the maximum number of marker bits we want, if the Lisp
implementation allows this many. The space allocated for each Scone
element grows by one pointer-word for each marker, so you may want
to reduce this if the core image is too large.")
(defconstant n-markers
(min max-marker-bits
desired-marker-bits)
"The maximum number of marker bits allowed in this Scone engine.
This number gets compiled in, so it cannot be changed
dynamically.")
(defconstant n-marker-pairs (floor n-markers 2)
"The maximum number of marker pairs.")
(defconstant all-markers-mask (- (expt 2 n-markers) 1)
"Bit mask that is 1 for each legal marker. Must be a fixnum.")
(declaim (type fixnum max-marker-bits desired-marker-bits n-markers
n-marker-pairs all-markers-mask))
) ;; End EVAL-WHEN.
(defmacro legal-marker? (m)
`(typep ,m '(integer 0 (,n-markers))))
;;; Marker to marker-bit conversion is a simple table lookup.
(eval-when (:execute :load-toplevel :compile-toplevel)
(defvar *marker-bits*
(make-array n-markers))
(proclaim `(type (simple-vector ,n-markers)
*marker-bits*))
(dotimes (i n-markers)
(setf (aref *marker-bits* i)
(ash 1 i)))
) ;; End EVAL-WHEN.
(defmacro marker-bit (m)
"Get the marker bit associated with marker M."
`(the fixnum (aref *marker-bits* ,m)))
(defmacro check-legal-marker (m)
"In interactive routines, check if M is a legal marker. If not, signal
an error."
`(unless (legal-marker? ,m)
(error "~S is not a legal marker." ,m)))
;;; ---------------------------------------------------------------------
(subsubsection "Marker Pairs")
;;; Markers are allocated in pairs. For each marker we allocate, there is
;;; a corresponding cancel-marker. So we divide the space of markers in
;;; half, rounding down. Indices in the lower half designate markers (or
;;; marker pairs) available to the user, while indices in the upper half
;;; designate the corresponding cancel-markers.
(defmacro get-cancel-marker (m)
"Get the cancel-marker corresponding to marker M."
`(the fixnum (+ (the fixnum ,m)
(the fixnum n-marker-pairs))))
(defmacro legal-marker-pair? (m)
`(typep ,m '(integer 0 (,n-marker-pairs))))
(defmacro check-legal-marker-pair (m)
"In interactive routines, check if M is a legal user marker. If not,
signal an error."
`(unless (legal-marker-pair? ,m)
(error "~S is not a legal user marker." ,m)))
;;; ---------------------------------------------------------------------
(subsubsection "Marker Predicates")
;; These are fast internal macros that do no checking. Not intended for
;; use at user-level.
(defmacro fast-marker-on? (e m)
"Check whether element E has marker M turned on."
`(/= 0 (the fixnum (logand (the fixnum (bits ,e))
(the fixnum (marker-bit ,m))))))
(defmacro fast-marker-off? (e m)
"Check whether element E has marker M turned off."
`(= 0 (the fixnum (logand (the fixnum (bits ,e))
(the fixnum (marker-bit ,m))))))
(defmacro all-bits-on? (bits mask)
"Predicate tests whether all the one-bits in MASK are on in BITS.
Assume that both BITS and MASK are positive fixnums with fewer than
N-MARKERS potentially on."
`(= 0 (the fixnum
(logand (the fixnum ,mask)
(the (unsigned-byte ,n-markers)
(logxor (the fixnum ,bits)
(the fixnum all-markers-mask)))))))
(defmacro any-bits-on? (bits mask)
"Predicate tests whether any of the bits in MASK are on in fixnum BITS."
`(/= 0 (the fixnum (logand (the fixnum ,bits)
(the fixnum ,mask)))))
(defmacro all-bits-off? (bits mask)
"Predicate tests whether all the bits in MASK are off in fixnum BITS."
`(= 0 (the fixnum (logand (the fixnum ,bits)
(the fixnum ,mask)))))
;;; ---------------------------------------------------------------------
(subsubsection "Marker Allocation")
;;; NOTE: Don't just grab a random marker and try to use it. Call
;;; GET-MARKER and use whatever marker it gives you. Keep it forever
;;; or use FREE-MARKER to return it when you're done. Better yet, use
;;; WITH-MARKERS. If you use random markers without telling the
;;; allocation machinery, you'll confuse things and may end up with
;;; some very subtle bugs.
;;; An array with a boolean value for each general marker pair. T means
;;; the marker is available for allocation. NIL means the marker is in
;;; use.
(defvar *available-markers*
(make-array n-marker-pairs :initial-element t))
(eval-when (:execute :load-toplevel :compile-toplevel)
(proclaim `(type (simple-array t (,n-marker-pairs))
*available-markers*)))
(defvar *n-available-markers* n-marker-pairs
"The number of markers currently available for allocation.")
(declaim (type fixnum *n-available-markers*))
(defvar *locked-markers*
(make-array n-marker-pairs :initial-element nil)
"A vector with an entry for each marker. If the entry is T, this
marker is locked and cannot be released by FREE-MARKER.")
(eval-when (:execute :load-toplevel :compile-toplevel)
(proclaim `(type (simple-array t (,n-marker-pairs))
*locked-markers*)))
(defun lock-marker (m)
"A locked marker will not be released by FREE-MARKER."
(setf (aref *locked-markers* m) t))
(defun unlock-marker (m)
"Release the lock on marker M."
(setf (aref *locked-markers* m) nil))
(defun locked-marker? (m)
"Predicate to determine if marker M is locked."
(svref *locked-markers* m))
(defmacro available-marker? (m)
"Predicate to check wether marker M is currently available."
`(and (legal-marker-pair? ,m)
(aref *available-markers* ,m)))
(defun get-marker ()
"Allocate an available marker, returning the index. If no available
markers remain, return NIL."
(when (> *n-available-markers* 0)
;; Scan all the markers to find an available one.
(dotimes (i n-marker-pairs)
(when (available-marker? i)
;; Marker I is the winner.
(setf (svref *available-markers* i) nil)
(decf *n-available-markers*)
(return-from get-marker i)))))
(defun free-marker (m)
"Return Marker M to the pool of available markers and clear the marker.
If the marker is already available or is locked, do nothing."
(check-legal-marker-pair m)
(unless (or (available-marker? m) (locked-marker? m))
(clear-marker-pair m)
(setf (aref *available-markers* m) t)
(incf *n-available-markers*)))
(defun free-markers ()
"Return all markers to the free pool and clear them."
(dotimes (i n-marker-pairs)
(free-marker i)))
(defmacro with-markers ((&rest marker-vars)
body-form
&optional
(fail-form
'(commentary "Insufficient markers available.")))
"MARKER-VARS is a list of variables that are locally bound, each getting
the index of a freshly allocated marker. We then execute the the BODY-FORM,
returning whatever value or values the last form returns. But
before leaving this form, we de-allocate and clear the markers.
If there are not enough markers available to fill all the MARKER-VARS,
we don't allocate any new markers. Instead we executre the FAIL-FORM
and return what it returns."
(let ((n-markers-needed (length marker-vars))
(bind-list nil)
(free-list)
(declare-list))
;; Prepare a let-list, a list of free-marker forms, and a
;; declare list.
(dolist (mv marker-vars)
(push `(,mv (get-marker)) bind-list)
(push `(free-marker ,mv) free-list)
(push mv declare-list))
;; Allocate the markers in the expected order.
(setq bind-list (nreverse bind-list))
(setq declare-list (nreverse declare-list))
;; Now construct the macro-expansion. If we have enough markers,
;; bind each variable to a freshly-allocated marker, then execute
;; the body-form. Free the markers on the way out, even if the
;; user throws.
`(if (>= *n-available-markers* ,n-markers-needed)
(let ,bind-list
(declare (fixnum ,@declare-list))
(unwind-protect
,body-form
(progn ,@free-list)))
,fail-form)))
;;; ---------------------------------------------------------------------
(subsubsection "Context and Activation Markers")
;;; The variable *CONTEXT* holds the currently-active context node. The
;;; *CONTEXT-MARKER* is placed on this node and upscanned whenever we change
;;; *CONTEXT*.
;;; The activation marker is placed on all nodes and links in the active
;;; context by following chains of context-wires. This use of an activation
;;; marker makes IN-CONTEXT slower, but makes the various scans faster.
;;; *CONTEXT-MARKER* is initially set to -1 to indicate that no marker has
;;; yet been assigned.
(defvar *context* nil
"The element representing the current context.")
;;; *CONTEXT-MARKER* marks the current context and all its superiors.
(defvar *context-marker* -1
"Marker permanently assigned to mark the current *CONTEXT* node and
its superiors.")
(declaim (type fixnum *context-marker*))
(defvar *context-mask* 0
"Bit mask for *CONTEXT-MARKER*.")
(declaim (type fixnum *context-mask*))
(defvar *context-cancel-marker* 0
"Cancellation marker corresponding to *CONTEXT-MARKER*.")
(declaim (type fixnum *context-cancel-marker*))
(defvar *context-cancel-mask* 0
"Bit mask for *CONTEXT-CANCEL-MARKER*.")
(declaim (type fixnum *context-cancel-mask*))
;;; ACTIVATION-MARKER marks the set of elements in the current context.
(defvar *activation-marker* 0
"Marker permanently assigned to mark every element active or
present in the current context.")
(declaim (type fixnum *activation-marker*))
(defvar *activation-mask* 0
"Bit mask for *ACTIVATION-MARKER*.")
(declaim (type fixnum *activation-mask*))
;;; NOTE: I'm not sure if we need a cancel-marker for activation, or
;;; if we can always use *context-cancel-marker*. Create it just in
;;; case we need it, since this marker would be wasted anyway.
(defvar *activation-cancel-marker* 0
"Cancellation marker corresponding to *ACTIVATION-MARKER*.")
(declaim (type fixnum *activation-cancel-marker*))
(defvar *activation-cancel-mask* 0
"Bit mask for *CONTEXT-CANCEL-MARKER*.")
(declaim (type fixnum *activation-cancel-mask*))
(defun context-marker-setup ()
"Set up the context and activation markers. These normally are
kept constant for the lifetime of a Scone process."
(if (eql *context-marker* -1)
(progn
(setq *context-marker* (get-marker))
(setq *activation-marker* (get-marker))
(commentary
"Assigning ~D as context marker, ~D as activation marker."
*context-marker*
*activation-marker*)
(setq *context-mask* (marker-bit *context-marker*))
(setq *activation-mask* (marker-bit *activation-marker*))
(setq *context-cancel-marker* (get-cancel-marker *context-marker*))
(setq *activation-cancel-marker* (get-cancel-marker *activation-marker*))
(setq *context-cancel-mask* (marker-bit *context-cancel-marker*))
(setq *activation-cancel-mask* (marker-bit *activation-cancel-marker*))
(lock-marker *context-marker*)
(lock-marker *activation-marker*))
(commentary "Ignoring attempt to re-initialize context marker.")))
;;; ---------------------------------------------------------------------
(subsubsection "Marker Implementation")
;;; For each marker, there is a doubly-linked list running through all the
;;; elements.
;;; NOTE: This is a tradeoff of space for time. Many scans want to do some
;;; operation for "all elements with marker N". We want to avoid scanning
;;; ALL elements, so we need a list for each marker. But we also want to
;;; avoid allocating list cells that we will have to GC later. This means
;;; that every element has space pre-allocated for all these chains. Store
;;; the start and end of the chain here, along with the count of marked
;;; elements.
(defvar *first-marked-element*
(make-array n-markers :initial-element nil)
"A vector with an entry for each marker. This is the first element in
the chain of elements having that mark.")
(eval-when (:execute :load-toplevel :compile-toplevel)
(proclaim `(type (simple-vector ,n-markers) *first-marked-element*)))
(defvar *last-marked-element*
(make-array n-markers :initial-element nil)
"A vector with an entry for each marker. This is the last element in the
chain of elements having that mark.")
(eval-when (:execute :load-toplevel :compile-toplevel)
(proclaim `(type (simple-vector ,n-markers) *last-marked-element*)))
(defvar *n-marked-elements*
(make-array n-markers :element-type 'fixnum :initial-element 0))
(eval-when (:execute :load-toplevel :compile-toplevel)
(proclaim `(type (simple-array fixnum (,n-markers)) *n-marked-elements*)))
(defmacro fast-marker-count (m)
"Return the number of elements marked with marker M."
`(aref (the (simple-array fixnum (,n-markers))
*n-marked-elements*)
,m))
(defmacro inc-marker-count (m)
"Increment the number of elements marked with marker M."
`(incf (the fixnum (aref (the (simple-array fixnum (,n-markers))
*n-marked-elements*)
,m))))
(defmacro dec-marker-count (m)
"Decrement the number of elements marked with marker M."
`(decf (the fixnum (aref (the (simple-array fixnum (,n-markers))
*n-marked-elements*)
,m))))
(defmacro zero-marker-count (m)
"Set to zero the number of elements marked with marker M."
`(setf (aref (the (simple-array fixnum (,n-markers))
*n-marked-elements*)
,m)
0))
(defmacro do-marked ((var
m
&optional
after)
&body body)
"This macro iterates over the set of elements with marker M. Each
element in turn is bound to VAR and then the body is executed, returning
NIL. If AFTER is present and non-nil, it should evaluate into an
element marked with M. Only iterate over elements after this one in the
chain of M-marked elements. NOTE: It is OK to mark new elements with M
in the body of this loop, but don't unmark any elements."
`(do ((,var
,(if after
`(if ,after
(svref (next-marked-element ,after) ,m)
(svref *first-marked-element* ,m))
`(svref *first-marked-element* ,m))
(svref (next-marked-element ,var) ,m)))
((null ,var))
,@body))
;;; ========================================================================
(subsection "Definitions Related to Flag Bits")
;;; A flag is like a permanent marker-bit on an element. Each
;;; flag-bit is assigned to some system-defined purpose -- these are
;;; not meant to be user-defined.
;;; There is a word full of flag-bits in each element, but we do not
;;; maintain a linked list of elements with a given flag. This is a
;;; difference between markers and flags.
;;; One important use of flag bits is to record the type of each
;;; element in a way that can quickly be tested by boolean-mask
;;; operations.
;;; IMPLEMENTATION NOTE: The current version of Scone was developed
;;; for a 32-bit implementation of Common Lisp, so flags and markers
;;; are kept in two separate words at the start of each element. Now
;;; that we have 64-bit machines running 64-bit Common Lisp
;;; impelementnations we can speed up the system by keeping all these
;;; bits in a single marker/flag word, and doing Boolean checks over
;;; both at the same time. That's on the to-do list, but it's tricky
;;; to build this in such a way that the system runs either on 32-bit
;;; or 64-bit implementations. So we may either burn our bridges and
;;; go to 64-bit always, or maintain two distinct Scone versions.
(defmacro new-flags (start &rest names)
"Allocate a number of flags in order, starting with START. We cannot
have more flags than MAX-MARKER-BITS."
(declare (list names))
(let ((list nil))
(do ((n start (1+ n))
(l names (cdr l)))
((null l)
(cons 'progn (nreverse list)))
(declare (fixnum n))
(when (> n max-marker-bits)
(error "Cannot define more than ~D flags in this Lisp."
n-markers))
(push `(defconstant ,(car l)
(ash 1 (the (unsigned-byte ,n-markers) ,n)))
list))))
;;; Simple flag macros and functions.
(defmacro fast-flag-on? (e f)
"Check whether element E has flag F turned on."
`(/= 0 (logand (flags ,e) ,f)))
(defmacro fast-flag-off? (e f)
"Check whether element E has flag F turned off."
`(= 0 (logand (flags ,e) ,f)))
;;; Define flags for the basic element types and modifiers.
;;; NOTE: The worst-case Lisp that we know about and care about
;;; allows 22 flag bits, so try to stay under that limit.
(new-flags
0
;; Basic families.
node-flag ; An indv or type node.
link-flag ; Any kind of link.
split-flag ; A split-element, maybe complete.
relation-flag ; A relation-element.
;; Basic modifiers.
kill-flag) ; Renders the element inoperative.
;; Node flags
(new-flags
5
indv-flag ; Any kind of individual node.
type-flag ; A type-node.
map-flag ; A MAP-node, may be either INDV or TYPE.
role-flag ; Node was defined as a role node.
primitive-flag ; An indv representing a Lisp object.
proper-flag ; A proper individual, not generic.
defined-flag) ; This node has a definition.
;; Subtypes and modfiers of a LINK or RELATION.
(new-flags
5
is-a-flag ; An IS-A link.
eq-flag ; An EQ link.
has-flag ; A HAS-link.
cancel-flag ; A CANCEL link.
statement-flag ; A link instantiating a user-defined relation.
not-flag ; Set on a link to indicate negation.
true-flag ; Set on a link tht is not negated.
up-flag ; Any link that markers cross A to B in an upscan.
h-flag ; A relation or statement.
mod-flag ; On an IS-A link, creates a derived
; IS-A link.
transitive-flag ; A transitive relation.
symmetric-flag) ; A smmetric relation.
;; Subtypes and modifiers of a SPLIT.
(new-flags
5
complete-split-flag) ; A complete split.
;;; The UP-MASK designates any link that propagates markers A-to-B in an UPSCAN.
(defconstant up-mask (logior link-flag true-flag up-flag))
;;; The CANCEL-UP-MASK designates any link that propagates cancel markers
;;; A-to-B in an UPSCAN.
(defconstant cancel-up-mask (logior link-flag not-flag up-flag))
;;; The H-MASK designates a STATEMENT or RELATION -- basically, any link
;;; type that propagates markers from the A, B, or C node to the
;;; corresponding node of the parent -- an H-shaped inheritance pattern.
(defconstant h-mask h-flag)
;;; ***************************************************************************
(section "Scone Elements")
;;; ***************************************************************************
;;; An element is the basic unit of knowledge in the Scone system. An
;;; element is either a NODE, representing some individual, type, or
;;; entity, a LINK, representing the statement of a relation between two or
;;; more entities. But a link has a built-in "handle node" representing