records.scm 21 KB

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