read-print.scm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2021-2023 Ludovic Courtès <ludo@gnu.org>
  3. ;;;
  4. ;;; This file is part of GNU Guix.
  5. ;;;
  6. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  7. ;;; under the terms of the GNU General Public License as published by
  8. ;;; the Free Software Foundation; either version 3 of the License, or (at
  9. ;;; your option) any later version.
  10. ;;;
  11. ;;; GNU Guix is distributed in the hope that it will be useful, but
  12. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;;; GNU General Public License for more details.
  15. ;;;
  16. ;;; You should have received a copy of the GNU General Public License
  17. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  18. (define-module (guix read-print)
  19. #:use-module (ice-9 control)
  20. #:use-module (ice-9 match)
  21. #:use-module (ice-9 rdelim)
  22. #:use-module (ice-9 vlist)
  23. #:use-module (srfi srfi-1)
  24. #:use-module (srfi srfi-26)
  25. #:use-module (srfi srfi-34)
  26. #:use-module (srfi srfi-35)
  27. #:use-module (guix i18n)
  28. #:use-module ((guix diagnostics)
  29. #:select (formatted-message
  30. &fix-hint &error-location
  31. location))
  32. #:export (pretty-print-with-comments
  33. pretty-print-with-comments/splice
  34. read-with-comments
  35. read-with-comments/sequence
  36. object->string*
  37. blank?
  38. vertical-space
  39. vertical-space?
  40. vertical-space-height
  41. canonicalize-vertical-space
  42. page-break
  43. page-break?
  44. comment
  45. comment?
  46. comment->string
  47. comment-margin?
  48. canonicalize-comment))
  49. ;;; Commentary:
  50. ;;;
  51. ;;; This module provides a comment-preserving reader and a comment-preserving
  52. ;;; pretty-printer smarter than (ice-9 pretty-print).
  53. ;;;
  54. ;;; Code:
  55. ;;;
  56. ;;; Comment-preserving reader.
  57. ;;;
  58. (define <blank>
  59. ;; The parent class for "blanks".
  60. (make-record-type '<blank> '()
  61. (lambda (obj port)
  62. (format port "#<blank ~a>"
  63. (number->string (object-address obj) 16)))
  64. #:extensible? #t))
  65. (define blank? (record-predicate <blank>))
  66. (define <vertical-space>
  67. (make-record-type '<vertical-space> '(height)
  68. #:parent <blank>
  69. #:extensible? #f))
  70. (define vertical-space? (record-predicate <vertical-space>))
  71. (define vertical-space (record-type-constructor <vertical-space>))
  72. (define vertical-space-height (record-accessor <vertical-space> 'height))
  73. (define canonicalize-vertical-space
  74. (let ((unit (vertical-space 1)))
  75. (lambda (space)
  76. "Return a vertical space corresponding to a single blank line."
  77. unit)))
  78. (define <page-break>
  79. (make-record-type '<page-break> '()
  80. #:parent <blank>
  81. #:extensible? #f))
  82. (define page-break? (record-predicate <page-break>))
  83. (define page-break
  84. (let ((break ((record-type-constructor <page-break>))))
  85. (lambda ()
  86. break)))
  87. (define <comment>
  88. ;; Comments.
  89. (make-record-type '<comment> '(str margin?)
  90. #:parent <blank>
  91. #:extensible? #f))
  92. (define comment? (record-predicate <comment>))
  93. (define string->comment (record-type-constructor <comment>))
  94. (define comment->string (record-accessor <comment> 'str))
  95. (define comment-margin? (record-accessor <comment> 'margin?))
  96. (define* (comment str #:optional margin?)
  97. "Return a new comment made from STR. When MARGIN? is true, return a margin
  98. comment; otherwise return a line comment. STR must start with a semicolon and
  99. end with newline, otherwise an error is raised."
  100. (when (or (string-null? str)
  101. (not (eqv? #\; (string-ref str 0)))
  102. (not (string-suffix? "\n" str)))
  103. (raise (condition
  104. (&message (message "invalid comment string")))))
  105. (string->comment str margin?))
  106. (define char-set:whitespace-sans-page-break
  107. ;; White space, excluding #\page.
  108. (char-set-difference char-set:whitespace (char-set #\page)))
  109. (define (space? chr)
  110. "Return true if CHR is white space, except for page breaks."
  111. (char-set-contains? char-set:whitespace-sans-page-break chr))
  112. (define (read-vertical-space port)
  113. "Read from PORT until a non-vertical-space character is met, and return a
  114. single <vertical-space> record."
  115. (let loop ((height 1))
  116. (match (read-char port)
  117. (#\newline (loop (+ 1 height)))
  118. ((? eof-object?) (vertical-space height))
  119. ((? space?) (loop height))
  120. (chr (unread-char chr port) (vertical-space height)))))
  121. (define (read-until-end-of-line port)
  122. "Read white space from PORT until the end of line, included."
  123. (let loop ()
  124. (match (read-char port)
  125. (#\newline #t)
  126. ((? eof-object?) #t)
  127. ((? space?) (loop))
  128. (chr (unread-char chr port)))))
  129. (define* (read-with-comments port #:key (blank-line? #t))
  130. "Like 'read', but include <blank> objects when they're encountered. When
  131. BLANK-LINE? is true, assume PORT is at the beginning of a new line."
  132. ;; Note: Instead of implementing this functionality in 'read' proper, which
  133. ;; is the best approach long-term, this code is a layer on top of 'read',
  134. ;; such that we don't have to rely on a specific Guile version.
  135. (define dot (list 'dot))
  136. (define (dot? x) (eq? x dot))
  137. (define (missing-closing-paren-error)
  138. (raise (make-compound-condition
  139. (formatted-message (G_ "unexpected end of file"))
  140. (condition
  141. (&error-location
  142. (location (match (port-filename port)
  143. (#f #f)
  144. (file (location file
  145. (port-line port)
  146. (port-column port))))))
  147. (&fix-hint
  148. (hint (G_ "Did you forget a closing parenthesis?")))))))
  149. (define (reverse/dot lst)
  150. ;; Reverse LST and make it an improper list if it contains DOT.
  151. (let loop ((result '())
  152. (lst lst))
  153. (match lst
  154. (() result)
  155. (((? dot?) . rest)
  156. (if (pair? rest)
  157. (let ((dotted (reverse rest)))
  158. (set-cdr! (last-pair dotted) (car result))
  159. dotted)
  160. (car result)))
  161. ((x . rest) (loop (cons x result) rest)))))
  162. (let loop ((blank-line? blank-line?)
  163. (return (const 'unbalanced)))
  164. (match (read-char port)
  165. ((? eof-object? eof)
  166. eof) ;oops!
  167. (chr
  168. (cond ((eqv? chr #\newline)
  169. (if blank-line?
  170. (read-vertical-space port)
  171. (loop #t return)))
  172. ((eqv? chr #\page)
  173. ;; Assume that a page break is on a line of its own and read
  174. ;; subsequent white space and newline.
  175. (read-until-end-of-line port)
  176. (page-break))
  177. ((char-set-contains? char-set:whitespace chr)
  178. (loop blank-line? return))
  179. ((memv chr '(#\( #\[))
  180. (let/ec return
  181. (let liip ((lst '()))
  182. (define item
  183. (loop (match lst
  184. (((? blank?) . _) #t)
  185. (_ #f))
  186. (lambda ()
  187. (return (reverse/dot lst)))))
  188. (if (eof-object? item)
  189. (missing-closing-paren-error)
  190. (liip (cons item lst))))))
  191. ((memv chr '(#\) #\]))
  192. (return))
  193. ((eq? chr #\')
  194. (list 'quote (loop #f return)))
  195. ((eq? chr #\`)
  196. (list 'quasiquote (loop #f return)))
  197. ((eq? chr #\#)
  198. (match (read-char port)
  199. (#\~ (list 'gexp (loop #f return)))
  200. (#\$ (list (match (peek-char port)
  201. (#\@
  202. (read-char port) ;consume
  203. 'ungexp-splicing)
  204. (_
  205. 'ungexp))
  206. (loop #f return)))
  207. (#\+ (list (match (peek-char port)
  208. (#\@
  209. (read-char port) ;consume
  210. 'ungexp-native-splicing)
  211. (_
  212. 'ungexp-native))
  213. (loop #f return)))
  214. (chr
  215. (unread-char chr port)
  216. (unread-char #\# port)
  217. (read port))))
  218. ((eq? chr #\,)
  219. (list (match (peek-char port)
  220. (#\@
  221. (read-char port)
  222. 'unquote-splicing)
  223. (_
  224. 'unquote))
  225. (loop #f return)))
  226. ((eqv? chr #\;)
  227. (unread-char chr port)
  228. (string->comment (read-line port 'concat)
  229. (not blank-line?)))
  230. (else
  231. (unread-char chr port)
  232. (match (read port)
  233. ((and token '#{.}#)
  234. (if (eq? chr #\.) dot token))
  235. (token token))))))))
  236. (define (read-with-comments/sequence port)
  237. "Read from PORT until the end-of-file is reached and return the list of
  238. expressions and blanks that were read."
  239. (let loop ((lst '())
  240. (blank-line? #t))
  241. (match (read-with-comments port #:blank-line? blank-line?)
  242. ((? eof-object?)
  243. (reverse! lst))
  244. ((? blank? blank)
  245. (loop (cons blank lst) #t))
  246. (exp
  247. (loop (cons exp lst) #f)))))
  248. ;;;
  249. ;;; Comment-preserving pretty-printer.
  250. ;;;
  251. (define-syntax vhashq
  252. (syntax-rules (quote)
  253. ((_) vlist-null)
  254. ((_ (key (quote (lst ...))) rest ...)
  255. (vhash-consq key '(lst ...) (vhashq rest ...)))
  256. ((_ (key value) rest ...)
  257. (vhash-consq key '((() . value)) (vhashq rest ...)))))
  258. (define %special-forms
  259. ;; Forms that are indented specially. The number is meant to be understood
  260. ;; like Emacs' 'scheme-indent-function' symbol property. When given an
  261. ;; alist instead of a number, the alist gives "context" in which the symbol
  262. ;; is a special form; for instance, context (modify-phases) means that the
  263. ;; symbol must appear within a (modify-phases ...) expression.
  264. (vhashq
  265. ('begin 1)
  266. ('case 2)
  267. ('cond 1)
  268. ('lambda 2)
  269. ('lambda* 2)
  270. ('match-lambda 1)
  271. ('match-lambda* 1)
  272. ('define 2)
  273. ('define* 2)
  274. ('define-public 2)
  275. ('define*-public 2)
  276. ('define-syntax 2)
  277. ('define-syntax-rule 2)
  278. ('define-module 2)
  279. ('define-gexp-compiler 2)
  280. ('define-record-type 2)
  281. ('define-record-type* 4)
  282. ('define-configuration 2)
  283. ('package/inherit 2)
  284. ('let 2)
  285. ('let* 2)
  286. ('letrec 2)
  287. ('letrec* 2)
  288. ('match 2)
  289. ('match-record 3)
  290. ('when 2)
  291. ('unless 2)
  292. ('package 1)
  293. ('origin 1)
  294. ('channel 1)
  295. ('modify-inputs 2)
  296. ('modify-phases 2)
  297. ('add-after '(((modify-phases) . 3)))
  298. ('add-before '(((modify-phases) . 3)))
  299. ('replace '(((modify-phases) . 2))) ;different from 'modify-inputs'
  300. ('substitute* 2)
  301. ('substitute-keyword-arguments 2)
  302. ('call-with-input-file 2)
  303. ('call-with-output-file 2)
  304. ('with-output-to-file 2)
  305. ('with-input-from-file 2)
  306. ('with-directory-excursion 2)
  307. ('wrap-program 2)
  308. ('wrap-script 2)
  309. ;; (gnu system) and (gnu services).
  310. ('operating-system 1)
  311. ('bootloader-configuration 1)
  312. ('mapped-device 1)
  313. ('file-system 1)
  314. ('swap-space 1)
  315. ('user-account 1)
  316. ('user-group 1)
  317. ('setuid-program 1)
  318. ('modify-services 2)
  319. ;; (gnu home).
  320. ('home-environment 1)))
  321. (define %newline-forms
  322. ;; List heads that must be followed by a newline. The second argument is
  323. ;; the context in which they must appear. This is similar to a special form
  324. ;; of 1, except that indent is 1 instead of 2 columns.
  325. (vhashq
  326. ('arguments '(package))
  327. ('sha256 '(origin source package))
  328. ('base32 '(sha256 origin))
  329. ('git-reference '(uri origin source))
  330. ('search-paths '(package))
  331. ('native-search-paths '(package))
  332. ('search-path-specification '())
  333. ('services '(operating-system))
  334. ('set-xorg-configuration '())
  335. ('services '(home-environment))
  336. ('home-bash-configuration '(service))
  337. ('introduction '(channel))))
  338. (define (prefix? candidate lst)
  339. "Return true if CANDIDATE is a prefix of LST."
  340. (let loop ((candidate candidate)
  341. (lst lst))
  342. (match candidate
  343. (() #t)
  344. ((head1 . rest1)
  345. (match lst
  346. (() #f)
  347. ((head2 . rest2)
  348. (and (equal? head1 head2)
  349. (loop rest1 rest2))))))))
  350. (define (special-form-lead symbol context)
  351. "If SYMBOL is a special form in the given CONTEXT, return its number of
  352. arguments; otherwise return #f. CONTEXT is a stack of symbols lexically
  353. surrounding SYMBOL."
  354. (match (vhash-assq symbol %special-forms)
  355. (#f #f)
  356. ((_ . alist)
  357. (any (match-lambda
  358. ((prefix . level)
  359. (and (prefix? prefix context) (- level 1))))
  360. alist))))
  361. (define (newline-form? symbol context)
  362. "Return true if parenthesized expressions starting with SYMBOL must be
  363. followed by a newline."
  364. (let ((matches (vhash-foldq* cons '() symbol %newline-forms)))
  365. (find (cut prefix? <> context)
  366. matches)))
  367. (define (escaped-string str)
  368. "Return STR with backslashes and double quotes escaped. Everything else, in
  369. particular newlines, is left as is."
  370. (list->string
  371. `(#\"
  372. ,@(string-fold-right (lambda (chr lst)
  373. (match chr
  374. (#\" (cons* #\\ #\" lst))
  375. (#\\ (cons* #\\ #\\ lst))
  376. (_ (cons chr lst))))
  377. '()
  378. str)
  379. #\")))
  380. (define %natural-whitespace-string-forms
  381. ;; When a string has one of these forms as its parent, only double quotes
  382. ;; and backslashes are escaped; newlines, tabs, etc. are left as-is.
  383. '(synopsis description G_ N_))
  384. (define (printed-string str context)
  385. "Return the read syntax for STR depending on CONTEXT."
  386. (define (preserve-newlines? str)
  387. (and (> (string-length str) 40)
  388. (string-index str #\newline)))
  389. (match context
  390. (()
  391. (if (preserve-newlines? str)
  392. (escaped-string str)
  393. (object->string str)))
  394. ((head . _)
  395. (if (or (memq head %natural-whitespace-string-forms)
  396. (preserve-newlines? str))
  397. (escaped-string str)
  398. (object->string str)))))
  399. (define (string-width str)
  400. "Return the \"width\" of STR--i.e., the width of the longest line of STR."
  401. (apply max (map string-length (string-split str #\newline))))
  402. (define (canonicalize-comment comment indent)
  403. "Canonicalize COMMENT, which is to be printed at INDENT, ensuring it has the
  404. \"right\" number of leading semicolons."
  405. (if (zero? indent)
  406. comment ;leave top-level comments unchanged
  407. (let ((line (string-trim-both
  408. (string-trim (comment->string comment) (char-set #\;)))))
  409. (string->comment (string-append
  410. (if (comment-margin? comment)
  411. ";"
  412. (if (string-null? line)
  413. ";;" ;no trailing space
  414. ";; "))
  415. line "\n")
  416. (comment-margin? comment)))))
  417. (define %not-newline
  418. (char-set-complement (char-set #\newline)))
  419. (define (print-multi-line-comment str indent port)
  420. "Print to PORT STR as a multi-line comment, with INDENT spaces preceding
  421. each line except the first one (they're assumed to be already there)."
  422. ;; While 'read-with-comments' only returns one-line comments, user-provided
  423. ;; comments might span multiple lines, which is why this is necessary.
  424. (let loop ((lst (string-tokenize str %not-newline)))
  425. (match lst
  426. (() #t)
  427. ((last)
  428. (display last port)
  429. (newline port))
  430. ((head tail ...)
  431. (display head port)
  432. (newline port)
  433. (display (make-string indent #\space) port)
  434. (loop tail)))))
  435. (define %integer-forms
  436. ;; Forms that take an integer as their argument, where said integer should
  437. ;; be printed in base other than decimal base.
  438. (letrec-syntax ((vhashq (syntax-rules ()
  439. ((_) vlist-null)
  440. ((_ (key value) rest ...)
  441. (vhash-consq key value (vhashq rest ...))))))
  442. (vhashq
  443. ('chmod 8)
  444. ('umask 8)
  445. ('mkdir 8)
  446. ('mkstemp 8)
  447. ('logand 16)
  448. ('logior 16)
  449. ('logxor 16)
  450. ('lognot 16))))
  451. (define (integer->string integer context)
  452. "Render INTEGER as a string using a base suitable based on CONTEXT."
  453. (define (form-base form)
  454. (match (vhash-assq form %integer-forms)
  455. (#f 10)
  456. ((_ . base) base)))
  457. (define (octal? form)
  458. (= 8 (form-base form)))
  459. (define base
  460. (match context
  461. ((head . tail)
  462. (match (form-base head)
  463. (8 8)
  464. (16 (if (any octal? tail) 8 16))
  465. (10 10)))
  466. (_ 10)))
  467. (string-append (match base
  468. (10 "")
  469. (16 "#x")
  470. (8 "#o"))
  471. (number->string integer base)))
  472. (define %special-non-extended-symbols
  473. ;; Special symbols that can be written without the #{...}# notation for
  474. ;; extended symbols: 1+, 1-, 123/, etc.
  475. (make-regexp "^[0-9]+[[:graph:]]+$" regexp/icase))
  476. (define (symbol->display-string symbol context)
  477. "Return the most appropriate representation of SYMBOL, resorting to extended
  478. symbol notation only when strictly necessary."
  479. (let ((str (symbol->string symbol)))
  480. (if (regexp-exec %special-non-extended-symbols str)
  481. str ;no need for the #{...}# notation
  482. (object->string symbol))))
  483. (define* (pretty-print-with-comments port obj
  484. #:key
  485. (format-comment
  486. (lambda (comment indent) comment))
  487. (format-vertical-space identity)
  488. (indent 0)
  489. (max-width 78)
  490. (long-list 5))
  491. "Pretty-print OBJ to PORT, attempting to at most MAX-WIDTH character columns
  492. and assuming the current column is INDENT. Comments present in OBJ are
  493. included in the output.
  494. Lists longer than LONG-LIST are written as one element per line. Comments are
  495. passed through FORMAT-COMMENT before being emitted; a useful value for
  496. FORMAT-COMMENT is 'canonicalize-comment'. Vertical space is passed through
  497. FORMAT-VERTICAL-SPACE; a useful value of 'canonicalize-vertical-space'."
  498. (define (list-of-lists? head tail)
  499. ;; Return true if HEAD and TAIL denote a list of lists--e.g., a list of
  500. ;; 'let' bindings.
  501. (match head
  502. ((thing _ ...) ;proper list
  503. (and (not (memq thing
  504. '(quote quasiquote unquote unquote-splicing)))
  505. (pair? tail)))
  506. (_ #f)))
  507. (define (starts-with-line-comment? lst)
  508. ;; Return true if LST starts with a line comment.
  509. (match lst
  510. ((x . _) (and (comment? x) (not (comment-margin? x))))
  511. (_ #f)))
  512. (let loop ((indent indent)
  513. (column indent)
  514. (delimited? #t) ;true if comes after a delimiter
  515. (context '()) ;list of "parent" symbols
  516. (obj obj))
  517. (define (print-sequence context indent column lst delimited?)
  518. (define long?
  519. (> (length lst) long-list))
  520. (let print ((lst lst)
  521. (first? #t)
  522. (delimited? delimited?)
  523. (column column))
  524. (match lst
  525. (()
  526. column)
  527. ((item . tail)
  528. (define newline?
  529. ;; Insert a newline if ITEM is itself a list, or if TAIL is long,
  530. ;; but only if ITEM is not the first item. Also insert a newline
  531. ;; before a keyword.
  532. (and (or (pair? item) long?
  533. (and (keyword? item)
  534. (not (eq? item #:allow-other-keys))))
  535. (not first?) (not delimited?)
  536. (not (blank? item))))
  537. (when newline?
  538. (newline port)
  539. (display (make-string indent #\space) port))
  540. (let ((column (if newline? indent column)))
  541. (print tail
  542. (keyword? item) ;keep #:key value next to one another
  543. (blank? item)
  544. (loop indent column
  545. (or newline? delimited?)
  546. context
  547. item)))))))
  548. (define (sequence-would-protrude? indent lst)
  549. ;; Return true if elements of LST written at INDENT would protrude
  550. ;; beyond MAX-WIDTH. This is implemented as a cheap test with false
  551. ;; negatives to avoid actually rendering all of LST.
  552. (find (match-lambda
  553. ((? string? str)
  554. (>= (+ (string-width str) 2 indent) max-width))
  555. ((? symbol? symbol)
  556. (>= (+ (string-width (symbol->display-string symbol context))
  557. indent)
  558. max-width))
  559. ((? boolean?)
  560. (>= (+ 2 indent) max-width))
  561. (()
  562. (>= (+ 2 indent) max-width))
  563. (_ ;don't know
  564. #f))
  565. lst))
  566. (define (special-form? head)
  567. (special-form-lead head context))
  568. (match obj
  569. ((? comment? comment)
  570. (if (comment-margin? comment)
  571. (begin
  572. (display " " port)
  573. (display (comment->string (format-comment comment indent))
  574. port))
  575. (begin
  576. ;; When already at the beginning of a line, for example because
  577. ;; COMMENT follows a margin comment, no need to emit a newline.
  578. (unless (= column indent)
  579. (newline port)
  580. (display (make-string indent #\space) port))
  581. (print-multi-line-comment (comment->string
  582. (format-comment comment indent))
  583. indent port)))
  584. (display (make-string indent #\space) port)
  585. indent)
  586. ((? vertical-space? space)
  587. (unless delimited? (newline port))
  588. (let loop ((i (vertical-space-height (format-vertical-space space))))
  589. (unless (zero? i)
  590. (newline port)
  591. (loop (- i 1))))
  592. (display (make-string indent #\space) port)
  593. indent)
  594. ((? page-break?)
  595. (unless delimited? (newline port))
  596. (display #\page port)
  597. (newline port)
  598. (display (make-string indent #\space) port)
  599. indent)
  600. (('quote lst)
  601. (unless delimited? (display " " port))
  602. (display "'" port)
  603. (loop indent (+ column (if delimited? 1 2)) #t context lst))
  604. (('quasiquote lst)
  605. (unless delimited? (display " " port))
  606. (display "`" port)
  607. (loop indent (+ column (if delimited? 1 2)) #t context lst))
  608. (('unquote lst)
  609. (unless delimited? (display " " port))
  610. (display "," port)
  611. (loop indent (+ column (if delimited? 1 2)) #t context lst))
  612. (('unquote-splicing lst)
  613. (unless delimited? (display " " port))
  614. (display ",@" port)
  615. (loop indent (+ column (if delimited? 2 3)) #t context lst))
  616. (('gexp lst)
  617. (unless delimited? (display " " port))
  618. (display "#~" port)
  619. (loop indent (+ column (if delimited? 2 3)) #t context lst))
  620. (('ungexp obj)
  621. (unless delimited? (display " " port))
  622. (display "#$" port)
  623. (loop indent (+ column (if delimited? 2 3)) #t context obj))
  624. (('ungexp-native obj)
  625. (unless delimited? (display " " port))
  626. (display "#+" port)
  627. (loop indent (+ column (if delimited? 2 3)) #t context obj))
  628. (('ungexp-splicing lst)
  629. (unless delimited? (display " " port))
  630. (display "#$@" port)
  631. (loop indent (+ column (if delimited? 3 4)) #t context lst))
  632. (('ungexp-native-splicing lst)
  633. (unless delimited? (display " " port))
  634. (display "#+@" port)
  635. (loop indent (+ column (if delimited? 3 4)) #t context lst))
  636. (((? special-form? head) arguments ...)
  637. ;; Special-case 'let', 'lambda', 'modify-inputs', etc. so the second
  638. ;; and following arguments are less indented.
  639. (let* ((lead (special-form-lead head context))
  640. (context (cons head context))
  641. (head (symbol->display-string head (cdr context)))
  642. (total (length arguments)))
  643. (unless delimited? (display " " port))
  644. (display "(" port)
  645. (display head port)
  646. (unless (zero? lead)
  647. (display " " port))
  648. ;; Print the first LEAD arguments.
  649. (let* ((indent (+ column 2
  650. (if delimited? 0 1)))
  651. (column (+ column 1
  652. (if (zero? lead) 0 1)
  653. (if delimited? 0 1)
  654. (string-length head)))
  655. (initial-indent column))
  656. (define new-column
  657. (let inner ((n lead)
  658. (arguments (take arguments (min lead total)))
  659. (column column))
  660. (if (zero? n)
  661. (begin
  662. (newline port)
  663. (display (make-string indent #\space) port)
  664. indent)
  665. (match arguments
  666. (() column)
  667. ((head . tail)
  668. (inner (- n 1) tail
  669. (loop initial-indent column
  670. (= n lead)
  671. context
  672. head)))))))
  673. ;; Print the remaining arguments.
  674. (let ((column (print-sequence
  675. context indent new-column
  676. (drop arguments (min lead total))
  677. #t)))
  678. (display ")" port)
  679. (+ column 1)))))
  680. ((head tail ...)
  681. (let* ((overflow? (>= column max-width))
  682. (column (if overflow?
  683. (+ indent 1)
  684. (+ column (if delimited? 1 2))))
  685. (newline? (or (newline-form? head context)
  686. (list-of-lists? head tail) ;'let' bindings
  687. (starts-with-line-comment? tail)))
  688. (context (cons head context)))
  689. (if overflow?
  690. (begin
  691. (newline port)
  692. (display (make-string indent #\space) port))
  693. (unless delimited? (display " " port)))
  694. (display "(" port)
  695. (let* ((new-column (loop column column #t context head))
  696. (indent (if (or (>= new-column max-width)
  697. (not (symbol? head))
  698. (sequence-would-protrude?
  699. (+ new-column 1) tail)
  700. newline?)
  701. column
  702. (+ new-column 1))))
  703. (when newline?
  704. ;; Insert a newline right after HEAD.
  705. (newline port)
  706. (display (make-string indent #\space) port))
  707. (let ((column
  708. (print-sequence context indent
  709. (if newline? indent new-column)
  710. tail newline?)))
  711. (display ")" port)
  712. (+ column 1)))))
  713. (_
  714. (let* ((str (cond ((string? obj)
  715. (printed-string obj context))
  716. ((integer? obj)
  717. (integer->string obj context))
  718. ((symbol? obj)
  719. (symbol->display-string obj context))
  720. (else
  721. (object->string obj))))
  722. (len (string-width str)))
  723. (if (and (> (+ column 1 len) max-width)
  724. (not delimited?))
  725. (begin
  726. (newline port)
  727. (display (make-string indent #\space) port)
  728. (display str port)
  729. (+ indent len))
  730. (begin
  731. (unless delimited? (display " " port))
  732. (display str port)
  733. (+ column (if delimited? 0 1) len))))))))
  734. (define (object->string* obj indent . args)
  735. "Pretty-print OBJ with INDENT columns as the initial indent. ARGS are
  736. passed as-is to 'pretty-print-with-comments'."
  737. (call-with-output-string
  738. (lambda (port)
  739. (apply pretty-print-with-comments port obj
  740. #:indent indent
  741. args))))
  742. (define* (pretty-print-with-comments/splice port lst
  743. #:rest rest)
  744. "Write to PORT the expressions and blanks listed in LST."
  745. (for-each (lambda (exp)
  746. (apply pretty-print-with-comments port exp rest)
  747. (unless (blank? exp)
  748. (newline port)))
  749. lst))