+(define-condition scope-error (error)
+ ((code :initarg :code :reader scope-error-code)
+ (detail :initarg :detail :reader scope-error-detail))
+ (:report (lambda (c stream) (format stream "Scope ~A: ~A" (scope-error-code c) (scope-error-detail c)))))
+(defun scope-problem (code detail) (error 'scope-error :code code :detail detail))
+(defun proper-list-p (value)
+ ;; LIST-LENGTH detects cycles; dotted tails signal TYPE-ERROR. ANSI CL only.
+ (and (listp value) (handler-case (integerp (list-length value)) (type-error () nil))))
+(defun canonical-scope (map themes)
+ "Validate before mutation and copy a set of current same-map Topic references."
+ (unless (proper-list-p themes)
+ (scope-problem :invalid-scope "Supply a proper finite list of Topics."))
+ (remove-duplicates
+ (mapcar (lambda (theme)
+ (unless (typep theme 'topic) (scope-problem :invalid-theme "A theme must be a Topic object."))
+ (let ((current (live-topic theme)))
+ (unless (eq map (%topic-parent current))
+ (scope-problem :foreign-theme "Every theme must belong to the item's Topic Map."))
+ current)) themes)
+ :test #'eq :from-end t))
+(defun same-scope-p (a b)
+ ;; Storage is canonical and duplicate-free; equality has no sequence ordering.
+ (and (= (length a) (length b)) (every (lambda (theme) (member theme b :test #'eq)) a)))
+