records.scm 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2018 Mark H Weaver <mhw@netris.org>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix records)
  20. #:use-module (srfi srfi-1)
  21. #:use-module (srfi srfi-9)
  22. #:use-module (srfi srfi-26)
  23. #:use-module (ice-9 match)
  24. #:use-module (ice-9 regex)
  25. #:use-module (ice-9 rdelim)
  26. #:autoload (system base target) (target-most-positive-fixnum)
  27. #:export (define-record-type*
  28. this-record
  29. alist->record
  30. object->fields
  31. recutils->alist
  32. match-record))
  33. ;;; Commentary:
  34. ;;;
  35. ;;; Utilities for dealing with Scheme records.
  36. ;;;
  37. ;;; Code:
  38. (define-syntax record-error
  39. (syntax-rules ()
  40. "Report a syntactic error in use of CONSTRUCTOR."
  41. ((_ constructor form fmt args ...)
  42. (syntax-violation constructor
  43. (format #f fmt args ...)
  44. form))))
  45. (eval-when (expand load eval)
  46. ;; The procedures below are needed both at run time and at expansion time.
  47. (define (current-abi-identifier type)
  48. "Return an identifier unhygienically derived from TYPE for use as its
  49. \"current ABI\" variable."
  50. (let ((type-name (syntax->datum type)))
  51. (datum->syntax
  52. type
  53. (string->symbol
  54. (string-append "% " (symbol->string type-name)
  55. " abi-cookie")))))
  56. (define (abi-check type cookie)
  57. "Return syntax that checks that the current \"application binary
  58. interface\" (ABI) for TYPE is equal to COOKIE."
  59. (with-syntax ((current-abi (current-abi-identifier type)))
  60. #`(unless (eq? current-abi #,cookie)
  61. ;; The source file where this exception is thrown must be
  62. ;; recompiled.
  63. (throw 'record-abi-mismatch-error 'abi-check
  64. "~a: record ABI mismatch; recompilation needed"
  65. (list #,type) '()))))
  66. (define* (report-invalid-field-specifier name bindings
  67. #:optional parent-form)
  68. "Report the first invalid binding among BINDINGS. PARENT-FORM is used for
  69. error-reporting purposes."
  70. (let loop ((bindings bindings))
  71. (syntax-case bindings ()
  72. (((field value) rest ...) ;good
  73. (loop #'(rest ...)))
  74. ((weird _ ...) ;weird!
  75. ;; WEIRD may be an identifier, thus lacking source location info, and
  76. ;; BINDINGS is a list, also lacking source location info. Hopefully
  77. ;; PARENT-FORM provides source location info.
  78. (apply syntax-violation name "invalid field specifier"
  79. (if parent-form
  80. (list parent-form #'weird)
  81. (list #'weird)))))))
  82. (define (report-duplicate-field-specifier name ctor)
  83. "Report the first duplicate identifier among the bindings in CTOR."
  84. (syntax-case ctor ()
  85. ((_ bindings ...)
  86. (let loop ((bindings #'(bindings ...))
  87. (seen '()))
  88. (syntax-case bindings ()
  89. (((field value) rest ...)
  90. (not (memq (syntax->datum #'field) seen))
  91. (loop #'(rest ...) (cons (syntax->datum #'field) seen)))
  92. ((duplicate rest ...)
  93. (syntax-violation name "duplicate field initializer"
  94. #'duplicate))
  95. (()
  96. #t)))))))
  97. (define-syntax-parameter this-record
  98. (lambda (s)
  99. "Return the record being defined. This macro may only be used in the
  100. context of the definition of a thunked field."
  101. (syntax-case s ()
  102. (id
  103. (identifier? #'id)
  104. (syntax-violation 'this-record
  105. "cannot be used outside of a record instantiation"
  106. #'id)))))
  107. (define-syntax make-syntactic-constructor
  108. (syntax-rules ()
  109. "Make the syntactic constructor NAME for TYPE, that calls CTOR, and
  110. expects all of EXPECTED fields to be initialized. DEFAULTS is the list of
  111. FIELD/DEFAULT-VALUE tuples, THUNKED is the list of identifiers of thunked
  112. fields, DELAYED is the list of identifiers of delayed fields, and SANITIZERS
  113. is the list of FIELD/SANITIZER tuples.
  114. ABI-COOKIE is the cookie (an integer) against which to check the run-time ABI
  115. of TYPE matches the expansion-time ABI."
  116. ((_ type name ctor (expected ...)
  117. #:abi-cookie abi-cookie
  118. #:thunked thunked
  119. #:this-identifier this-identifier
  120. #:delayed delayed
  121. #:innate innate
  122. #:sanitizers sanitizers
  123. #:defaults defaults)
  124. (define-syntax name
  125. (lambda (s)
  126. (define (record-inheritance orig-record field+value)
  127. ;; Produce code that returns a record identical to ORIG-RECORD,
  128. ;; except that values for the FIELD+VALUE alist prevail.
  129. (define (field-inherited-value f)
  130. (and=> (find (lambda (x)
  131. (eq? f (car (syntax->datum x))))
  132. field+value)
  133. car))
  134. ;; Make sure there are no unknown field names.
  135. (let* ((fields (map (compose car syntax->datum) field+value))
  136. (unexpected (lset-difference eq? fields '(expected ...))))
  137. (when (pair? unexpected)
  138. (record-error 'name s "extraneous field initializers ~a"
  139. unexpected)))
  140. #`(make-struct/no-tail type
  141. #,@(map (lambda (field index)
  142. (or (field-inherited-value field)
  143. (if (innate-field? field)
  144. (wrap-field-value
  145. field (field-default-value field))
  146. #`(struct-ref #,orig-record
  147. #,index))))
  148. '(expected ...)
  149. (iota (length '(expected ...))))))
  150. (define (thunked-field? f)
  151. (memq (syntax->datum f) 'thunked))
  152. (define (delayed-field? f)
  153. (memq (syntax->datum f) 'delayed))
  154. (define (innate-field? f)
  155. (memq (syntax->datum f) 'innate))
  156. (define field-sanitizer
  157. (let ((lst (map (match-lambda
  158. ((f p)
  159. (list (syntax->datum f) p)))
  160. #'sanitizers)))
  161. (lambda (f)
  162. (or (and=> (assoc-ref lst (syntax->datum f)) car)
  163. #'(lambda (x) x)))))
  164. (define (wrap-field-value f value)
  165. (let* ((sanitizer (field-sanitizer f))
  166. (value #`(#,sanitizer #,value)))
  167. (cond ((thunked-field? f)
  168. #`(lambda (x)
  169. (syntax-parameterize ((#,this-identifier
  170. (lambda (s)
  171. (syntax-case s ()
  172. (id
  173. (identifier? #'id)
  174. #'x)))))
  175. #,value)))
  176. ((delayed-field? f)
  177. #`(delay #,value))
  178. (else value))))
  179. (define default-values
  180. ;; List of symbol/value tuples.
  181. (map (match-lambda
  182. ((f v)
  183. (list (syntax->datum f) v)))
  184. #'defaults))
  185. (define (field-default-value f)
  186. (car (assoc-ref default-values (syntax->datum f))))
  187. (define (field-bindings field+value)
  188. ;; Return field to value bindings, for use in 'let*' below.
  189. (map (lambda (field+value)
  190. (syntax-case field+value ()
  191. ((field value)
  192. #`(field
  193. #,(wrap-field-value #'field #'value)))))
  194. field+value))
  195. (syntax-case s (inherit expected ...)
  196. ((_ (inherit orig-record) (field value) (... ...))
  197. #`(let* #,(field-bindings #'((field value) (... ...)))
  198. #,(abi-check #'type abi-cookie)
  199. #,(record-inheritance #'orig-record
  200. #'((field value) (... ...)))))
  201. ((_ (field value) (... ...))
  202. (let ((fields (map syntax->datum #'(field (... ...)))))
  203. (define (field-value f)
  204. (or (find (lambda (x)
  205. (eq? f (syntax->datum x)))
  206. #'(field (... ...)))
  207. (wrap-field-value f (field-default-value f))))
  208. ;; Pass S to make sure source location info is preserved.
  209. (report-duplicate-field-specifier 'name s)
  210. (let ((fields (append fields (map car default-values))))
  211. (cond ((lset= eq? fields '(expected ...))
  212. #`(let* #,(field-bindings
  213. #'((field value) (... ...)))
  214. #,(abi-check #'type abi-cookie)
  215. (ctor #,@(map field-value '(expected ...)))))
  216. ((pair? (lset-difference eq? fields
  217. '(expected ...)))
  218. (record-error 'name s
  219. "extraneous field initializers ~a"
  220. (lset-difference eq? fields
  221. '(expected ...))))
  222. (else
  223. (record-error 'name s
  224. "missing field initializers ~a"
  225. (lset-difference eq?
  226. '(expected ...)
  227. fields)))))))
  228. ((_ bindings (... ...))
  229. ;; One of BINDINGS doesn't match the (field value) pattern.
  230. ;; Report precisely which one is faulty, instead of letting the
  231. ;; "source expression failed to match any pattern" error.
  232. (report-invalid-field-specifier 'name
  233. #'(bindings (... ...))
  234. s))))))))
  235. (define-syntax-rule (define-field-property-predicate predicate property)
  236. "Define PREDICATE as a procedure that takes a syntax object and, when passed
  237. a field specification, returns the field name if it has the given PROPERTY."
  238. (define (predicate s)
  239. (syntax-case s (property)
  240. ((field (property values (... ...)) _ (... ...))
  241. #'field)
  242. ((field _ properties (... ...))
  243. (predicate #'(field properties (... ...))))
  244. (_ #f))))
  245. (define-syntax define-record-type*
  246. (lambda (s)
  247. "Define the given record type such that an additional \"syntactic
  248. constructor\" is defined, which allows instances to be constructed with named
  249. field initializers, à la SRFI-35, as well as default values. An example use
  250. may look like this:
  251. (define-record-type* <thing> thing make-thing
  252. thing?
  253. this-thing
  254. (name thing-name (default \"chbouib\"))
  255. (port thing-port
  256. (default (current-output-port)) (thunked))
  257. (loc thing-location (innate) (default (current-source-location))))
  258. This example defines a macro 'thing' that can be used to instantiate records
  259. of this type:
  260. (thing
  261. (name \"foo\")
  262. (port (current-error-port)))
  263. The value of 'name' or 'port' could as well be omitted, in which case the
  264. default value specified in the 'define-record-type*' form is used:
  265. (thing)
  266. The 'port' field is \"thunked\", meaning that calls like '(thing-port x)' will
  267. actually compute the field's value in the current dynamic extent, which is
  268. useful when referring to fluids in a field's value. Furthermore, that thunk
  269. can access the record it belongs to via the 'this-thing' identifier.
  270. A field can also be marked as \"delayed\" instead of \"thunked\", in which
  271. case its value is effectively wrapped in a (delay …) form.
  272. A field can also have an associated \"sanitizer\", which is a procedure that
  273. takes a user-supplied field value and returns a \"sanitized\" value for the
  274. field:
  275. (define-record-type* <thing> thing make-thing
  276. thing?
  277. this-thing
  278. (name thing-name
  279. (sanitize (lambda (value)
  280. (cond ((string? value) value)
  281. ((symbol? value) (symbol->string value))
  282. (else (throw 'bad! value)))))))
  283. It is possible to copy an object 'x' created with 'thing' like this:
  284. (thing (inherit x) (name \"bar\"))
  285. This expression returns a new object equal to 'x' except for its 'name'
  286. field and its 'loc' field---the latter is marked as \"innate\", so it is not
  287. inherited."
  288. (define (field-default-value s)
  289. (syntax-case s (default)
  290. ((field (default val) _ ...)
  291. (list #'field #'val))
  292. ((field _ properties ...)
  293. (field-default-value #'(field properties ...)))
  294. (_ #f)))
  295. (define (field-sanitizer s)
  296. (syntax-case s (sanitize)
  297. ((field (sanitize proc) _ ...)
  298. (list #'field #'proc))
  299. ((field _ properties ...)
  300. (field-sanitizer #'(field properties ...)))
  301. (_ #f)))
  302. (define-field-property-predicate delayed-field? delayed)
  303. (define-field-property-predicate thunked-field? thunked)
  304. (define-field-property-predicate innate-field? innate)
  305. (define (wrapped-field? s)
  306. (or (thunked-field? s) (delayed-field? s)))
  307. (define (wrapped-field-accessor-name field)
  308. ;; Return the name (an unhygienic syntax object) of the "real"
  309. ;; getter for field, which is assumed to be a wrapped field.
  310. (syntax-case field ()
  311. ((field get properties ...)
  312. (let* ((getter (syntax->datum #'get))
  313. (real-getter (symbol-append '% getter '-real)))
  314. (datum->syntax #'get real-getter)))))
  315. (define (field-spec->srfi-9 field)
  316. ;; Convert a field spec of our style to a SRFI-9 field spec of the
  317. ;; form (field get).
  318. (syntax-case field ()
  319. ((name get properties ...)
  320. #`(name
  321. #,(if (wrapped-field? field)
  322. (wrapped-field-accessor-name field)
  323. #'get)))))
  324. (define (thunked-field-accessor-definition field)
  325. ;; Return the real accessor for FIELD, which is assumed to be a
  326. ;; thunked field.
  327. (syntax-case field ()
  328. ((name get _ ...)
  329. (with-syntax ((real-get (wrapped-field-accessor-name field)))
  330. #'(define-inlinable (get x)
  331. ;; The real value of that field is a thunk, so call it.
  332. ((real-get x) x))))))
  333. (define (delayed-field-accessor-definition field)
  334. ;; Return the real accessor for FIELD, which is assumed to be a
  335. ;; delayed field.
  336. (syntax-case field ()
  337. ((name get _ ...)
  338. (with-syntax ((real-get (wrapped-field-accessor-name field)))
  339. #'(define-inlinable (get x)
  340. ;; The real value of that field is a promise, so force it.
  341. (force (real-get x)))))))
  342. (define (compute-abi-cookie field-specs)
  343. ;; Compute an "ABI cookie" for the given FIELD-SPECS. We use
  344. ;; 'string-hash' because that's a better hash function that 'hash' on a
  345. ;; list of symbols.
  346. (syntax-case field-specs ()
  347. (((field get properties ...) ...)
  348. (string-hash (object->string
  349. (syntax->datum #'((field properties ...) ...)))
  350. (cond-expand
  351. (guile-3 (target-most-positive-fixnum))
  352. (else most-positive-fixnum))))))
  353. (syntax-case s ()
  354. ((_ type syntactic-ctor ctor pred
  355. this-identifier
  356. (field get properties ...) ...)
  357. (identifier? #'this-identifier)
  358. (let* ((field-spec #'((field get properties ...) ...))
  359. (thunked (filter-map thunked-field? field-spec))
  360. (delayed (filter-map delayed-field? field-spec))
  361. (innate (filter-map innate-field? field-spec))
  362. (defaults (filter-map field-default-value
  363. #'((field properties ...) ...)))
  364. (sanitizers (filter-map field-sanitizer
  365. #'((field properties ...) ...)))
  366. (cookie (compute-abi-cookie field-spec)))
  367. (with-syntax (((field-spec* ...)
  368. (map field-spec->srfi-9 field-spec))
  369. ((thunked-field-accessor ...)
  370. (filter-map (lambda (field)
  371. (and (thunked-field? field)
  372. (thunked-field-accessor-definition
  373. field)))
  374. field-spec))
  375. ((delayed-field-accessor ...)
  376. (filter-map (lambda (field)
  377. (and (delayed-field? field)
  378. (delayed-field-accessor-definition
  379. field)))
  380. field-spec)))
  381. #`(begin
  382. (define-record-type type
  383. (ctor field ...)
  384. pred
  385. field-spec* ...)
  386. (define #,(current-abi-identifier #'type)
  387. #,cookie)
  388. #,@(if (free-identifier=? #'this-identifier #'this-record)
  389. #'()
  390. #'((define-syntax-parameter this-identifier
  391. (lambda (s)
  392. "Return the record being defined. This macro may
  393. only be used in the context of the definition of a thunked field."
  394. (syntax-case s ()
  395. (id
  396. (identifier? #'id)
  397. (syntax-violation 'this-identifier
  398. "cannot be used outside \
  399. of a record instantiation"
  400. #'id)))))))
  401. thunked-field-accessor ...
  402. delayed-field-accessor ...
  403. (make-syntactic-constructor type syntactic-ctor ctor
  404. (field ...)
  405. #:abi-cookie #,cookie
  406. #:thunked #,thunked
  407. #:this-identifier #'this-identifier
  408. #:delayed #,delayed
  409. #:innate #,innate
  410. #:sanitizers #,sanitizers
  411. #:defaults #,defaults)))))
  412. ((_ type syntactic-ctor ctor pred
  413. (field get properties ...) ...)
  414. ;; When no 'this' identifier was specified, use 'this-record'.
  415. #'(define-record-type* type syntactic-ctor ctor pred
  416. this-record
  417. (field get properties ...) ...)))))
  418. (define* (alist->record alist make keys
  419. #:optional (multiple-value-keys '()))
  420. "Apply MAKE to the values associated with KEYS in ALIST. Items in KEYS that
  421. are also in MULTIPLE-VALUE-KEYS are considered to occur possibly multiple
  422. times in ALIST, and thus their value is a list."
  423. (let ((args (map (lambda (key)
  424. (if (member key multiple-value-keys)
  425. (filter-map (match-lambda
  426. ((k . v)
  427. (and (equal? k key) v)))
  428. alist)
  429. (assoc-ref alist key)))
  430. keys)))
  431. (apply make args)))
  432. (define (object->fields object fields port)
  433. "Write OBJECT (typically a record) as a series of recutils-style fields to
  434. PORT, according to FIELDS. FIELDS must be a list of field name/getter pairs."
  435. (let loop ((fields fields))
  436. (match fields
  437. (()
  438. object)
  439. (((field . get) rest ...)
  440. (format port "~a: ~a~%" field (get object))
  441. (loop rest)))))
  442. (define %recutils-field-charset
  443. ;; Valid characters starting a recutils field.
  444. ;; info "(recutils) Fields"
  445. (char-set-union char-set:upper-case
  446. char-set:lower-case
  447. (char-set #\%)))
  448. (define (recutils->alist port)
  449. "Read a recutils-style record from PORT and return it as a list of key/value
  450. pairs. Stop upon an empty line (after consuming it) or EOF."
  451. (let loop ((line (read-line port))
  452. (result '()))
  453. (cond ((eof-object? line)
  454. (reverse result))
  455. ((string-null? line)
  456. (if (null? result)
  457. (loop (read-line port) result) ; leading space: ignore it
  458. (reverse result))) ; end-of-record marker
  459. (else
  460. ;; Now check the first character of LINE, since that's what the
  461. ;; recutils manual says is enough.
  462. (let ((first (string-ref line 0)))
  463. (cond
  464. ((char-set-contains? %recutils-field-charset first)
  465. (let* ((colon (string-index line #\:))
  466. (field (string-take line colon))
  467. (value (string-trim (string-drop line (+ 1 colon)))))
  468. (loop (read-line port)
  469. (alist-cons field value result))))
  470. ((eqv? first #\#) ;info "(recutils) Comments"
  471. (loop (read-line port) result))
  472. ((eqv? first #\+) ;info "(recutils) Fields"
  473. (let ((new-line (if (string-prefix? "+ " line)
  474. (string-drop line 2)
  475. (string-drop line 1))))
  476. (match result
  477. (((field . value) rest ...)
  478. (loop (read-line port)
  479. `((,field . ,(string-append value "\n" new-line))
  480. ,@rest))))))
  481. (else
  482. (error "unmatched line" line))))))))
  483. (define-syntax match-record
  484. (syntax-rules ()
  485. "Bind each FIELD of a RECORD of the given TYPE to it's FIELD name.
  486. The current implementation does not support thunked and delayed fields."
  487. ((_ record type (field fields ...) body ...)
  488. (if (eq? (struct-vtable record) type)
  489. ;; TODO compute indices and report wrong-field-name errors at
  490. ;; expansion time
  491. ;; TODO support thunked and delayed fields
  492. (let ((field ((record-accessor type 'field) record)))
  493. (match-record record type (fields ...) body ...))
  494. (throw 'wrong-type-arg record)))
  495. ((_ record type () body ...)
  496. (begin body ...))))
  497. ;;; records.scm ends here