lisp-utils.scm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2016, 2017 Andy Patterson <ajpatter@uwaterloo.ca>
  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 build lisp-utils)
  19. #:use-module (ice-9 format)
  20. #:use-module (ice-9 hash-table)
  21. #:use-module (ice-9 match)
  22. #:use-module (ice-9 regex)
  23. #:use-module (srfi srfi-1)
  24. #:use-module (srfi srfi-26)
  25. #:use-module (guix build utils)
  26. #:export (%lisp
  27. %lisp-type
  28. %source-install-prefix
  29. lisp-eval-program
  30. compile-system
  31. test-system
  32. replace-escaped-macros
  33. generate-executable-wrapper-system
  34. generate-executable-entry-point
  35. generate-executable-for-system
  36. %bundle-install-prefix
  37. bundle-asd-file
  38. wrap-output-translations
  39. prepend-to-source-registry
  40. build-program
  41. build-image
  42. make-asd-file
  43. valid-char-set
  44. normalize-string
  45. library-output))
  46. ;;; Commentary:
  47. ;;;
  48. ;;; Tools to evaluate lisp programs within a lisp session, generate wrapper
  49. ;;; systems for executables. Compile, test, and produce images for systems and
  50. ;;; programs, and link them with their dependencies.
  51. ;;;
  52. ;;; Code:
  53. (define %lisp
  54. ;; File name of the Lisp compiler.
  55. (make-parameter "lisp"))
  56. (define %lisp-type
  57. ;; String representing the class of implementation being used.
  58. (make-parameter "lisp"))
  59. ;; The common parent for Lisp source files, as will as the symbolic
  60. ;; link farm for system definition (.asd) files.
  61. (define %source-install-prefix "/share/common-lisp")
  62. (define (%bundle-install-prefix)
  63. (string-append %source-install-prefix "/" (%lisp-type) "-bundle-systems"))
  64. (define (library-output outputs)
  65. "If a `lib' output exists, build things there. Otherwise use `out'."
  66. (or (assoc-ref outputs "lib") (assoc-ref outputs "out")))
  67. ;; See nix/libstore/store-api.cc#checkStoreName.
  68. (define valid-char-set
  69. (string->char-set
  70. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+-._?="))
  71. (define (normalize-string str)
  72. "Replace invalid characters in STR with a hyphen."
  73. (string-join (string-tokenize str valid-char-set) "-"))
  74. (define (normalize-dependency dependency)
  75. "Normalize the name of DEPENDENCY. Handles dependency definitions of the
  76. dependency-def form described by
  77. <https://common-lisp.net/project/asdf/asdf.html#The-defsystem-grammar>.
  78. Assume that any symbols in DEPENDENCY will be in upper-case."
  79. (match dependency
  80. ((':VERSION name rest ...)
  81. `(:version ,(normalize-string name) ,@rest))
  82. ((':FEATURE feature-specification dependency-specification)
  83. `(:feature
  84. ,feature-specification
  85. ,(normalize-dependency dependency-specification)))
  86. ((? string? name) (normalize-string name))
  87. (require-specification require-specification)))
  88. (define (inputs->asd-file-map inputs)
  89. "Produce a hash table of the form (system . asd-file), where system is the
  90. name of an ASD system, and asd-file is the full path to its definition."
  91. (alist->hash-table
  92. (filter-map
  93. (match-lambda
  94. ((_ . path)
  95. (let ((prefix (string-append path (%bundle-install-prefix))))
  96. (and (directory-exists? prefix)
  97. (match (find-files prefix "\\.asd$")
  98. ((asd-file)
  99. (cons
  100. (string-drop-right (basename asd-file) 4) ; drop ".asd"
  101. asd-file))
  102. (_ #f))))))
  103. inputs)))
  104. (define (wrap-output-translations translations)
  105. `(:output-translations
  106. ,@translations
  107. :inherit-configuration))
  108. (define (lisp-eval-program program)
  109. "Evaluate PROGRAM with a given LISP implementation."
  110. (define invocation (lisp-invocation program))
  111. (format #t "Invoking ~a: ~{~s ~}~%" (%lisp-type) invocation)
  112. (apply invoke invocation))
  113. (define (spread-statements program argument-name)
  114. "Return a list with the statements from PROGRAM spread between
  115. ARGUMENT-NAME, a string representing the argument a lisp implementation uses
  116. to accept statements to be evaluated before starting."
  117. (append-map (lambda (statement)
  118. (list argument-name (format #f "~S" statement)))
  119. program))
  120. (define (lisp-invocation program)
  121. "Return a list of arguments for system* determining how to invoke LISP
  122. with PROGRAM."
  123. (match (%lisp-type)
  124. ("sbcl" `(,(%lisp) "--non-interactive"
  125. ,@(spread-statements program "--eval")))
  126. ("ecl" `(,(%lisp)
  127. ,@(spread-statements program "--eval")
  128. "--eval" "(quit)"))
  129. (_ (error "The LISP provided is not supported at this time."))))
  130. (define (asdf-load-all systems)
  131. (map (lambda (system)
  132. `(asdf:load-system ,system))
  133. systems))
  134. (define (compile-system system asd-file)
  135. "Use a lisp implementation to compile SYSTEM using asdf. Load ASD-FILE
  136. first."
  137. (lisp-eval-program
  138. `((require :asdf)
  139. (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
  140. (asdf:operate 'asdf:compile-bundle-op ,system))))
  141. (define (system-dependencies system asd-file)
  142. "Return the dependencies of SYSTEM, as reported by
  143. asdf:system-depends-on. First load the system's ASD-FILE."
  144. (define deps-file ".deps.sexp")
  145. (define program
  146. `((require :asdf)
  147. (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
  148. (with-open-file
  149. (stream ,deps-file :direction :output)
  150. (format stream
  151. "~s~%"
  152. (asdf:system-depends-on
  153. (asdf:find-system ,system))))))
  154. (dynamic-wind
  155. (lambda _
  156. (lisp-eval-program program))
  157. (lambda _
  158. (call-with-input-file deps-file read))
  159. (lambda _
  160. (when (file-exists? deps-file)
  161. (delete-file deps-file)))))
  162. (define (compiled-system system)
  163. (let ((system (basename system))) ; this is how asdf handles slashes
  164. (match (%lisp-type)
  165. ("sbcl" (string-append system "--system"))
  166. (_ system))))
  167. (define* (generate-system-definition system
  168. #:key version dependencies)
  169. `(asdf:defsystem
  170. ,(normalize-string system)
  171. :class asdf/bundle:prebuilt-system
  172. :version ,version
  173. :depends-on ,dependencies
  174. :components ((:compiled-file ,(compiled-system system)))
  175. ,@(if (string=? "ecl" (%lisp-type))
  176. `(:lib ,(string-append system ".a"))
  177. '())))
  178. (define (test-system system asd-file test-asd-file)
  179. "Use a lisp implementation to test SYSTEM using asdf. Load ASD-FILE first.
  180. Also load TEST-ASD-FILE if necessary."
  181. (lisp-eval-program
  182. `((require :asdf)
  183. (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
  184. ,@(if test-asd-file
  185. `((asdf:load-asd (truename ,test-asd-file)))
  186. ;; Try some likely files.
  187. (map (lambda (file)
  188. `(when (uiop:file-exists-p ,file)
  189. (asdf:load-asd (truename ,file))))
  190. (list
  191. (string-append system "-tests.asd")
  192. (string-append system "-test.asd")
  193. "tests.asd"
  194. "test.asd")))
  195. (asdf:test-system ,system))))
  196. (define (string->lisp-keyword . strings)
  197. "Return a lisp keyword for the concatenation of STRINGS."
  198. (string->symbol (apply string-append ":" strings)))
  199. (define* (generate-executable-for-system type system #:key compress?)
  200. "Use LISP to generate an executable, whose TYPE can be 'asdf:image-op or
  201. 'asdf:program-op. The latter will always be standalone. Depends on having
  202. created a \"SYSTEM-exec\" system which contains the entry program."
  203. (lisp-eval-program
  204. `((require :asdf)
  205. ;; Only SBCL supports compression as of 2019-09-02.
  206. ,(if (and compress? (string=? (%lisp-type) "sbcl"))
  207. '(defmethod asdf:perform ((o asdf:image-op) (c asdf:system))
  208. (uiop:dump-image (asdf:output-file o c)
  209. :executable t
  210. :compression t))
  211. '())
  212. (asdf:operate ',type ,(string-append system "-exec")))))
  213. (define (generate-executable-wrapper-system system dependencies)
  214. "Generates a system which can be used by asdf to produce an image or program
  215. inside the current directory. The image or program will contain
  216. DEPENDENCIES."
  217. (with-output-to-file (string-append system "-exec.asd")
  218. (lambda _
  219. (format #t "~y~%"
  220. `(defsystem ,(string->lisp-keyword system "-exec")
  221. :entry-point ,(string-append system "-exec:main")
  222. :depends-on (:uiop
  223. ,@(map string->lisp-keyword
  224. dependencies))
  225. :components ((:file ,(string-append system "-exec"))))))))
  226. (define (generate-executable-entry-point system entry-program)
  227. "Generates an entry point program from the list of lisp statements
  228. ENTRY-PROGRAM for SYSTEM within the current directory."
  229. (with-output-to-file (string-append system "-exec.lisp")
  230. (lambda _
  231. (let ((system (string->lisp-keyword system "-exec")))
  232. (format #t "~{~y~%~%~}"
  233. `((defpackage ,system
  234. (:use :cl)
  235. (:export :main))
  236. (in-package ,system)
  237. (defun main ()
  238. (let ((arguments uiop:*command-line-arguments*))
  239. (declare (ignorable arguments))
  240. ,@entry-program))))))))
  241. (define (generate-dependency-links registry system)
  242. "Creates a program which populates asdf's source registry from REGISTRY, an
  243. alist of dependency names to corresponding asd files. This allows the system
  244. to locate its dependent systems."
  245. `(progn
  246. (asdf/source-registry:ensure-source-registry)
  247. ,@(map (match-lambda
  248. ((name . asd-file)
  249. `(setf
  250. (gethash ,name
  251. asdf/source-registry:*source-registry*)
  252. ,(string->symbol "#p")
  253. ,asd-file)))
  254. registry)))
  255. (define* (make-asd-file asd-file
  256. #:key system version inputs
  257. (system-asd-file #f))
  258. "Create an ASD-FILE for SYSTEM@VERSION, appending a program to allow the
  259. system to find its dependencies, as described by GENERATE-DEPENDENCY-LINKS."
  260. (define dependencies
  261. (let ((deps
  262. (system-dependencies system system-asd-file)))
  263. (if (eq? 'NIL deps)
  264. '()
  265. (map normalize-dependency deps))))
  266. (define lisp-input-map
  267. (inputs->asd-file-map inputs))
  268. (define dependency-name
  269. (match-lambda
  270. ((':version name _ ...) name)
  271. ((':feature _ dependency-specification)
  272. (dependency-name dependency-specification))
  273. ((? string? name) name)
  274. (_ #f)))
  275. (define registry
  276. (filter-map hash-get-handle
  277. (make-list (length dependencies)
  278. lisp-input-map)
  279. (map dependency-name dependencies)))
  280. (call-with-output-file asd-file
  281. (lambda (port)
  282. (display
  283. (replace-escaped-macros
  284. (format #f "~y~%~y~%"
  285. (generate-system-definition system
  286. #:version version
  287. #:dependencies dependencies)
  288. (generate-dependency-links registry system)))
  289. port))))
  290. (define (bundle-asd-file output-path original-asd-file)
  291. "Find the symlinked bundle file for ORIGINAL-ASD-FILE by looking in
  292. OUTPUT-PATH/share/common-lisp/LISP-bundle-systems/<system>.asd. Returns two
  293. values: the asd file itself and the directory in which it resides."
  294. (let ((bundle-asd-path (string-append output-path
  295. (%bundle-install-prefix))))
  296. (values (string-append bundle-asd-path "/" (basename original-asd-file))
  297. bundle-asd-path)))
  298. (define (replace-escaped-macros string)
  299. "Replace simple lisp forms that the guile writer escapes, for example by
  300. replacing #{#p}# with #p. Should only be used to replace truly simple forms
  301. which are not nested."
  302. (regexp-substitute/global #f "(#\\{)(\\S*)(\\}#)" string
  303. 'pre 2 'post))
  304. (define (prepend-to-source-registry path)
  305. (setenv "CL_SOURCE_REGISTRY"
  306. (string-append path ":" (or (getenv "CL_SOURCE_REGISTRY") ""))))
  307. (define* (build-program program outputs #:key
  308. (dependency-prefixes (list (library-output outputs)))
  309. (dependencies (list (basename program)))
  310. entry-program
  311. compress?
  312. #:allow-other-keys)
  313. "Generate an executable program containing all DEPENDENCIES, and which will
  314. execute ENTRY-PROGRAM. The result is placed in PROGRAM. When executed, it
  315. will run ENTRY-PROGRAM, a list of Common Lisp expressions in which `arguments'
  316. has been bound to the command-line arguments which were passed. Link in any
  317. asd files from DEPENDENCY-PREFIXES to ensure references to those libraries are
  318. retained."
  319. (generate-executable program
  320. #:dependencies dependencies
  321. #:dependency-prefixes dependency-prefixes
  322. #:entry-program entry-program
  323. #:compress? compress?
  324. #:type 'asdf:program-op)
  325. (let* ((name (basename program))
  326. (bin-directory (dirname program)))
  327. (with-directory-excursion bin-directory
  328. (rename-file (string-append name "-exec")
  329. name)))
  330. #t)
  331. (define* (build-image image outputs #:key
  332. (dependency-prefixes (list (library-output outputs)))
  333. (dependencies (list (basename image)))
  334. #:allow-other-keys)
  335. "Generate an image, possibly standalone, which contains all DEPENDENCIES,
  336. placing the result in IMAGE.image. Link in any asd files from
  337. DEPENDENCY-PREFIXES to ensure references to those libraries are retained."
  338. (generate-executable image
  339. #:dependencies dependencies
  340. #:dependency-prefixes dependency-prefixes
  341. #:entry-program '(nil)
  342. #:type 'asdf:image-op)
  343. (let* ((name (basename image))
  344. (bin-directory (dirname image)))
  345. (with-directory-excursion bin-directory
  346. (rename-file (string-append name "-exec--all-systems.image")
  347. (string-append name ".image"))))
  348. #t)
  349. (define* (generate-executable out-file #:key
  350. dependencies
  351. dependency-prefixes
  352. entry-program
  353. type
  354. compress?
  355. #:allow-other-keys)
  356. "Generate an executable by using asdf operation TYPE, containing whithin the
  357. image all DEPENDENCIES, and running ENTRY-PROGRAM in the case of an
  358. executable. Link in any asd files from DEPENDENCY-PREFIXES to ensure
  359. references to those libraries are retained."
  360. (let* ((bin-directory (dirname out-file))
  361. (name (basename out-file)))
  362. (mkdir-p bin-directory)
  363. (with-directory-excursion bin-directory
  364. (generate-executable-wrapper-system name dependencies)
  365. (generate-executable-entry-point name entry-program))
  366. (prepend-to-source-registry
  367. (string-append bin-directory "/"))
  368. (setenv "ASDF_OUTPUT_TRANSLATIONS"
  369. (replace-escaped-macros
  370. (format
  371. #f "~S"
  372. (wrap-output-translations
  373. `(((,bin-directory :**/ :*.*.*)
  374. (,bin-directory :**/ :*.*.*)))))))
  375. (generate-executable-for-system type name #:compress? compress?)
  376. (let* ((after-store-prefix-index
  377. (string-index out-file #\/
  378. (1+ (string-length (%store-directory)))))
  379. (output (string-take out-file after-store-prefix-index))
  380. (hidden-asd-links (string-append output "/.asd-files")))
  381. (mkdir-p hidden-asd-links)
  382. (for-each
  383. (lambda (path)
  384. (for-each
  385. (lambda (asd-file)
  386. (symlink asd-file
  387. (string-append hidden-asd-links
  388. "/" (basename asd-file))))
  389. (find-files (string-append path (%bundle-install-prefix))
  390. "\\.asd$")))
  391. dependency-prefixes))
  392. (delete-file (string-append bin-directory "/" name "-exec.asd"))
  393. (delete-file (string-append bin-directory "/" name "-exec.lisp"))))