lisp-utils.scm 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 component?)
  169. `(asdf:defsystem
  170. ,(normalize-string system)
  171. ,@(if component?
  172. '(:class asdf/bundle:prebuilt-system)
  173. '())
  174. :version ,version
  175. :depends-on ,dependencies
  176. ,@(if component?
  177. `(:components ((:compiled-file ,(compiled-system system))))
  178. '())
  179. ,@(if (string=? "ecl" (%lisp-type))
  180. `(:lib ,(string-append system ".a"))
  181. '())))
  182. (define (test-system system asd-file test-asd-file)
  183. "Use a lisp implementation to test SYSTEM using asdf. Load ASD-FILE first.
  184. Also load TEST-ASD-FILE if necessary."
  185. (lisp-eval-program
  186. `((require :asdf)
  187. (asdf:load-asd (truename ,asd-file) :name ,(normalize-string system))
  188. ,@(if test-asd-file
  189. `((asdf:load-asd (truename ,test-asd-file)))
  190. ;; Try some likely files.
  191. (map (lambda (file)
  192. `(when (uiop:file-exists-p ,file)
  193. (asdf:load-asd (truename ,file))))
  194. (list
  195. (string-append system "-tests.asd")
  196. (string-append system "-test.asd")
  197. "tests.asd"
  198. "test.asd")))
  199. (asdf:test-system ,system))))
  200. (define (string->lisp-keyword . strings)
  201. "Return a lisp keyword for the concatenation of STRINGS."
  202. (string->symbol (apply string-append ":" strings)))
  203. (define* (generate-executable-for-system type system #:key compress?)
  204. "Use LISP to generate an executable, whose TYPE can be 'asdf:image-op or
  205. 'asdf:program-op. The latter will always be standalone. Depends on having
  206. created a \"SYSTEM-exec\" system which contains the entry program."
  207. (lisp-eval-program
  208. `((require :asdf)
  209. ;; Only SBCL supports compression as of 2019-09-02.
  210. ,(if (and compress? (string=? (%lisp-type) "sbcl"))
  211. '(defmethod asdf:perform ((o asdf:image-op) (c asdf:system))
  212. (uiop:dump-image (asdf:output-file o c)
  213. :executable t
  214. :compression t))
  215. '())
  216. (asdf:operate ',type ,(string-append system "-exec")))))
  217. (define (generate-executable-wrapper-system system dependencies)
  218. "Generates a system which can be used by asdf to produce an image or program
  219. inside the current directory. The image or program will contain
  220. DEPENDENCIES."
  221. (with-output-to-file (string-append system "-exec.asd")
  222. (lambda _
  223. (format #t "~y~%"
  224. `(defsystem ,(string->lisp-keyword system "-exec")
  225. :entry-point ,(string-append system "-exec:main")
  226. :depends-on (:uiop
  227. ,@(map string->lisp-keyword
  228. dependencies))
  229. :components ((:file ,(string-append system "-exec"))))))))
  230. (define (generate-executable-entry-point system entry-program)
  231. "Generates an entry point program from the list of lisp statements
  232. ENTRY-PROGRAM for SYSTEM within the current directory."
  233. (with-output-to-file (string-append system "-exec.lisp")
  234. (lambda _
  235. (let ((system (string->lisp-keyword system "-exec")))
  236. (format #t "~{~y~%~%~}"
  237. `((defpackage ,system
  238. (:use :cl)
  239. (:export :main))
  240. (in-package ,system)
  241. (defun main ()
  242. (let ((arguments uiop:*command-line-arguments*))
  243. (declare (ignorable arguments))
  244. ,@entry-program))))))))
  245. (define (generate-dependency-links registry system)
  246. "Creates a program which populates asdf's source registry from REGISTRY, an
  247. alist of dependency names to corresponding asd files. This allows the system
  248. to locate its dependent systems."
  249. `(progn
  250. (asdf/source-registry:ensure-source-registry)
  251. ,@(map (match-lambda
  252. ((name . asd-file)
  253. `(setf
  254. (gethash ,name
  255. asdf/source-registry:*source-registry*)
  256. ,(string->symbol "#p")
  257. ,asd-file)))
  258. registry)))
  259. (define* (make-asd-file asd-file
  260. #:key system version inputs
  261. (system-asd-file #f))
  262. "Create an ASD-FILE for SYSTEM@VERSION, appending a program to allow the
  263. system to find its dependencies, as described by GENERATE-DEPENDENCY-LINKS."
  264. (define dependencies
  265. (let ((deps
  266. (system-dependencies system system-asd-file)))
  267. (if (eq? 'NIL deps)
  268. '()
  269. (map normalize-dependency deps))))
  270. (define lisp-input-map
  271. (inputs->asd-file-map inputs))
  272. (define dependency-name
  273. (match-lambda
  274. ((':version name _ ...) name)
  275. ((':feature _ dependency-specification)
  276. (dependency-name dependency-specification))
  277. ((? string? name) name)
  278. (_ #f)))
  279. (define registry
  280. (filter-map hash-get-handle
  281. (make-list (length dependencies)
  282. lisp-input-map)
  283. (map dependency-name dependencies)))
  284. ;; Ensure directory exists, which might not be the case for an .asd without components.
  285. (mkdir-p (dirname asd-file))
  286. (call-with-output-file asd-file
  287. (lambda (port)
  288. (display
  289. (replace-escaped-macros
  290. (format #f "~y~%~y~%"
  291. (generate-system-definition
  292. system
  293. #:version version
  294. #:dependencies dependencies
  295. ;; Some .asd don't have components, and thus they don't generate any .fasl.
  296. #:component? (match (%lisp-type)
  297. ("sbcl" (pair? (find-files (dirname asd-file)
  298. "--system\\.fasl$")))
  299. ("ecl" (pair? (find-files (dirname asd-file)
  300. "\\.fasb$")))
  301. (_ (error "The LISP provided is not supported at this time."))))
  302. (generate-dependency-links registry system)))
  303. port))))
  304. (define (bundle-asd-file output-path original-asd-file)
  305. "Find the symlinked bundle file for ORIGINAL-ASD-FILE by looking in
  306. OUTPUT-PATH/share/common-lisp/LISP-bundle-systems/<system>.asd. Returns two
  307. values: the asd file itself and the directory in which it resides."
  308. (let ((bundle-asd-path (string-append output-path
  309. (%bundle-install-prefix))))
  310. (values (string-append bundle-asd-path "/" (basename original-asd-file))
  311. bundle-asd-path)))
  312. (define (replace-escaped-macros string)
  313. "Replace simple lisp forms that the guile writer escapes, for example by
  314. replacing #{#p}# with #p. Should only be used to replace truly simple forms
  315. which are not nested."
  316. (regexp-substitute/global #f "(#\\{)(\\S*)(\\}#)" string
  317. 'pre 2 'post))
  318. (define (prepend-to-source-registry path)
  319. (setenv "CL_SOURCE_REGISTRY"
  320. (string-append path ":" (or (getenv "CL_SOURCE_REGISTRY") ""))))
  321. (define* (build-program program outputs #:key
  322. (dependency-prefixes (list (library-output outputs)))
  323. (dependencies (list (basename program)))
  324. entry-program
  325. compress?
  326. #:allow-other-keys)
  327. "Generate an executable program containing all DEPENDENCIES, and which will
  328. execute ENTRY-PROGRAM. The result is placed in PROGRAM. When executed, it
  329. will run ENTRY-PROGRAM, a list of Common Lisp expressions in which `arguments'
  330. has been bound to the command-line arguments which were passed. Link in any
  331. asd files from DEPENDENCY-PREFIXES to ensure references to those libraries are
  332. retained."
  333. (generate-executable program
  334. #:dependencies dependencies
  335. #:dependency-prefixes dependency-prefixes
  336. #:entry-program entry-program
  337. #:compress? compress?
  338. #:type 'asdf:program-op)
  339. (let* ((name (basename program))
  340. (bin-directory (dirname program)))
  341. (with-directory-excursion bin-directory
  342. (rename-file (string-append name "-exec")
  343. name)))
  344. #t)
  345. (define* (build-image image outputs #:key
  346. (dependency-prefixes (list (library-output outputs)))
  347. (dependencies (list (basename image)))
  348. #:allow-other-keys)
  349. "Generate an image, possibly standalone, which contains all DEPENDENCIES,
  350. placing the result in IMAGE.image. Link in any asd files from
  351. DEPENDENCY-PREFIXES to ensure references to those libraries are retained."
  352. (generate-executable image
  353. #:dependencies dependencies
  354. #:dependency-prefixes dependency-prefixes
  355. #:entry-program '(nil)
  356. #:type 'asdf:image-op)
  357. (let* ((name (basename image))
  358. (bin-directory (dirname image)))
  359. (with-directory-excursion bin-directory
  360. (rename-file (string-append name "-exec--all-systems.image")
  361. (string-append name ".image"))))
  362. #t)
  363. (define* (generate-executable out-file #:key
  364. dependencies
  365. dependency-prefixes
  366. entry-program
  367. type
  368. compress?
  369. #:allow-other-keys)
  370. "Generate an executable by using asdf operation TYPE, containing whithin the
  371. image all DEPENDENCIES, and running ENTRY-PROGRAM in the case of an
  372. executable. Link in any asd files from DEPENDENCY-PREFIXES to ensure
  373. references to those libraries are retained."
  374. (let* ((bin-directory (dirname out-file))
  375. (name (basename out-file)))
  376. (mkdir-p bin-directory)
  377. (with-directory-excursion bin-directory
  378. (generate-executable-wrapper-system name dependencies)
  379. (generate-executable-entry-point name entry-program))
  380. (prepend-to-source-registry
  381. (string-append bin-directory "/"))
  382. (setenv "ASDF_OUTPUT_TRANSLATIONS"
  383. (replace-escaped-macros
  384. (format
  385. #f "~S"
  386. (wrap-output-translations
  387. `(((,bin-directory :**/ :*.*.*)
  388. (,bin-directory :**/ :*.*.*)))))))
  389. (generate-executable-for-system type name #:compress? compress?)
  390. (let* ((after-store-prefix-index
  391. (string-index out-file #\/
  392. (1+ (string-length (%store-directory)))))
  393. (output (string-take out-file after-store-prefix-index))
  394. (hidden-asd-links (string-append output "/.asd-files")))
  395. (mkdir-p hidden-asd-links)
  396. (for-each
  397. (lambda (path)
  398. (for-each
  399. (lambda (asd-file)
  400. (symlink asd-file
  401. (string-append hidden-asd-links
  402. "/" (basename asd-file))))
  403. (find-files (string-append path (%bundle-install-prefix))
  404. "\\.asd$")))
  405. dependency-prefixes))
  406. (delete-file (string-append bin-directory "/" name "-exec.asd"))
  407. (delete-file (string-append bin-directory "/" name "-exec.lisp"))))