Compare commits

..
4 Commits
Author SHA1 Message Date
Hilton Chain ed43a49877 services: jellyfin: Use the contract system. 2026-09-13 17:41:06 +08:00
Hilton Chain c8625f6a8c utils: records: Integrate the contract system. 2026-09-13 17:41:06 +08:00
Hilton Chain a88ac359a0 utils: Add a Racket-like contract system. 2026-09-13 17:41:06 +08:00
Hilton Chain f34040153c utils: Import (guix records).
* modules/rosenthal/utils/records.scm (define-record-type/dolly)
(this-record, match-record/dolly, match-record-lambda/dolly): New
macros.
* .dir-locals.el (scheme-mode): Update.
2026-09-13 17:41:01 +08:00
7 changed files with 1759 additions and 7 deletions

No files matched your search

+3
View File
@@ -42,6 +42,9 @@
. .
((geiser-repl-add-project-paths . ("modules")) ((geiser-repl-add-project-paths . ("modules"))
(eval . (put 'match-record/dolly 'scheme-indent-function 3))
(eval . (put 'match-record-lambda/dolly 'scheme-indent-function 2))
(eval . (put 'computed-substitution-with-inputs 'scheme-indent-function 1)) (eval . (put 'computed-substitution-with-inputs 'scheme-indent-function 1))
(eval . (put 'hidden-desktop-entry 'scheme-indent-function 1)) (eval . (put 'hidden-desktop-entry 'scheme-indent-function 1))
(eval . (put 'modify-services/by-name 'scheme-indent-function 1)) (eval . (put 'modify-services/by-name 'scheme-indent-function 1))
+9 -7
View File
@@ -7,8 +7,10 @@
#:use-module (guix modules) #:use-module (guix modules)
#:use-module (guix packages) #:use-module (guix packages)
#:use-module (guix records) #:use-module (guix records)
#:use-module (rosenthal utils contract combinators)
#:use-module (rosenthal utils file) #:use-module (rosenthal utils file)
#:use-module (rosenthal utils predicates) #:use-module (rosenthal utils predicates)
#:use-module (rosenthal utils records)
;; Guix origin methods ;; Guix origin methods
#:use-module (guix download) #:use-module (guix download)
;; Guix System ;; Guix System
@@ -392,7 +394,7 @@ test its configuration file."))
;;; Jellyfin media system (Native, currently written for the Nix package). ;;; Jellyfin media system (Native, currently written for the Nix package).
;;; ;;;
(define-record-type* <jellyfin-configuration> (define-record-type/dolly <jellyfin-configuration>
jellyfin-configuration jellyfin-configuration
make-jellyfin-configuration make-jellyfin-configuration
jellyfin-configuration? jellyfin-configuration?
@@ -462,8 +464,8 @@ test its configuration file."))
(documentation (documentation
"Extra command-line options."))) "Extra command-line options.")))
(define (jellyfin-account-service config) (define jellyfin-account-service
(match-record config <jellyfin-configuration> (match-record-lambda/dolly <jellyfin-configuration>
(data-directory user group) (data-directory user group)
(list (user-group (list (user-group
(name "jellyfin") (name "jellyfin")
@@ -478,8 +480,8 @@ test its configuration file."))
(shell (file-append shadow "/sbin/nologin")) (shell (file-append shadow "/sbin/nologin"))
(system? #t))))) (system? #t)))))
(define (jellyfin-activation-service config) (define jellyfin-activation-service
(match-record config <jellyfin-configuration> (match-record-lambda/dolly <jellyfin-configuration>
(data-directory config-directory cache-directory log-directory) (data-directory config-directory cache-directory log-directory)
#~(let ((owner (getpwnam "jellyfin"))) #~(let ((owner (getpwnam "jellyfin")))
(for-each (lambda (dir) (for-each (lambda (dir)
@@ -489,8 +491,8 @@ test its configuration file."))
cache-directory cache-directory
log-directory))))) log-directory)))))
(define (jellyfin-shepherd-service config) (define jellyfin-shepherd-service
(match-record config <jellyfin-configuration> (match-record-lambda/dolly <jellyfin-configuration>
(jellyfin (jellyfin
data-directory config-directory cache-directory log-directory data-directory config-directory cache-directory log-directory
shepherd-requirement extra-options) shepherd-requirement extra-options)
+97
View File
@@ -0,0 +1,97 @@
;;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Copyright © 2026 Hilton Chain <hako@ultrarare.space>
(define-module (rosenthal utils contract)
#:use-module (ice-9 match)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (guix colors)
#:use-module (guix diagnostics)
#:use-module (rosenthal utils contract impl)
#:use-module (rosenthal utils contract blame)
#:use-module (rosenthal utils contract combinators)
#:export (apply-contract/guix-record-field
contract
define/contract))
#|
Helpers to attach contracts to values and functions.
See (rosenthal utils contract impl) for more information.
|#
(define (src->location-str src)
(match src
((_ _ _)
(let ((location (source-properties->location src)))
(if (supports-hyperlinks? (guix-warning-port))
(location->hyperlink location)
(location->string location))))
(_ #f)))
(define* (apply-contract contract value positive negative name location
#:key context-limit)
(let* ((ctc (->contract contract))
(ctc-name (contract-name ctc))
(checker (contract-checker ctc))
(blame
(make-blame*
#:source location
#:value name
#:build-name (lambda () ctc-name)
#:positive positive
#:negative #f
#:original? #t
#:context-limit context-limit)))
(cond
(checker
(if (checker value)
value
(raise-blame-error
blame #:missing-party negative
`(expected: "~a" got: "~s") ctc-name value)))
(else
(((contract-enforcer ctc) blame) value negative)))))
(define-syntax apply-contract/guix-record-field
(lambda (stx)
(syntax-case stx ()
((_ ctc value record-name field-name)
(with-syntax ((field-name #'(format #f "(field: ~a)" field-name))
(location (src->location-str (syntax-source stx))))
;; Use field-name for both positive and negative parties, to ensure the
;; error message is always "contract violation".
#'(apply-contract ctc value field-name field-name record-name location))))))
(define-syntax contract
(lambda (stx)
(syntax-case stx ()
((_ ctc value positive negative name location #:context-limit context-limit)
#'(apply-contract ctc value positive negative name location #:context-limit context-limit))
((_ ctc value positive negative name location)
#'(contract ctc value positive negative name location #:context-limit #f))
((_ ctc value positive negative name)
(with-syntax ((location (src->location-str (syntax-source stx))))
#'(contract ctc value positive negative name location)))
((_ ctc value positive negative)
#'(contract ctc value positive negative positive))
((_ ctc value)
#'(contract ctc value 'unknown-definition 'caller)))))
(define-syntax define/contract
(lambda (stx)
(syntax-case stx ()
((_ (name . args) ctc body ...)
(if (null? #'(body ...))
(syntax-violation 'define/contract "missing body" stx)
(with-syntax ((value #'(lambda* args body ...)))
#'(define name
(contract ctc value '(definition: name) 'caller 'name)))))
((_ name ctc body ...)
(if (null? #'(body ...))
(syntax-violation 'define/contract "missing body" stx)
(with-syntax ((value #'(begin body ...)))
#'(define name
(contract ctc value '(definition: name) 'caller 'name))))))))
+703
View File
@@ -0,0 +1,703 @@
;;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Copyright © 2026 Hilton Chain <hako@ultrarare.space>
;;; https://github.com/racket/racket/blob/master/racket/collects/racket/contract/private/blame.rkt
;;; Copyright © 2010-2019, 2021, 2024 Racket authors
;;; Ported from Racket, original copyright notice below:
;;;
;;; Permission is hereby granted, free of charge, to any person obtaining a copy
;;; of this software and associated documentation files (the "Software"), to
;;; deal in the Software without restriction, including without limitation the
;;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;;; sell copies of the Software, and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be included in
;;; all copies or substantial portions of the Software.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;;; IN THE SOFTWARE.
(define-module (rosenthal utils contract blame)
#:use-module (ice-9 format)
#:use-module (ice-9 match)
#:use-module (ice-9 regex)
#:use-module (ice-9 string-fun)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (srfi srfi-71)
#:export (blame?
make-blame
blame-source
blame-positive
blame-negative
blame-contract
blame-value
blame-original?
blame-swapped?
blame-swap
blame-replace-negative ;used for indy blame
blame-replaced-negative? ;used for indy blame
blame-update ;used for option contract transfers
blame-add-context
;; blame-add-unknown-context
blame-context
blame-replaced-negative?
blame-add-missing-party
blame-missing-party?
;; blame-add-extra-field
raise-blame-error
;; current-blame-format
;; exn:fail:contract:blame
;; blame-fmt->-string
;; invariant-assertion-party
;; NOTE: New interfaces.
contract-violation?
make-blame*))
#|
Blame provides error reporting for the contract system. This module implements
its structure and APIs, and currently follows Racket error message conventions.
See also:
https://docs.racket-lang.org/reference/exns.html#(part._err-msg-conventions)
Blame has a linked structure of <blame> -> <blame> -> ... -> <all-the-info>.
<all-the-info> records contract information and each <blame> node adds extra
context to it. The extra context is combinator-specific (e.g. "the #1 element
of"). For higher-order functions, it also includes whether the positive party
and negative party are swapped.
The positive party provides a definition, and the negative party uses it. For
contracts on higher-order functions, both parties are swapped for function
arguments.
For example, consider the following definition:
(define/contract (example f)
(->/c (->/c number? number?) number?)
...)
The positive party and negative party for ‘example’ will be ‘example’ and
‘caller’, respectively.
‘f’ has a function contract ‘(->/c number? number?)’. As an argument of
‘example’, it initially gets ‘example’ for positive and ‘caller’ for negative.
However the definition of ‘f’ is provided by the caller, so both parties should
be swapped: ‘caller’ for positive, and ‘example’ for negative.
|##|
‘make-blame’ constructs a blame. (<blame> -> <all-the-info>)
(define b1
(make-blame*
#:source #f
#:value 'my-function
#:build-name (const "(listof/c (listof/c number?))")
#:positive 'my-function
#:negative 'caller
#:original? #t))
b1
=> #<<blame>
context-frame: #f
swapped?: #f
and-more: #<<all-the-info> ...>
(blame-swapped? b1)
=> #f
(blame-positive b1)
=> 'my-function
(blame-negative b1)
=> 'caller
(blame-context b1)
=> '()
(blame-contract b1)
=> "(listof/c (listof/c number?))"
‘blame-add-context’ adds a new head node with extra context. (<blame> -> ...)
(define b2
(blame-add-context b1 "an element of" #:swap? #t))
b2
=> #<<blame>
context-frame: "an element of"
swapped? #t
and-more: #<<blame>
context-frame: #f
swapped?: #f
and-more: #<<all-the-info> ...>>
(blame-swapped? b2)
=> #t
(blame-positive b2)
=> 'caller
(blame-negative b2)
=> 'my-function
(blame-context b2)
=> '("an element of")
(blame-contract b2)
=> "(listof/c (listof/c number?))"
(define b3
(blame-add-context b2 "the #1 element of" #:swap? #t))
b3
=> #<<blame>
context-frame: "the #1 element of"
swapped? #t
and-more: #<<blame>
context-frame: "an element of"
swapped? #t
and-more: #<<blame>
context-frame: #f
swapped?: #f
and-more: #<<all-the-info> ...>>
(blame-swapped? b3)
=> #f
(blame-positive b3)
=> 'my-function
(blame-negative b3)
=> 'caller
(blame-context b3)
=> '("the #1 element of" "an element of")
(blame-contract b3)
=> "(listof/c (listof/c number?))"
|#
(define-condition-type &contract-violation &message
contract-violation?)
(define-record-type <important>
(make-important name sense-swapped?)
important?
(name important-name) ; any/c
(sense-swapped? important-sense-swapped?)) ; boolean?
(define-record-type <all-the-info>
(make-all-the-info positive negative source value build-name important
missing-party? context-limit replaced-negative?)
all-the-info?
(positive all-the-info-positive) ; (or/c #f (listof/c any/c))
(negative all-the-info-negative) ; (or/c #f (listof/c any/c))
(source all-the-info-source) ; (or/c #f string?)
(value all-the-info-value) ; any/c
(build-name all-the-info-build-name) ; (->/c string?)
(important all-the-info-important) ; important?
(missing-party? all-the-info-missing-party?) ; boolean?
(context-limit all-the-info-context-limit) ; (or/c #f (and/c integer? (not/c negative?)))
(replaced-negative? all-the-info-replaced-negative?)) ; boolean?
(define (all-the-info-replace-positive all-the-info new-pos)
(make-all-the-info
(all-the-info-positive new-pos)
(all-the-info-negative all-the-info)
(all-the-info-source all-the-info)
(all-the-info-value all-the-info)
(all-the-info-build-name all-the-info)
(all-the-info-important all-the-info)
(all-the-info-missing-party? all-the-info)
(all-the-info-context-limit all-the-info)
(all-the-info-replaced-negative? all-the-info)))
(define (all-the-info-replace-negative all-the-info new-neg)
(make-all-the-info
(all-the-info-positive all-the-info)
(all-the-info-negative new-neg)
(all-the-info-source all-the-info)
(all-the-info-value all-the-info)
(all-the-info-build-name all-the-info)
(all-the-info-important all-the-info)
(all-the-info-missing-party? all-the-info)
(all-the-info-context-limit all-the-info)
(all-the-info-replaced-negative? all-the-info)))
(define-record-type <blame>
(%make-blame context-frame swapped? and-more)
blame?
(context-frame %blame-context-frame) ; (or/c #f string?)
(swapped? %blame-swapped?) ; boolean?
(and-more %blame-and-more)) ; (or/c blame? all-the-info?)
(define* (make-blame source value build-name positive negative original?
#:key (context-limit #f))
(define build/memo-name
(lambda ()
(build-name)))
(define all-the-info
(make-all-the-info
(and positive (list positive))
(and negative (list negative))
source
value
build/memo-name
#f
(not (and positive negative))
context-limit
#f))
(%make-blame
#f
(not original?)
all-the-info))
(define* (make-blame* #:key source value build-name positive negative original?
(context-limit #f))
(make-blame source value build-name positive negative original?
#:context-limit context-limit))
(define (blame->all-the-info blame)
(let loop ((b blame))
(if (blame? b)
(loop (%blame-and-more b))
b)))
(define blame-source
(compose all-the-info-source blame->all-the-info))
(define blame-value
(compose all-the-info-value blame->all-the-info))
(define (blame-contract blame)
((all-the-info-build-name (blame->all-the-info blame))))
(define blame-important
(compose all-the-info-important blame->all-the-info))
(define blame-missing-party?
(compose all-the-info-missing-party? blame->all-the-info))
(define blame-context-limit
(compose all-the-info-context-limit blame->all-the-info))
(define blame-replaced-negative?
(compose all-the-info-replaced-negative? blame->all-the-info))
(define (blame-get-info blame getter)
(let loop ((b blame)
(swapped? #f))
(if (blame? b)
(loop (%blame-and-more b)
(if (%blame-swapped? b)
(not swapped?)
swapped?))
(getter b swapped?))))
(define (blame-set-info blame setter)
(let loop ((b blame)
(swap? #f))
(if (blame? b)
(%make-blame
(%blame-context-frame b)
(%blame-swapped? b)
(loop (%blame-and-more b)
(if (%blame-swapped? b)
(not swap?)
swap?)))
(setter b swap?))))
(define (%blame-positive blame)
(blame-get-info
blame
(lambda (all-the-info swapped?)
(if swapped?
(all-the-info-negative all-the-info)
(all-the-info-positive all-the-info)))))
(define (%blame-negative blame)
(blame-get-info
blame
(lambda (all-the-info swapped?)
(if swapped?
(all-the-info-positive all-the-info)
(all-the-info-negative all-the-info)))))
(define (show-blame accessor blame)
(match (accessor blame)
((x) x)
(x x)))
(define blame-positive
(cut show-blame %blame-positive <>))
(define blame-negative
(cut show-blame %blame-negative <>))
(define (ensure-blame-known who blame)
(unless (and (%blame-positive blame)
(%blame-negative blame))
(error who "blame info is not known; positive ~s negative ~s"
(%blame-positive blame)
(%blame-negative blame))))
(define (blame-update blame extra-positive extra-negative)
(ensure-blame-known 'blame-update blame)
(blame-set-info
blame
(lambda (all-the-info swap?)
(if swap?
(make-all-the-info
(cons extra-negative
(all-the-info-positive all-the-info))
(cons extra-positive
(all-the-info-negative all-the-info))
(all-the-info-source all-the-info)
(all-the-info-value all-the-info)
(all-the-info-build-name all-the-info)
(all-the-info-important all-the-info)
(all-the-info-missing-party? all-the-info)
(all-the-info-context-limit all-the-info)
(all-the-info-replaced-negative? all-the-info))
(make-all-the-info
(cons extra-positive
(all-the-info-positive all-the-info))
(cons extra-negative
(all-the-info-negative all-the-info))
(all-the-info-source all-the-info)
(all-the-info-value all-the-info)
(all-the-info-build-name all-the-info)
(all-the-info-important all-the-info)
(all-the-info-missing-party? all-the-info)
(all-the-info-context-limit all-the-info)
(all-the-info-replaced-negative? all-the-info))))))
(define (blame-swap blame)
(%make-blame
(%blame-context-frame blame)
(not (%blame-swapped? blame))
(%blame-and-more blame)))
(define (blame-swapped? blame)
(blame-get-info
blame
(lambda (_ swapped?) swapped?)))
(define blame-original?
(negate blame-swapped?))
(define (blame/important-original? blame)
(let ((important (blame-important blame)))
(cond
((equal? (%blame-positive blame)
(%blame-negative blame))
#f)
(important
(equal? (important-sense-swapped? important)
(blame-original? blame)))
(else
(blame-original? blame)))))
(define (blame-replace-negative blame new-neg)
(blame-set-info
blame
(lambda (all-the-info swap?)
(if swap?
(all-the-info-replace-positive all-the-info new-neg)
(all-the-info-replace-negative all-the-info new-neg)))))
(define (blame-add-missing-party blame missing-party)
(if missing-party
(begin
(unless (blame-missing-party? blame)
(error 'blame-add-missing-party "already have the party: ~s; trying to add ~s"
(if (blame-swapped? blame)
(%blame-positive blame)
(%blame-negative blame))
missing-party))
(blame-set-info
blame
(lambda (all-the-info _)
(make-all-the-info
(or (all-the-info-positive all-the-info)
(list missing-party))
(or (all-the-info-negative all-the-info)
(list missing-party))
(all-the-info-source all-the-info)
(all-the-info-value all-the-info)
(all-the-info-build-name all-the-info)
(all-the-info-important all-the-info)
#f
(all-the-info-context-limit all-the-info)
(all-the-info-replaced-negative? all-the-info)))))
blame))
(define (blame-context blame)
(let loop ((top (%blame-context-frame blame))
(b (%blame-and-more blame)))
(cond
((all-the-info? b)
(if top
(list top)
'()))
(else
(cons top
(loop (%blame-context-frame b)
(%blame-and-more b)))))))
(define* (blame-add-context blame context #:key important swap?)
(let ((context-limit (blame-context-limit blame)))
(if context-limit
(cond
((not (zero? context-limit))
(let ((limited-blame
dropped-swap?
(drop-to-limit blame context-limit)))
(%make-blame
context
(not (equal? dropped-swap? swap?))
limited-blame)))
(swap?
(%make-blame
(%blame-context-frame blame)
(not (%blame-swapped? blame))
(%blame-and-more blame)))
(else blame))
(%make-blame
context
swap?
(if important
(let loop ((b blame))
(if (blame? b)
(%make-blame
(%blame-context-frame b)
(%blame-swapped? b)
(loop (%blame-and-more b)))
(make-all-the-info
(all-the-info-positive b)
(all-the-info-negative b)
(all-the-info-source b)
(all-the-info-value b)
(all-the-info-build-name b)
(make-important
important
(if swap?
(not (blame-original? b))
(blame-original? b)))
(all-the-info-missing-party? b)
(all-the-info-context-limit b)
(all-the-info-replaced-negative? b))))
blame)))))
(define (drop-to-limit blame context-limit)
(define short-enough?
(let loop ((b blame)
(n (- context-limit 1)))
(or (all-the-info? b)
(if (zero? n)
#f
(loop (%blame-and-more b)
(- n 1))))))
(if short-enough?
(values blame #f)
(let ()
(define swapped? #f)
(define limited-blame
(let outer-loop ((outer-b blame)
(n (- context-limit 1)))
(if (zero? n)
(let inner-loop ((inner-b outer-b)
(swap? #f))
(if (blame? inner-b)
(inner-loop (%blame-and-more inner-b)
(if (%blame-swapped? inner-b)
(not swap?)
swap?))
(begin
(set! swapped? swap?)
inner-b)))
(%make-blame
(%blame-context-frame outer-b)
(%blame-swapped? outer-b)
(outer-loop (%blame-and-more outer-b)
(- n 1))))))
(values limited-blame swapped?))))
(define* (raise-blame-error raw-blame #:optional x #:key (missing-party #f)
#:rest fmt+args)
(define blame
(if (and (blame-original? raw-blame)
(not missing-party))
raw-blame
(blame-add-missing-party raw-blame missing-party)))
(define start-of-message
(let ((self-or-not
(if (blame/important-original? blame)
"broke its own contract"
"contract violation")))
(cond
((blame-important blame)
(format #f "~a: ~a" (important-name (blame-important blame)) self-or-not))
((blame-value blame)
(format #f "~a: ~a" (blame-value blame) self-or-not))
(else
(format #f "~a" self-or-not)))))
(define custom-message
(let loop ((args fmt+args))
(match args
;; Keyword arguments will be added to #:rest as well, strip them.
(((? keyword? kw) arg . rest)
(loop rest))
((fmt . fmt-args)
;; When formatting outputs, please use ~s to mimic Racket ~e.
;;
;; XXX: ~s doesn't directly map to Racket ~e. With symbol 'x, ~s
;; gives ‘x’ but Racket ~e gives ‘'x’, for example.
(apply format #f (blame-fmt->string blame fmt) fmt-args)))))
(define context-lines
(let ((context (blame-context blame)))
(or (and context
(not (null? context))
(let loop ((ctx context)
(idx 0)
(res '()))
(if (null? ctx)
(reverse res)
(loop (cdr ctx)
(1+ idx)
(cons (if (zero? idx)
(format #f " in: ~a~%" (car ctx))
(format #f " ~a~%" (car ctx)))
res)))))
'())))
(define contract-line
(format #f " ~a ~a~%"
(if (null? context-lines) "in:" " ")
(blame-contract blame)))
(define from-line
(format #f " contract from: ~a~%"
(if (blame-original? blame)
(last (%blame-positive blame))
(last (%blame-negative blame)))))
(define on-line
(or (and (blame-important blame)
(blame-value blame)
(format #f " contract on: ~a~%" (blame-value blame)))
""))
(define blaming-line
(let ((blame-parties (%blame-positive blame)))
(match blame-parties
((one-party)
(format #f " blaming: ~a~%" one-party))
((multiple-parties ...)
(format #f " blaming multiple parties: ~{~a~%~}~%" multiple-parties)))))
(define assumption-line
" (assuming the contract is correct)")
(define at-line
(or (and=> (blame-source blame)
(cut format #f "~% at: ~a" <>))
""))
(raise
(condition
(&contract-violation
(message
(format #f "~%~a~a~{~a~}~a~a~a~a~a~a"
start-of-message
(if (string-null? custom-message) "~%" custom-message)
context-lines
contract-line
from-line
on-line
blaming-line
assumption-line
at-line))))))
(define (blame-fmt->string blame fmt)
(define original?
(blame/important-original? blame))
(define (tag->str+newline? key val)
(define* (kv->str key val)
(string-append key " " val))
(match key
;; Racket doesn't use ‘got’, but ‘expected’ vs ‘got’ sounds more natural
;; considering directions.
((or 'given: 'got:)
(values (kv->str (if original? "produced:" "given:") val)
#t))
((or 'given 'got)
(values (kv->str (if original? "produced" "given") val)
#f))
('expected:
(values (kv->str (if original? "promised:" "expected:") val)
#t))
('expected
(values (kv->str (if original? "promised" "expected") val)
#f))
('received:
(values (kv->str (if original? "supplied:" "received:") val)
#t))))
(define (normalize-continued-error-message str)
"If STR contains newline (unless at the end), ensure there's a space next to
it."
(define (not-space? x)
(not (equal? x #\space)))
(define str-newline-normalized
(string-replace-substring str "~%" "\n"))
(if (string-contains str-newline-normalized "\n")
(let loop ((chars (string->list str-newline-normalized))
(result '()))
(if (null? chars)
(list->string (reverse result))
(match chars
((#\newline (? not-space? next) . rest)
(loop rest
(append (reverse (list #\newline #\space next))
result)))
((first . rest)
(loop rest
(cons first result))))))
str-newline-normalized))
(define (build-string old new newline?)
(if newline?
(string-append old "\n " new)
(let ((old (if (string-null? old) ";\n" old))
(new (normalize-continued-error-message new)))
(if (or (string-suffix? " " old)
(string-match "^[\n ]" new))
(string-append old new)
(string-append old " " new)))))
(if (string? fmt)
fmt
(let loop ((strs fmt)
(result ""))
(if (null? strs)
(if (string-null? result)
result
(string-append result "\n"))
(match strs
(((? symbol? key) (? string? val) . rest)
(let ((str newline? (tag->str+newline? key val)))
(loop rest
(build-string result str newline?))))
((str . rest)
(loop rest
(build-string result str #f))))))))
@@ -0,0 +1,148 @@
;;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Copyright © 2026 Hilton Chain <hako@ultrarare.space>
(define-module (rosenthal utils contract combinators)
#:use-module (ice-9 match)
#:autoload (rnrs bytevectors) (bytevector?)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (rosenthal utils contract impl)
#:use-module (rosenthal utils contract blame)
#:export (any/c
none/c
or/c
listof/c
->/c
->contract))
#|
This module implements contract combinators. To avoid name collisions, all
combinator names have a ‘/c’ suffix.
|#
(define any/c
(make-contract
#:name "any/c"
#:checker (const #t)))
(define none/c
(make-contract
#:name "none/c"
#:checker (const #f)))
(define (or/c . ctcs)
(let* ((contracts (map ->contract ctcs))
(enforcers (map contract-enforcer contracts))
(name (compound-contract-name "or/c" contracts) ))
(make-contract
#:name name
#:enforcer
(lambda (blame)
(define procs
(map (lambda (enforcer)
(enforcer blame))
enforcers))
(lambda (val neg-party)
(let loop ((procs procs))
(if (null? procs)
(raise-blame-error blame #:missing-party neg-party
'(expected: "~a" got: "~s")
name val)
(match procs
((proc . rest)
(guard (c ((contract-violation? c)
(loop rest)))
(proc val neg-party)))))))))))
(define (listof/c ctc)
(let* ((contract (->contract ctc))
(enforcer (contract-enforcer contract)))
(make-contract
#:name (compound-contract-name "listof/c" (list contract))
#:enforcer
(lambda (blame)
(define proc
(enforcer (blame-add-context blame "an element of")))
(lambda (val neg-party)
(unless (list? val)
(raise-blame-error blame #:missing-party neg-party
'(expected: "a list of ~a" got: "~s")
(contract-name contract)
val))
(map (lambda (element)
(proc element neg-party))
val))))))
;; TODO: Rewrite as a macro to support define*, multiple return values, and
;; ‘any’.
(define (->/c . ctcs)
(let* ((contracts (map ->contract ctcs))
(domain-contracts (drop-right contracts 1))
(range-contract (last contracts))
(contract-arity (length domain-contracts)))
(make-contract
#:name (compound-contract-name "->/c" contracts)
#:enforcer
(lambda (blame)
(define domain-blames
(map (lambda (index)
(let ((position (format #f "the #~a argument of" index)))
(blame-add-context blame position #:swap? #t)))
(iota contract-arity 1)))
(define domain-enforcers
(map contract-enforcer domain-contracts))
(define range-proc
(let ((range-blame (blame-add-context blame "the range of")))
((contract-enforcer range-contract) range-blame)))
(lambda (val neg-party)
(unless (procedure? val)
(raise-blame-error blame #:missing-party neg-party
'(expected: "a procedure" got: "~s") val))
(lambda args
;; XXX: Can't check procedure arity in Guile.
(let ((arity (length args)))
(unless (= arity contract-arity)
(raise-blame-error
(blame-swap blame) #:missing-party neg-party
`("assuming arity of the contract is always correct"
expected: "~a argument(s)" got: "~a argument(s)")
contract-arity arity)))
(define args*
(map (lambda (arg blame enforcer)
((enforcer blame) arg neg-party))
args
domain-blames
domain-enforcers))
(range-proc (apply val args*) neg-party)))))))
(define (->contract x)
(match x
((? contract?) x)
((? procedure?)
(make-contract
#:name (format #f "~s" (or (procedure-name x) '???))
#:checker x))
((or (? symbol?)
(? boolean?)
(? keyword?))
(make-contract
#:name (format #f "~s" x)
#:checker (cut eq? x <>)))
((or (? string?)
(? bytevector?)
(? char?)
+nan.0)
(make-contract
#:name (format #f "~s" x)
#:checker (cut equal? x <>)))
((? number?)
(make-contract
#:name (format #f "~s" x)
#:checker (cut = x <>)))
(_ (error (format #f "cannot use as contract: ~s" x)))))
+70
View File
@@ -0,0 +1,70 @@
;;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Copyright © 2026 Hilton Chain <hako@ultrarare.space>
(define-module (rosenthal utils contract impl)
#:use-module (srfi srfi-9)
#:use-module (rosenthal utils contract blame)
#:export (contract?
make-contract
contract-name
contract-checker
contract-enforcer
compound-contract-name))
#|
This module provides the data representation of contracts.
When constructing a contract via ‘make-contract’, at least one of a checker or
an enforcer must be specified.
A checker is a predicate function. An enforcer is a function that actually
performs the check and either returns the value or raises an error with extra
context. If only a checker is provided, an enforcer will be automatically
created.
Note that checkers should only be provided when values can be checked
immediately (e.g. checking a value is a number). Checkers don't work well for
things like a list of numbers, since we won't know the location and context of a
failure.
Contract combinators may rely on checkers' availability for optimizations.
Enforcers are "late neg projections" in Racket, which look like the following:
(lambda (blame)
(lambda (val neg-party)
...))
This allows a contract to be partially evaluated when it's constructed and
attached, before the value is actually checked.
See also (rosenthal utils contract combinators) for more examples, and
(rosenthal utils contract combinators) for error reporting of contracts.
|#
(define-record-type <contract>
(%make-contract name checker enforcer)
contract?
(name contract-name) ; string?
(checker contract-checker) ; (or/c #f (->/c any/c boolean?))
(enforcer contract-enforcer)) ; (->/c blame? (->/c any/c any/c any/c))
(define* (make-contract #:key name checker enforcer)
(%make-contract
name
checker
(or enforcer
(lambda (blame)
(lambda (val neg-party)
(if (checker val)
val
(raise-blame-error blame #:missing-party neg-party
`(expected: "~a" got: "~s") name val)))))))
(define (compound-contract-name name ctcs)
(format #f "(~a ~a)"
name
(string-join (map contract-name ctcs) " ")))
+729
View File
@@ -0,0 +1,729 @@
;;; SPDX-License-Identifier: GPL-3.0-or-later
;;; Copyright © 2012-2026 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2018 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2026 coopi <coldsideofyourpillow@disroot.org>
(define-module (rosenthal utils records)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-26)
#:use-module (ice-9 match)
#:use-module (ice-9 rdelim)
#:autoload (system syntax) (syntax-local-binding)
#:autoload (rosenthal utils contract) (apply-contract/guix-record-field)
#:export (define-record-type/dolly
this-record
match-record/dolly
match-record-lambda/dolly))
(define-syntax record-error
(syntax-rules ()
"Report a syntactic error in use of CONSTRUCTOR."
((_ constructor form fmt args ...)
(syntax-violation constructor
(format #f fmt args ...)
form))))
(eval-when (expand load eval)
;; The procedures below are needed both at run time and at expansion time.
(define %record-constructor-max-argument-count
;; Maximum number of positional arguments for record constructors. This
;; matches Guile's 'make-record-type', which uses a rest argument above
;; that number.
20)
(define (current-abi-identifier type)
"Return an identifier unhygienically derived from TYPE for use as its
\"current ABI\" variable."
(let ((type-name (syntax->datum type)))
(datum->syntax
type
(string->symbol
(string-append "% " (symbol->string type-name)
" abi-cookie")))))
(define (record-abi-mismatch-error type)
(throw 'record-abi-mismatch-error 'abi-check
"~a: record ABI mismatch; recompilation needed"
(list type) '()))
(define (abi-check type cookie)
"Return syntax that checks that the current \"application binary
interface\" (ABI) for TYPE is equal to COOKIE."
(with-syntax ((current-abi (current-abi-identifier type)))
#`(unless (eq? current-abi #,cookie)
;; The source file where this exception is thrown must be
;; recompiled.
(record-abi-mismatch-error #,type))))
(define* (report-invalid-field-specifier name bindings
#:optional parent-form)
"Report the first invalid binding among BINDINGS. PARENT-FORM is used for
error-reporting purposes."
(let loop ((bindings bindings))
(syntax-case bindings ()
(((field value) rest ...) ;good
(loop #'(rest ...)))
((weird _ ...) ;weird!
;; WEIRD may be an identifier, thus lacking source location info, and
;; BINDINGS is a list, also lacking source location info. Hopefully
;; PARENT-FORM provides source location info.
(apply syntax-violation name "invalid field specifier"
(if parent-form
(list parent-form #'weird)
(list #'weird)))))))
(define (report-duplicate-field-specifier name ctor)
"Report the first duplicate identifier among the bindings in CTOR."
(syntax-case ctor ()
((_ bindings ...)
(let loop ((bindings #'(bindings ...))
(seen '()))
(syntax-case bindings ()
(((field value) rest ...)
(not (memq (syntax->datum #'field) seen))
(loop #'(rest ...) (cons (syntax->datum #'field) seen)))
((duplicate rest ...)
(syntax-violation name "duplicate field initializer"
#'duplicate))
(()
#t)))))))
(define-syntax map-fields
(lambda (x)
(syntax-case x ()
((_ type within)
(syntax-violation (syntax->datum #'within)
"undefined record type"
#'type))
(_ (syntax-violation 'map-fields "bad use of syntactic keyword" x x)))))
(define-syntax-parameter this-record
(lambda (s)
"Return the record being defined. This macro may only be used in the
context of the definition of a thunked field."
(syntax-case s ()
(id
(identifier? #'id)
(syntax-violation 'this-record
"cannot be used outside of a record instantiation"
#'id)))))
(define-syntax make-syntactic-constructor
(syntax-rules ()
"Make the syntactic constructor NAME for TYPE, that calls CTOR, and
expects all of EXPECTED fields to be initialized. DEFAULTS is the list of
FIELD/DEFAULT-VALUE tuples, THUNKED is the list of identifiers of thunked
fields, DELAYED is the list of identifiers of delayed fields, and SANITIZERS
is the list of FIELD/SANITIZER tuples.
ABI-COOKIE is the cookie (an integer) against which to check the run-time ABI
of TYPE matches the expansion-time ABI."
((_ type name ctor (expected ...)
#:abi-cookie abi-cookie
#:thunked thunked
#:this-identifier this-identifier
#:delayed delayed
#:innate innate
#:contracts contracts
#:sanitizers sanitizers
#:defaults defaults)
(define-syntax name
(lambda (s)
(define (constructor-call field-values)
(if (< (length '(expected ...))
%record-constructor-max-argument-count)
#`(ctor #,abi-cookie #,@field-values)
#`(apply ctor #,abi-cookie (list #,@field-values))))
(define (record-inheritance orig-record field+value)
;; Produce code that returns a record identical to ORIG-RECORD,
;; except that values for the FIELD+VALUE alist prevail.
(define (field-inherited-value f)
(and=> (find (lambda (x)
(eq? f (car (syntax->datum x))))
field+value)
car))
;; Make sure there are no unknown field names.
(let* ((fields (map (compose car syntax->datum) field+value))
(unexpected (lset-difference eq? fields '(expected ...))))
(when (pair? unexpected)
(record-error 'name s "extraneous field initializers ~a"
unexpected)))
(constructor-call
(map (lambda (field index)
(or (field-inherited-value field)
(if (innate-field? field)
(wrap-field-value
field (field-default-value field))
#`(struct-ref #,orig-record #,index))))
'(expected ...)
(iota (length '(expected ...))))))
(define (thunked-field? f)
(memq (syntax->datum f) 'thunked))
(define (delayed-field? f)
(memq (syntax->datum f) 'delayed))
(define (innate-field? f)
(memq (syntax->datum f) 'innate))
(define field-contract
(let ((lst (map (match-lambda
((f p)
(list (syntax->datum f) p)))
#'contracts)))
(lambda (f)
(or (and=> (assoc-ref lst (syntax->datum f)) car)
#'any/c))))
(define field-sanitizer
(let ((lst (map (match-lambda
((f p)
(list (syntax->datum f) p)))
#'sanitizers)))
(lambda (f)
(or (and=> (assoc-ref lst (syntax->datum f)) car)
#'identity))))
(define (field-index f)
;; Return the index of F within the record.
(let ((f (syntax->datum f)))
(let loop ((fields '(expected ...))
(index 0))
(match fields
(()
;; Internal error.
(record-error 'name s "field not found ~a" f))
((head . rest)
(if (eq? f head)
index
(loop rest (+ 1 index))))))))
(define (check-shadowing identifier)
;; Warn if IDENTIFIER shadows a local binding.
;; Note: not using (guix diagnostics) to remain independent of
;; other Guix modules.
(when (eq? 'lexical (syntax-local-binding identifier))
(format (current-warning-port)
"~a: inherited field binding '~a' of \
record type '~a' shadows local variable~%"
(match (syntax-source identifier)
(#f "<unknown-location>")
(lst (format #f "~a:~a:~a"
(assq-ref lst 'filename)
(and=> (assq-ref lst 'line) 1+)
(assq-ref lst 'column))))
(syntax->datum identifier)
(syntax->datum #'type))))
(define* (wrap-field-value f value #:optional parent)
;; Wrap VALUE, the value of field F, such that its sanitizer is
;; called and its properties (thunked, delayed) honored. When
;; PARENT is true, bind F to the value inherited from PARENT in the
;; lexical scope of VALUE.
(let* ((contract (field-contract f))
(sanitizer (field-sanitizer f))
(contract? (not (eq? (syntax->datum contract) 'any/c)))
(sanitizer? (not (eq? (syntax->datum sanitizer) 'identity)))
(value
(cond
((and contract? sanitizer?)
#`(#,sanitizer
(apply-contract/guix-record-field
#,contract
#,value
#,(symbol->string (syntax->datum (record-type-name type)))
#,(symbol->string (syntax->datum #'f)))))
(contract?
#`(apply-contract/guix-record-field
#,contract
#,value
#,(symbol->string (syntax->datum (record-type-name type)))
#,(symbol->string (syntax->datum f))))
(sanitizer?
#`(#,sanitizer #,value))
(else value))))
(cond ((thunked-field? f)
(if parent
;; Compute the value being inherited by calling the
;; thunked field F of PARENT with a self-reference for
;; the new record being constructed.
(with-syntax ((inherited
#`((struct-ref #,parent
#,(field-index f))
#,this-identifier)))
(check-shadowing f)
#`(lambda (x)
(syntax-parameterize ((#,this-identifier
(lambda (s)
(syntax-case s ()
(id
(identifier? #'id)
#'x)))))
;; Bind F, the field identifier, to the value
;; being inherited.
(let-syntax ((#,f (identifier-syntax inherited)))
#,value))))
#`(lambda (x)
(syntax-parameterize ((#,this-identifier
(lambda (s)
(syntax-case s ()
(id
(identifier? #'id)
#'x)))))
#,value))))
((delayed-field? f)
#`(delay #,value))
(else value))))
(define default-values
;; List of symbol/value tuples.
(map (match-lambda
((f v)
(list (syntax->datum f) v)))
#'defaults))
(define (field-default-value f)
(car (assoc-ref default-values (syntax->datum f))))
(define (field-bindings field+value)
;; Return field to value bindings, for use in 'let*' below.
(map (lambda (field+value)
(syntax-case field+value ()
((field value)
#`(field
#,(wrap-field-value #'field #'value)))))
field+value))
(define (field-bindings/inheritance parent field+value)
;; Return field to value bindings, for use in 'let*' below.
(map (lambda (field+value)
(syntax-case field+value ()
((field value)
#`(field
#,(wrap-field-value #'field #'value parent)))))
field+value))
(syntax-case s (inherit expected ...)
((_ (inherit orig-record) (field value) (... ...))
#`(let* #,(field-bindings/inheritance #'orig-record
#'((field value) (... ...)))
#,(abi-check #'type abi-cookie)
#,(record-inheritance #'orig-record
#'((field value) (... ...)))))
((_ (field value) (... ...))
(let ((fields (map syntax->datum #'(field (... ...)))))
(define (field-value f)
(or (find (lambda (x)
(eq? f (syntax->datum x)))
#'(field (... ...)))
(wrap-field-value f (field-default-value f))))
;; Pass S to make sure source location info is preserved.
(report-duplicate-field-specifier 'name s)
(let ((fields (append fields (map car default-values))))
(cond ((lset= eq? fields '(expected ...))
#`(let* #,(field-bindings
#'((field value) (... ...)))
#,(constructor-call
(map field-value '(expected ...)))))
((pair? (lset-difference eq? fields
'(expected ...)))
(record-error 'name s
"extraneous field initializers ~a"
(lset-difference eq? fields
'(expected ...))))
(else
(record-error 'name s
"missing field initializers ~a"
(lset-difference eq?
'(expected ...)
fields)))))))
((_ bindings (... ...))
;; One of BINDINGS doesn't match the (field value) pattern.
;; Report precisely which one is faulty, instead of letting the
;; "source expression failed to match any pattern" error.
(report-invalid-field-specifier 'name
#'(bindings (... ...))
s))))))))
(define-syntax-rule (define-field-property-predicate predicate property)
"Define PREDICATE as a procedure that takes a syntax object and, when passed
a field specification, returns the field name if it has the given PROPERTY."
(define (predicate s)
(syntax-case s (property)
((field (property values (... ...)) _ (... ...))
#'field)
((field _ properties (... ...))
(predicate #'(field properties (... ...))))
(_ #f))))
(define-syntax define-record-type/dolly
(lambda (s)
"Define the given record type such that an additional \"syntactic
constructor\" is defined, which allows instances to be constructed with named
field initializers, à la SRFI-35, as well as default values. An example use
may look like this:
(define-record-type* <thing> thing make-thing
thing?
this-thing
(name thing-name (default \"chbouib\"))
(port thing-port
(default (current-output-port)) (thunked))
(loc thing-location (innate) (default (current-source-location))))
This example defines a macro 'thing' that can be used to instantiate records
of this type:
(thing
(name \"foo\")
(port (current-error-port)))
The value of 'name' or 'port' could as well be omitted, in which case the
default value specified in the 'define-record-type*' form is used:
(thing)
The 'port' field is \"thunked\", meaning that calls like '(thing-port x)' will
actually compute the field's value in the current dynamic extent, which is
useful when referring to fluids in a field's value. Furthermore, that thunk
can access the record it belongs to via the 'this-thing' identifier.
A field can also be marked as \"delayed\" instead of \"thunked\", in which
case its value is effectively wrapped in a (delay …) form.
A field can also have an associated \"sanitizer\", which is a procedure that
takes a user-supplied field value and returns a \"sanitized\" value for the
field:
(define-record-type* <thing> thing make-thing
thing?
this-thing
(name thing-name
(sanitize (lambda (value)
(cond ((string? value) value)
((symbol? value) (symbol->string value))
(else (throw 'bad! value)))))))
It is possible to copy an object 'x' created with 'thing' like this:
(thing (inherit x) (name \"bar\"))
This expression returns a new object equal to 'x' except for its 'name'
field and its 'loc' field---the latter is marked as \"innate\", so it is not
inherited."
(define (rtd-identifier type)
;; Return an identifier derived from TYPE to name its record type
;; descriptor (RTD).
(let ((type-name (syntax->datum type)))
(datum->syntax
type
(string->symbol
(string-append "% " (symbol->string type-name) " rtd")))))
(define (field-default-value s)
(syntax-case s (default)
((field (default val) _ ...)
(list #'field #'val))
((field _ properties ...)
(field-default-value #'(field properties ...)))
(_ #f)))
(define (field-contract s)
(syntax-case s (contract)
((field (contract ctc) _ ...)
(list #'field #'ctc))
((field _ properties ...)
(field-contract #'(field properties ...)))
(_ #f)))
(define (field-sanitizer s)
(syntax-case s (sanitize)
((field (sanitize proc) _ ...)
(list #'field #'proc))
((field _ properties ...)
(field-sanitizer #'(field properties ...)))
(_ #f)))
(define-field-property-predicate delayed-field? delayed)
(define-field-property-predicate thunked-field? thunked)
(define-field-property-predicate innate-field? innate)
(define (wrapped-field? s)
(or (thunked-field? s) (delayed-field? s)))
(define (wrapped-field-accessor-name field)
;; Return the name (an unhygienic syntax object) of the "real"
;; getter for field, which is assumed to be a wrapped field.
(syntax-case field ()
((field get properties ...)
(let* ((getter (syntax->datum #'get))
(real-getter (symbol-append '% getter '-real)))
(datum->syntax #'get real-getter)))))
(define (field-spec->srfi-9 field)
;; Convert a field spec of our style to a SRFI-9 field spec of the
;; form (field get).
(syntax-case field ()
((name get properties ...)
#`(name
#,(if (wrapped-field? field)
(wrapped-field-accessor-name field)
#'get)))))
(define (thunked-field-accessor-definition field)
;; Return the real accessor for FIELD, which is assumed to be a
;; thunked field.
(syntax-case field ()
((name get _ ...)
(with-syntax ((real-get (wrapped-field-accessor-name field)))
#'(define-inlinable (get x)
;; The real value of that field is a thunk, so call it.
((real-get x) x))))))
(define (delayed-field-accessor-definition field)
;; Return the real accessor for FIELD, which is assumed to be a
;; delayed field.
(syntax-case field ()
((name get _ ...)
(with-syntax ((real-get (wrapped-field-accessor-name field)))
#'(define-inlinable (get x)
;; The real value of that field is a promise, so force it.
(force (real-get x)))))))
(define (compute-abi-cookie field-specs)
;; Compute an "ABI cookie" for the given FIELD-SPECS. We use
;; 'string-hash' because that's a better hash function that 'hash' on a
;; list of symbols.
(syntax-case field-specs ()
(((field get properties ...) ...)
;; Passing (target-most-positive-fixnum) as the second argument of
;; 'string-hash' won't have the intended effect when cross-compiling
;; because that second argument is used to compute a modulo after the
;; hash has been computed on an 'unsigned long'. Instead, only keep
;; the 32 most significant bits on 64-bit platforms, unconditionally.
;; See <https://issues.guix.gnu.org/74296>.
(let ((hash-value
(string-hash
(object->string (syntax->datum #'((field properties ...) ...))))))
(cond
((< most-positive-fixnum (ash 1 32)) hash-value)
((< most-positive-fixnum (ash 1 64)) (ash hash-value -32))
(else (error "unexpected!" most-positive-fixnum)))))))
(syntax-case s ()
((_ type syntactic-ctor ctor pred
this-identifier
(field get properties ...) ...)
(identifier? #'this-identifier)
(let* ((field-spec #'((field get properties ...) ...))
(thunked (filter-map thunked-field? field-spec))
(delayed (filter-map delayed-field? field-spec))
(innate (filter-map innate-field? field-spec))
(defaults (filter-map field-default-value
#'((field properties ...) ...)))
(contracts (filter-map field-contract
#'((field properties ...) ...)))
(sanitizers (filter-map field-sanitizer
#'((field properties ...) ...)))
(cookie (compute-abi-cookie field-spec))
(field-count (length field-spec))
(constructor-procedure
(datum->syntax
#'ctor
(symbol-append (string->symbol " %")
(syntax->datum #'ctor)
'-procedure/abi-check))))
(define (constructor-body)
(if (< field-count %record-constructor-max-argument-count)
#`(case-lambda
((actual-cookie field ...)
(unless (eq? actual-cookie #,cookie)
(record-abi-mismatch-error type))
(ctor field ...))
(_
(record-abi-mismatch-error type)))
#`(case-lambda
((actual-cookie . field-values)
(unless (and (eq? actual-cookie #,cookie)
(= (length field-values)
#,field-count))
(record-abi-mismatch-error type))
(apply ctor field-values))
(_
(record-abi-mismatch-error type)))))
(with-syntax ((ctor-procedure constructor-procedure)
((field-spec* ...)
(map field-spec->srfi-9 field-spec))
((field-type ...)
(map (match-lambda
((? thunked-field?)
(datum->syntax s 'thunked))
((? delayed-field?)
(datum->syntax s 'delayed))
(else
(datum->syntax s 'normal)))
field-spec))
((thunked-field-accessor ...)
(filter-map (lambda (field)
(and (thunked-field? field)
(thunked-field-accessor-definition
field)))
field-spec))
((delayed-field-accessor ...)
(filter-map (lambda (field)
(and (delayed-field? field)
(delayed-field-accessor-definition
field)))
field-spec)))
#`(begin
(define-record-type #,(rtd-identifier #'type)
(ctor field ...)
pred
field-spec* ...)
;; Rectify the vtable type name...
(set-struct-vtable-name! #,(rtd-identifier #'type) 'type)
(cond-expand
(guile-3
;; ... and the record type name.
(struct-set! #,(rtd-identifier #'type) vtable-offset-user
'type))
(else #f))
(define-syntax type
(lambda (s)
"This macro lets us query record type info at
macro-expansion time."
(syntax-case s (map-fields)
((_ (map-fields _ _) macro)
#'(macro ((field field-type) ...)))
(id
(identifier? #'id)
#'#,(rtd-identifier #'type)))))
(define #,(current-abi-identifier #'type)
#,cookie)
#,@(if (free-identifier=? #'this-identifier #'this-record)
#'()
#'((define-syntax-parameter this-identifier
(lambda (s)
"Return the record being defined. This macro may
only be used in the context of the definition of a thunked field."
(syntax-case s ()
(id
(identifier? #'id)
(syntax-violation 'this-identifier
"cannot be used outside \
of a record instantiation"
#'id)))))))
thunked-field-accessor ...
delayed-field-accessor ...
(define ctor-procedure
;; This procedure is *not* inlined, to reduce code bloat
;; (struct initialization takes at least one instruction per
;; field).
#,(constructor-body))
(make-syntactic-constructor type syntactic-ctor ctor-procedure
(field ...)
#:abi-cookie #,cookie
#:thunked #,thunked
#:this-identifier #'this-identifier
#:delayed #,delayed
#:innate #,innate
#:contracts #,contracts
#:sanitizers #,sanitizers
#:defaults #,defaults)))))
((_ type syntactic-ctor ctor pred
(field get properties ...) ...)
;; When no 'this' identifier was specified, use 'this-record'.
#'(define-record-type/dolly type syntactic-ctor ctor pred
this-record
(field get properties ...) ...)))))
;;;
;;; Pattern matching.
;;;
(define-syntax lookup-field+wrapper
(lambda (s)
"Look up FIELD in the given list and return both an expression that represents
its offset in the record and a procedure that wraps it to return its \"true\" value
(for instance, FORCE is returned in the case of a delayed field). RECORD is passed
to thunked values. Raise a syntax violation when the field is not found."
(syntax-case s (normal delayed thunked)
((_ record field offset ())
(syntax-violation 'match-record
"unknown record type field"
;; Attach the local source data to the field.
(datum->syntax #f (syntax->datum #'field) #:source s)))
((_ record field offset ((head normal) tail ...))
(free-identifier=? #'field #'head)
#'(values offset identity))
((_ record field offset ((head delayed) tail ...))
(free-identifier=? #'field #'head)
#'(values offset force))
((_ record field offset ((head thunked) tail ...))
(free-identifier=? #'field #'head)
#'(values offset (cut <> record)))
((_ record field offset (_ tail ...))
#'(lookup-field+wrapper record field
(+ 1 offset) (tail ...))))))
(define-syntax match-record-inner
(lambda (s)
(syntax-case s ()
((_ record type ((field variable) rest ...) body ...)
#'(let-syntax ((field-offset+wrapper
(syntax-rules ()
((_ f)
(lookup-field+wrapper record field 0 f)))))
(let*-values (((offset wrap)
(type (map-fields type match-record)
field-offset+wrapper))
((variable)
(wrap (struct-ref record offset))))
(match-record-inner record type (rest ...) body ...))))
((_ record type (field rest ...) body ...)
;; Redirect to the canonical form above.
#'(match-record-inner record type ((field field) rest ...) body ...))
((_ record type () body ...)
#'(begin body ...)))))
(define-syntax match-record/dolly
(syntax-rules ()
"Bind each FIELD of a RECORD of the given TYPE to its FIELD name.
The order in which fields appear does not matter. A syntax error is raised if
an unknown field is queried."
((_ record type (fields ...) body ...)
(if (eq? (struct-vtable record) type)
(match-record-inner record type (fields ...) body ...)
(throw 'wrong-type-arg "match-record"
"Wrong type (expecting a ~a record): ~S"
(list 'type record) (list record))))))
(define-syntax match-record-lambda/dolly
(syntax-rules ()
"Return a procedure accepting a single record of the given TYPE for which each
FIELD will be bound to its FIELD name within the returned procedure. A syntax error
is raised if an unknown field is queried."
((_ type (field ...) body ...)
(lambda (record)
(match-record/dolly record type (field ...)
body ...)))))