1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2015 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
6 ;;;; LilyPond is free software: you can redistribute it and/or modify
7 ;;;; it under the terms of the GNU General Public License as published by
8 ;;;; the Free Software Foundation, either version 3 of the License, or
9 ;;;; (at your option) any later version.
11 ;;;; LilyPond is distributed in the hope that it will be useful,
12 ;;;; but 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.
16 ;;;; You should have received a copy of the GNU General Public License
17 ;;;; along with LilyPond. If not, see <http://www.gnu.org/licenses/>.
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
28 (defmacro-public _i (x) x)
30 ;;; Boolean thunk - are we integrating Guile V2.0 or higher with LilyPond?
31 (define-public (guile-v2)
32 (string>? (version) "1.9.10"))
34 (read-enable 'positions)
38 (debug-enable 'backtrace)
39 (debug-set! show-file-name #t)))
41 (define-public PLATFORM
44 (car (string-tokenize (utsname:sysname (uname)) char-set:letter)))))
46 ;; We don't use (srfi srfi-39) (parameter objects) here because that
47 ;; does not give us a name/handle to the underlying fluids themselves.
49 (define %parser (make-fluid))
50 (define %location (make-fluid))
51 ;; No public setters: should not get overwritten in action
52 (define-public (*parser*) (fluid-ref %parser))
53 (define-public (*location*) (fluid-ref %location))
54 ;; but properly scoped location should be fine
55 (defmacro-public with-location (loc . body)
56 `(with-fluids ((,%location ,loc)) ,@body))
58 ;; It would be nice to convert occurences of parser/location to
59 ;; (*parser*)/(*location*) using the syncase module but it is utterly
60 ;; broken in GUILE 1 and would require changing a lot of unrelated
61 ;; innocuous constructs which just happen to fall apart with
62 ;; inscrutable error messages.
65 ;; Session-handling variables and procedures.
67 ;; A "session" corresponds to one .ly file processed on a LilyPond
68 ;; command line. Every session gets to see a reasonably fresh state
69 ;; of LilyPond and should work independently from previous files.
71 ;; Session management relies on cooperation, namely the user not
72 ;; trying to change variables and data structures internal to
73 ;; LilyPond. It is not proof against in-place modification of data
74 ;; structures (as they are just reinitialized with the original
75 ;; identities), and it is not proof against tampering with internals.
77 ;; As a consequence, session management is not sufficient for
78 ;; separating multiple independent .ly files in "-dsafe" mode: you
79 ;; should give each its own LilyPond process when reliable separation
82 ;; For standard tasks and programming practices, multiple sessions in
83 ;; the same LilyPond job should work reasonably independently and
84 ;; without "bleed-over" while still loading and compiling the
85 ;; relevant .scm and .ly files only once.
88 (define lilypond-declarations '())
89 (define lilypond-exports '())
90 (define after-session-hook (make-hook))
92 (define-public (call-after-session thunk)
93 (if (ly:undead? lilypond-declarations)
94 (ly:error (_ "call-after-session used after session start")))
95 (add-hook! after-session-hook thunk #t))
97 (defmacro-public define-session (name value)
98 "This defines a variable @var{name} with the starting value
99 @var{value} that is reinitialized at the start of each session.
100 A@tie{}session basically corresponds to one LilyPond file on the
101 command line. The value is recorded at the start of the first session
102 after loading all initialization files and before loading the user
103 file and is reinstated for all of the following sessions. This
104 happens just by replacing the value, not by copying structures, so you
105 should not destructively modify them. For example, lists defined in
106 this manner should be changed within a session only be adding material
107 to their front or replacing them altogether, not by modifying parts of
108 them. It is an error to call @code{define-session} after the first
109 session has started."
110 (define (add-session-variable name value)
111 (if (ly:undead? lilypond-declarations)
112 (ly:error (_ "define-session used after session start")))
113 (let ((var (make-variable value)))
114 (module-add! (current-module) name var)
115 (set! lilypond-declarations (cons var lilypond-declarations))))
116 `(,add-session-variable ',name ,value))
118 (defmacro-public define-session-public (name value)
119 "Like @code{define-session}, but also exports @var{name} into parser modules."
120 (define (add-session-variable name value)
121 (if (ly:undead? lilypond-declarations)
122 (ly:error (_ "define-session-public used after session start")))
123 (let ((var (make-variable value)))
124 (module-add! (current-module) name var)
125 (set! lilypond-exports (acons name var lilypond-exports))))
126 `(,add-session-variable ',name ,value))
128 (define (session-terminate)
129 (if (ly:undead? lilypond-declarations)
132 (lambda (p) (variable-set! (cadr p) (cddr p)))
133 (ly:get-undead lilypond-declarations))
134 (run-hook after-session-hook))))
136 (define lilypond-interfaces #f)
138 (define-public (session-initialize thunk)
139 "Initialize this session. The first session in a LilyPond run is
140 initialized by calling @var{thunk}, then recording the values of all
141 variables in the current module as well as those defined with
142 @code{define-session}. Subsequent calls of @code{session-initialize}
143 ignore @var{thunk} and instead just reinitialize all recorded
144 variables to their value after the initial call of @var{thunk}."
146 ;; We need to save the variables of the current module along with
147 ;; their values: functions defined in the module might refer to the
150 ;; The entries in lilypond-declarations consist of a cons* consisting
151 ;; of symbol, variable, and value. Variables defined with
152 ;; define-session have the symbol set to #f.
154 (if (ly:undead? lilypond-declarations)
156 (module-use-interfaces! (current-module) (reverse lilypond-interfaces))
161 (variable-set! var val)
163 (module-add! (current-module) (car p) var))))
164 (ly:get-undead lilypond-declarations)))
166 ;; import all public session variables natively into parser
167 ;; module. That makes them behave identically under define/set!
168 (for-each (lambda (v)
169 (module-add! (current-module) (car v) (cdr v)))
171 ;; Initialize first session
173 ;; lilypond-exports is no longer needed since we will grab its
174 ;; values from (current-module).
175 (set! lilypond-exports #f)
176 (set! lilypond-interfaces
177 (filter (lambda (m) (eq? 'interface (module-kind m)))
178 (module-uses (current-module))))
179 (let ((decl (map! (lambda (v)
180 (cons* #f v (variable-ref v)))
181 lilypond-declarations)))
184 (let ((val (variable-ref v)))
185 (if (not (ly:lily-parser? val))
191 (set! lilypond-declarations (ly:make-undead decl))))))
193 (define scheme-options-definitions
197 ;; - [subject-]object-object-verb +"ing"
198 ;; - [subject-]-verb-object-object
200 ;; Avoid overlong lines in `lilypond -dhelp'! Strings should not
201 ;; be longer than 48 characters per line.
204 "Render at higher resolution (using given factor)
205 and scale down result to prevent jaggies in
209 "Create .tex, .texi, .count files in the
213 "Select backend. Possible values: 'eps, 'null,
214 'ps, 'scm, 'socket, 'svg.")
215 (check-internal-types
217 "Check every property assignment for types.")
220 "Generate cut-out snippets of a score.")
223 "LilyPond prefix for data files (read-only).")
226 "Dump memory debugging statistics.")
227 (debug-gc-assert-parsed-dead
229 "For memory debugging: Ensure that all
230 references to parsed objects are dead. This is
231 an internal option, and is switched on
232 automatically for `-ddebug-gc'.")
235 "Debug the flex lexer.")
236 (debug-page-breaking-scoring
238 "Dump scores for many different page breaking
242 "Debug the bison parser.")
243 (debug-property-callbacks
245 "Debug cyclic callback chains.")
249 (delete-intermediate-files
251 "Delete unusable, intermediate PostScript files.")
254 "Dump memory and time information for each file.")
257 "Dump timing information (system-dependent).")
260 "Dump output signatures of each system. Used for
261 regression testing.")
264 "Embed the source files inside the generated PDF document.")
267 "Pad left edge of the output EPS bounding box by
268 given amount (in mm).")
271 "Load fonts via Ghostscript.")
274 "Load only LilyPond fonts via Ghostscript.")
277 "Run LilyPond from a GUI and redirect stderr to
282 (include-book-title-preview
284 "Include book titles in preview images.")
287 "Include fonts in separate-system EPS files.")
290 "Include file for global settings, included before the score is processed.")
293 "Process in parallel, using the given number of
297 "If string FOO is given as argument, redirect
298 output to log file `FOO.log'.")
301 "Maximum depth for the markup tree. If a markup has more levels,
302 assume it will not terminate on its own, print a warning and return a
303 null markup instead.")
304 (midi-extension ,(if (eq? PLATFORM 'windows)
307 "Set the default file extension for MIDI output
308 file to given string.")
309 (music-strings-to-paths
311 "Convert text strings to paths when glyphs belong
315 "Add point & click links to PDF and SVG output.")
318 "Set default paper size.")
321 "Set GhostScript's output format for pixel images.")
324 "Create preview images also.")
327 "Print pages in the normal way.")
328 (protected-scheme-parsing
330 "Continue when errors in inline scheme are caught
331 in the parser. If #f, halt on errors and print
333 (profile-property-accesses
335 "Keep statistics of get_property() calls.")
338 "Set resolution for generating PNG pixmaps to
339 given value (in dpi).")
342 "Specify name of a file which contains a list of
343 input files to be processed.")
346 "When processing an \\include command, look for
347 the included file relative to the current file\
348 \n(instead of the root file)")
351 "Run in safer mode.")
354 "For input files `FILE1.ly', `FILE2.ly', ...
355 output log data to files `FILE1.log',
357 (show-available-fonts
359 "List available font names.")
360 (strict-infinity-checking
362 "Force a crash on encountering Inf and NaN
363 floating point exceptions.")
366 "Don't use directories from input files while
367 constructing output file names.")
370 "Set the PostScript strokeadjust operator explicitly.
371 This employs different drawing primitives, resulting in
372 large PDF file size increases but often markedly better
376 "Use woff font files in SVG backend.")
377 (trace-memory-frequency
379 "Record Scheme cell usage this many times per
380 second. Dump results to `FILE.stacks' and
382 (trace-scheme-coverage
384 "Record coverage of Scheme files in `FILE.cov'.")
385 (verbose ,(ly:verbose-output?)
386 "Verbose output, i.e. loglevel at least DEBUG (read-only).")
389 "Change all warning and programming_error
390 messages into errors.")
393 ;; Need to do this in the beginning. Other parts of the Scheme
394 ;; initialization depend on these options.
396 (for-each (lambda (x)
397 (ly:add-option (car x) (cadr x) (caddr x)))
398 scheme-options-definitions)
400 (for-each (lambda (x)
401 (ly:set-option (car x) (cdr x)))
402 (eval-string (ly:command-line-options)))
406 (if (defined? 'set-debug-cell-accesses!)
407 (set-debug-cell-accesses! #f))
409 ;;(set-debug-cell-accesses! 1000)
411 (use-modules (ice-9 regex)
423 (scm safe-utility-defs))
425 (define-public _ gettext)
426 ;;; There are new modules defined in Guile V2.0 which we need to use.
428 ;; Modules and scheme files loaded by lily.scm use currying
429 ;; in Guile V2 this needs a module which is not present in Guile V1.8
434 (ly:debug (_ "Using (ice-9 curried-definitions) module\n"))
435 (use-modules (ice-9 curried-definitions)))
437 (ly:debug (_ "Guile 1.8\n"))))
439 ;; TODO add in modules for V1.8.7 deprecated in V2.0 and integrated
440 ;; into Guile base code, like (ice-9 syncase).
443 (define-public fancy-format
446 (define-public (ergonomic-simple-format dest . rest)
447 "Like ice-9's @code{format}, but without the memory consumption."
449 (apply simple-format #f dest rest)
450 (apply simple-format dest rest)))
453 ergonomic-simple-format)
456 (define-public (myd k v)
463 (define-public (print . args)
464 (apply format (current-output-port) args))
467 ;;; General settings.
469 ;;; Debugging evaluator is slower. This should have a more sensible
473 (if (or (ly:get-option 'verbose)
474 (ly:get-option 'trace-memory-frequency)
475 (ly:get-option 'trace-scheme-coverage))
477 (ly:set-option 'protected-scheme-parsing #f)
478 (debug-enable 'backtrace)
479 (read-enable 'positions)))
481 (if (ly:get-option 'trace-scheme-coverage)
484 (define music-string-to-path-backends
487 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
488 (ly:set-option 'music-strings-to-paths #t))
490 (define-public (ly:load x)
491 (let* ((file-name (%search-load-path x)))
492 (ly:debug "[~A" file-name)
494 (ly:error (_ "cannot find: ~A") x))
495 (primitive-load-path file-name) ;; to support Guile V2 autocompile
496 ;; TODO: Any chance to use ly:debug here? Need to extend it to prevent
497 ;; a newline in this case
498 (if (ly:get-option 'verbose)
499 (ly:progress "]\n"))))
502 (let ((platform (string-tokenize
503 (vector-ref (uname) 0) char-set:letter+digit)))
504 (if (null? (cdr platform)) #f
505 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
508 (if (string-index x #\\)
510 (string-regexp-substitute
512 (string-regexp-substitute "\\\\" "/" x))))
514 (define-public (ly-getcwd)
515 (if (eq? PLATFORM 'windows)
519 (define-public (is-absolute? file-name)
520 (let ((file-name-length (string-length file-name)))
521 (if (= file-name-length 0)
523 (or (eq? (string-ref file-name 0) #\/)
524 (and (eq? PLATFORM 'windows)
525 (> file-name-length 2)
526 (eq? (string-ref file-name 1) #\:)
527 (or (eq? (string-ref file-name 2) #\\)
528 (eq? (string-ref file-name 2) #\/)))))))
530 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
531 ;;; If necessary, emulate Guile V2 module_export_all! for Guile V1.8.n
534 (define (module-export-all! mod)
535 (define (fresh-interface!)
536 (let ((iface (make-module)))
537 (set-module-name! iface (module-name mod))
538 ;; for guile 2: (set-module-version! iface (module-version mod))
539 (set-module-kind! iface 'interface)
540 (set-module-public-interface! mod iface)
542 (let ((iface (or (module-public-interface mod)
543 (fresh-interface!))))
544 (set-module-obarray! iface (module-obarray mod))))))
547 (define-safe-public (lilypond-version)
549 (map (lambda (x) (if (symbol? x)
555 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
558 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
560 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
564 ;; List of Scheme files to be loaded into the (lily) module.
566 ;; - Library definitions, need to be at the head of the list
567 (define init-scheme-files-lib
570 ;; - Files containing definitions used later by other files later in load
571 (define init-scheme-files-used
572 '("markup-macros.scm"
573 "parser-ly-from-scheme.scm"))
574 ;; - Main body of files to be loaded
575 (define init-scheme-files-body
577 "define-event-classes.scm"
578 "define-music-callbacks.scm"
579 "define-music-types.scm"
580 "define-note-names.scm"
585 "define-markup-commands.scm"
587 "modal-transforms.scm"
588 "chord-generic-names.scm"
589 "chord-ignatzek-names.scm"
590 "music-functions.scm"
593 "define-music-properties.scm"
595 "time-signature-settings.scm"
600 "define-context-properties.scm"
601 "translation-functions.scm"
615 "define-woodwind-diagrams.scm"
616 "display-woodwind-diagrams.scm"
617 "predefined-fretboards.scm"
618 "define-grob-properties.scm"
620 "define-grob-interfaces.scm"
621 "define-stencil-commands.scm"
622 "scheme-engravers.scm"
627 "backend-library.scm"
629 ;; - Files to be loaded last
630 (define init-scheme-files-tail
631 ;; - must be after everything has been defined
634 ;; Now construct the load list
636 (define init-scheme-files
637 (append init-scheme-files-lib
638 init-scheme-files-used
639 init-scheme-files-body
640 init-scheme-files-tail))
642 (for-each ly:load init-scheme-files)
644 (define-public r5rs-primary-predicates
645 `((,boolean? . "boolean")
646 (,char? . "character")
647 (,number? . "number")
650 (,procedure? . "procedure")
651 (,string? . "string")
652 (,symbol? . "symbol")
653 (,vector? . "vector")))
655 (define-public r5rs-secondary-predicates
656 `((,char-alphabetic? . "alphabetic character")
657 (,char-lower-case? . "lower-case character")
658 (,char-numeric? . "numeric character")
659 (,char-upper-case? . "upper-case character")
660 (,char-whitespace? . "whitespace character")
662 (,complex? . "complex number")
663 (,even? . "even number")
664 (,exact? . "exact number")
665 (,inexact? . "inexact number")
666 (,integer? . "integer")
667 (,negative? . "negative number")
668 (,odd? . "odd number")
669 (,positive? . "positive number")
670 (,rational? . "rational number")
671 (,real? . "real number")
677 (,input-port? . "input port")
678 (,output-port? . "output port")
680 ;; would this ever be used?
681 (,eof-object? . "end-of-file object")
684 (define-public guile-predicates
685 `((,hash-table? . "hash table")
688 (define-public lilypond-scheme-predicates
689 `((,boolean-or-symbol? . "boolean or symbol")
691 (,cheap-list? . "list")
692 (,fraction? . "fraction, as pair")
693 (,grob-list? . "list of grobs")
694 (,index? . "non-negative integer")
695 (,key? . "index or symbol")
696 (,key-list? . "list of indexes or symbols")
697 (,key-list-or-music? . "key list or music")
698 (,key-list-or-symbol? . "key list or symbol")
699 (,markup? . "markup")
700 (,markup-command-list? . "markup command list")
701 (,markup-list? . "markup list")
702 (,moment-pair? . "pair of moment objects")
703 (,number-list? . "number list")
704 (,number-or-grob? . "number or grob")
705 (,number-or-markup? . "number or markup")
706 (,number-or-pair? . "number or pair")
707 (,number-or-string? . "number or string")
708 (,number-pair? . "pair of numbers")
709 (,number-pair-list? . "list of number pairs")
710 (,rational-or-procedure? . "an exact rational or procedure")
711 (,rhythmic-location? . "rhythmic location")
712 (,scheme? . "any type")
713 (,string-or-pair? . "string or pair")
714 (,string-or-music? . "string or music")
715 (,string-or-symbol? . "string or symbol")
716 (,symbol-list? . "symbol list")
717 (,symbol-list-or-music? . "symbol list or music")
718 (,symbol-list-or-symbol? . "symbol list or symbol")
722 (define-public lilypond-exported-predicates
723 `((,ly:book? . "book")
725 (,ly:context? . "context")
726 (,ly:context-def? . "context definition")
727 (,ly:context-mod? . "context modification")
728 (,ly:dimension? . "dimension, in staff space")
729 (,ly:dir? . "direction")
730 (,ly:dispatcher? . "dispatcher")
731 (,ly:duration? . "duration")
732 (,ly:event? . "post event")
733 (,ly:font-metric? . "font metric")
734 (,ly:grob? . "graphical (layout) object")
735 (,ly:grob-array? . "array of grobs")
736 (,ly:grob-properties? . "grob properties")
737 (,ly:input-location? . "input location")
739 (,ly:iterator? . "iterator")
740 (,ly:lily-lexer? . "lily-lexer")
741 (,ly:lily-parser? . "lily-parser")
742 (,ly:listener? . "listener")
743 (,ly:moment? . "moment")
744 (,ly:music? . "music")
745 (,ly:music-function? . "music function")
746 (,ly:music-list? . "list of music objects")
747 (,ly:music-output? . "music output")
748 (,ly:otf-font? . "OpenType font")
749 (,ly:output-def? . "output definition")
750 (,ly:page-marker? . "page marker")
751 (,ly:pango-font? . "pango font")
752 (,ly:paper-book? . "paper book")
753 (,ly:paper-system? . "paper-system Prob")
754 (,ly:pitch? . "pitch")
755 (,ly:prob? . "property object")
756 (,ly:score? . "score")
757 (,ly:skyline? . "skyline")
758 (,ly:skyline-pair? . "pair of skylines")
759 (,ly:source-file? . "source file")
760 (,ly:spanner? . "spanner")
761 (,ly:spring? . "spring")
762 (,ly:stencil? . "stencil")
763 (,ly:stream-event? . "stream event")
764 (,ly:translator? . "translator")
765 (,ly:translator-group? . "translator group")
766 (,ly:undead? . "undead container")
767 (,ly:unpure-pure-container? . "unpure/pure container")
771 (set! type-p-name-alist
772 (append r5rs-primary-predicates
773 r5rs-secondary-predicates
775 lilypond-scheme-predicates
776 lilypond-exported-predicates))
779 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
782 (define (profile-measurements)
785 (list (- (+ (tms:cutime t)
787 (assoc-get 'gc-time-taken stats))
788 (assoc-get 'total-cells-allocated stats 0))))
790 (define (dump-profile base last this)
791 (let* ((outname (format #f "~a.profile" (dir-basename base ".ly")))
792 (diff (map - this last)))
793 (ly:progress "\nWriting timing to ~a...\n" outname)
794 (format (open-file outname "w")
795 "time: ~a\ncells: ~a\n"
796 (if (ly:get-option 'dump-cpu-profile)
801 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
802 ;; debug memory leaks
807 (define gc-protect-stat-count
810 ;; Undead objects that should be ignored after the first time round
812 (make-weak-key-hash-table 0))
814 (define-public (dump-live-object-stats outfile)
815 (for-each (lambda (x)
816 (format outfile "~a: ~a\n" (car x) (cdr x)))
817 (sort (gc-live-object-stats)
819 (string<? (car x) (car y))))))
821 (define-public (dump-gc-protects)
822 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
823 (let* ((protects (sort (hash-table->alist (ly:protects))
825 (< (object-address (car a))
826 (object-address (car b))))))
827 (out-file-name (string-append
828 "gcstat-" (number->string gc-protect-stat-count)
830 (outfile (open-file out-file-name "w")))
832 (ly:progress "Dumping GC statistics ~a...\n" out-file-name)
833 (for-each (lambda (y)
836 (format outfile "~a (~a) = ~a\n" (object-address x) c x)))
839 (not (symbol? (car x))))
841 (format outfile "\nprotected symbols: ~a\n"
842 (apply + (map (lambda (obj-count)
843 (if (symbol? (car obj-count))
848 ;; (display (ly:smob-protects))
850 (if (defined? 'gc-live-object-stats)
852 (ly:progress "Live object statistics: GC'ing\n")
856 (ly:progress "Asserting dead objects\n")
857 (ly:set-option 'debug-gc-assert-parsed-dead #t)
859 (ly:set-option 'debug-gc-assert-parsed-dead #f)
862 (if (not (hashq-ref gc-zombies x))
864 (ly:programming-error "Parsed object should be dead: ~a" x)
865 (hashq-set! gc-zombies x #t))))
866 (ly:parsed-undead-list!))
867 (set! stats (gc-live-object-stats))
868 (ly:progress "Dumping live object statistics.\n")
869 (dump-live-object-stats outfile)))
871 (let* ((stats (gc-stats)))
872 (for-each (lambda (sym)
873 (format outfile "~a ~a ~a\n"
874 gc-protect-stat-count
876 (assoc-get sym stats "?")))
877 '(protected-objects bytes-malloced cell-heap-size)))
879 (close-port outfile)))
881 (define (check-memory)
882 "Read `/proc/self' to check up on memory use."
883 (define (gulp-file name)
884 (let* ((file (open-input-file name))
885 (text (read-delimited "" file)))
889 (let* ((stat (gulp-file "/proc/self/status"))
890 (lines (string-split stat #\newline))
891 (interesting (filter-map
893 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
895 (mem (string->number (match:substring (car interesting) 1))))
896 (format #t "VMDATA: ~a\n" mem)
900 (begin (dump-gc-protects)
903 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
905 (define (multi-fork count)
906 "Split this process into COUNT helpers. Returns either a list of
907 PIDs or the number of the process."
908 (define (helper count acc)
910 (let* ((pid (primitive-fork)))
913 (helper (1- count) (cons pid acc))))
918 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
920 (define* (ly:exit status #:optional (silently #f))
921 "Exit function for lilypond"
924 ((0) (ly:basic-progress (_ "Success: compilation successfully completed")))
925 ((1) (ly:warning (_ "Compilation completed with warnings or errors")))
926 (else (ly:message ""))))
929 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
931 (define-public (lilypond-main files)
932 "Entry point for LilyPond."
933 (eval-string (ly:command-line-code))
934 (if (ly:get-option 'help)
935 (begin (ly:option-usage)
937 (if (ly:get-option 'show-available-fonts)
938 (begin (ly:font-config-display-fonts)
940 (if (ly:get-option 'gui)
945 (if (ly:get-option 'read-file-list)
950 (string-split (string-delete (ly:gulp-file f) #\cr) #\nl))
952 (if (and (number? (ly:get-option 'job-count))
953 (>= (length files) (ly:get-option 'job-count)))
954 (let* ((count (ly:get-option 'job-count))
955 (split-todo (split-list files count))
956 (joblist (multi-fork count))
958 (if (not (string-or-symbol? (ly:get-option 'log-file)))
959 (ly:set-option 'log-file "lilypond-multi-run"))
960 (if (number? joblist)
961 (begin (ly:set-option
962 'log-file (format #f "~a-~a"
963 (ly:get-option 'log-file) joblist))
964 (set! files (vector-ref split-todo joblist)))
965 (begin (ly:progress "\nForking into jobs: ~a\n" joblist)
968 (let* ((stat (cdr (waitpid pid))))
971 (acons (list-element-index joblist pid)
978 (logfile (format #f "~a-~a.log"
979 (ly:get-option 'log-file) job))
980 (log (ly:gulp-file logfile))
981 (len (string-length log))
982 (tail (substring log (max 0 (- len 1024)))))
983 (if (status:term-sig state)
986 (format #f (_ "job ~a terminated with signal: ~a")
987 job (status:term-sig state)))
989 (_ "logfile ~a (exit ~a):\n~a")
990 logfile (status:exit-val state) tail))))
993 (ly:error "Children ~a exited with errors."
995 ;; must overwrite individual entries
996 (if (ly:get-option 'dump-profile)
997 (dump-profile "lily-run-total"
998 '(0 0) (profile-measurements)))
1003 (if (string-or-symbol? (ly:get-option 'log-file))
1004 (ly:stderr-redirect (format #f "~a.log" (ly:get-option 'log-file)) "w"))
1005 (let ((failed (lilypond-all files)))
1006 (if (ly:get-option 'trace-scheme-coverage)
1008 (coverage:show-all (lambda (f)
1009 (string-contains f "lilypond")))))
1011 (begin (ly:error (_ "failed files: ~S") (string-join failed))
1017 (define-public (lilypond-all files)
1019 (separate-logs (ly:get-option 'separate-log-files))
1022 (if (string-or-symbol? (ly:get-option 'log-file))
1023 (open-file (format #f "~a.log" (ly:get-option 'log-file))
1025 (fdes->outport 2))))
1026 (do-measurements (ly:get-option 'dump-profile))
1027 (handler (lambda (key failed-file)
1028 (set! failed (append (list failed-file) failed)))))
1032 (let* ((start-measurements (if do-measurements
1033 (profile-measurements)
1035 (base (dir-basename x ".ly"))
1036 (all-settings (ly:all-options)))
1038 (ly:stderr-redirect (format #f "~a.log" base) "w"))
1040 (format ping-log "Processing ~a\n" base))
1041 (if (ly:get-option 'trace-memory-frequency)
1042 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
1043 (lilypond-file handler x)
1044 (ly:check-expected-warnings)
1046 (if start-measurements
1047 (dump-profile x start-measurements (profile-measurements)))
1048 (if (ly:get-option 'trace-memory-frequency)
1049 (begin (mtrace:stop-trace)
1050 (mtrace:dump-results base)))
1051 (for-each (lambda (s)
1052 (ly:set-option (car s) (cdr s)))
1054 (ly:set-option 'debug-gc-assert-parsed-dead #t)
1056 (ly:set-option 'debug-gc-assert-parsed-dead #f)
1059 (if (not (hashq-ref gc-zombies x))
1061 (ly:programming-error "Parsed object should be dead: ~a" x)
1062 (hashq-set! gc-zombies x #t))))
1063 (ly:parsed-undead-list!))
1064 (if (ly:get-option 'debug-gc)
1066 (ly:reset-all-fonts))
1070 ;; Ensure a notice re failed files is written to aggregate logfile.
1072 (format ping-log "Failed files: ~a\n" failed))
1073 (if (ly:get-option 'dump-profile)
1074 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
1077 (define (lilypond-file handler file-name)
1078 (catch 'ly-file-failed
1079 (lambda () (ly:parse-file file-name))
1080 (lambda (x . args) (handler x file-name))))
1082 (use-modules (scm editor))
1084 (define-public (gui-main files)
1086 (gui-no-files-handler))
1087 (if (not (string? (ly:get-option 'log-file)))
1088 (let* ((base (dir-basename (car files) ".ly"))
1089 (log-name (string-append base ".log")))
1090 (if (not (ly:get-option 'gui))
1091 (ly:message (_ "Redirecting output to ~a...") log-name))
1092 (ly:stderr-redirect log-name "w")
1093 (ly:message "# -*-compilation-*-"))
1094 (let ((failed (lilypond-all files)))
1098 (ly:stderr-redirect "foo" "r")
1099 (system (get-editor-command log-name 0 0 0))
1100 (ly:error (_ "failed files: ~S") (string-join failed))
1105 (define (gui-no-files-handler)
1106 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
1107 ;; FIXME: soft-code, localize
1108 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
1109 (cmd (get-editor-command welcome-ly 0 0 0)))
1110 (ly:message (_ "Invoking `~a'...\n") cmd)