结构和 CLOS 实例是否检查槽类型都未定义。
许多实现都会为结构做这件事 - 但不是全部。
很少有实现会为 CLOS 实例做到这一点 - 例如,Clozure CL 实际上就是这样做的。
SBCL 还可以检查 CLOS 插槽类型 - 当安全性很高时:
* (declaim (optimize safety))
NIL
* (progn
(defclass foo-class ()
((bar :initarg :bar
:type list)))
(make-instance 'foo-class :bar 'some-symb))
debugger invoked on a TYPE-ERROR: The value SOME-SYMB is not of type LIST.
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [ABORT] Exit debugger, returning to top level.
((SB-PCL::SLOT-TYPECHECK LIST) SOME-SYMB)
0]
不然怎么办?
这是一种高级主题,可能需要一些 CLOS 元对象协议黑客技术。两种变体:
对于后者,这里是自建的SBCL版本,用于检查写入槽的类型:
首先是元类:
; first a metaclass for classes which checks slot writes
(defclass checked-class (standard-class)
())
; this is a MOP method, probably use CLOSER-MOP for a portable version
(defmethod sb-mop:validate-superclass
((class checked-class)
(superclass standard-class))
t)
现在我们检查该元类的所有插槽写入:
; this is a MOP method, probably use CLOSER-MOP for a portable version
(defmethod (setf sb-mop:slot-value-using-class) :before
(new-value (class checked-class) object slot)
(assert (typep new-value (sb-mop:slot-definition-type slot))
()
"new value ~a is not of type ~a in object ~a slot ~a"
new-value (sb-mop:slot-definition-type slot) object slot))
我们的示例类使用该元类:
(defclass foo-class ()
((bar :initarg :bar :type list))
(:metaclass checked-class))
使用它:
* (make-instance 'foo-class :bar 42)
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {10005605B3}>:
new value 42 is not of type LIST
in object #<FOO-CLASS {1004883143}>
slot #<STANDARD-EFFECTIVE-SLOT-DEFINITION COMMON-LISP-USER::BAR>
Type HELP for debugger help, or (SB-EXT:EXIT) to exit from SBCL.
restarts (invokable by number or by possibly-abbreviated name):
0: [CONTINUE] Retry assertion.
1: [ABORT ] Exit debugger, returning to top level.