1 ;;;; This file is part of LilyPond, the GNU music typesetter.
3 ;;;; Copyright (C) 1998--2010 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 (read-enable 'positions)
33 (define-public PLATFORM
36 (car (string-tokenize (utsname:sysname (uname)))))))
38 (define scheme-options-definitions
42 ;; - [subject-]object-object-verb +"ing"
43 ;; - [subject-]-verb-object-object
45 ;; Avoid overlong lines in `lilypond -dhelp'! Strings should not
46 ;; be longer than 48 characters per line.
49 "Render at higher resolution (using given factor)
50 and scale down result to prevent jaggies in
53 "Create .tex, .texi, .count files in the
56 "Select backend. Possible values: 'eps, 'null,
57 'ps, 'scm, 'socket, 'svg.")
58 (check-internal-types #f
59 "Check every property assignment for types.")
61 "Generate cut-out snippets of a score.")
63 "LilyPond prefix for data files (read-only).")
65 "Dump memory debugging statistics.")
66 (debug-gc-assert-parsed-dead #f
67 "For memory debugging: Ensure that all
68 references to parsed objects are dead. This is
69 an internal option, and is switched on
70 automatically for `-ddebug-gc'.")
72 "Debug the flex lexer.")
73 (debug-page-breaking-scoring #f
74 "Dump scores for many different page breaking
77 "Debug the bison parser.")
78 (debug-property-callbacks #f
79 "Debug cyclic callback chains.")
82 (delete-intermediate-files #t
83 "Delete unusable, intermediate PostScript files.")
85 "Dump memory and time information for each file.")
87 "Dump timing information (system-dependent).")
89 "Dump output signatures of each system. Used for
92 "Pad left edge of the output EPS bounding box by
93 given amount (in mm).")
95 "Load fonts via Ghostscript.")
96 (gs-load-lily-fonts #f
97 "Load only LilyPond fonts via Ghostscript.")
99 "Run LilyPond from a GUI and redirect stderr to
103 (include-book-title-preview #t
104 "Include book titles in preview images.")
105 (include-eps-fonts #t
106 "Include fonts in separate-system EPS files.")
108 "Process in parallel, using the given number of
111 "If string FOO is given as argument, redirect
112 output to log file `FOO.log'.")
113 (midi-extension ,(if (eq? PLATFORM 'windows)
116 "Set the default file extension for MIDI output
117 file to given string.")
118 (music-strings-to-paths #f
119 "Convert text strings to paths when glyphs belong
122 "Make \\relative mode for simultaneous music work
123 similar to chord syntax.")
125 "Add point & click links to PDF output.")
127 "Set default paper size.")
128 (pixmap-format "png16m"
129 "Set GhostScript's output format for pixel images.")
131 "Create preview images also.")
133 "Print pages in the normal way.")
134 (protected-scheme-parsing #t
135 "Continue when errors in inline scheme are caught
136 in the parser. If #f, halt on errors and print
138 (profile-property-accesses #f
139 "Keep statistics of get_property() calls.")
141 "Set resolution for generating PNG pixmaps to
142 given value (in dpi).")
144 "Specify name of a file which contains a list of
145 input files to be processed.")
146 (relative-includes #f
147 "When processing an \\include command, look for
148 the included file relative to the current file
149 (instead of the root file)")
151 "Run in safer mode.")
152 (strict-infinity-checking #f
153 "Force a crash on encountering Inf and NaN
154 floating point exceptions.")
156 "Don't use directories from input files while
157 constructing output file names.")
158 (separate-log-files #f
159 "For input files `FILE1.ly', `FILE2.ly', ...
160 output log data to files `FILE1.log',
162 (trace-memory-frequency #f
163 "Record Scheme cell usage this many times per
164 second. Dump results to `FILE.stacks' and
166 (trace-scheme-coverage #f
167 "Record coverage of Scheme files in `FILE.cov'.")
168 (show-available-fonts #f
169 "List available font names.")
170 (verbose ,(ly:command-line-verbose?)
171 "Value of the --verbose flag (read-only).")
173 "Change all warning and programming_error
174 messages into errors.")
177 ;; Need to do this in the beginning. Other parts of the Scheme
178 ;; initialization depend on these options.
180 (for-each (lambda (x)
181 (ly:add-option (car x) (cadr x) (caddr x)))
182 scheme-options-definitions)
184 (for-each (lambda (x)
185 (ly:set-option (car x) (cdr x)))
186 (eval-string (ly:command-line-options)))
190 (if (defined? 'set-debug-cell-accesses!)
191 (set-debug-cell-accesses! #f))
193 ;(set-debug-cell-accesses! 1000)
195 (use-modules (ice-9 regex)
208 (define-public fancy-format
211 (define-public (ergonomic-simple-format dest . rest)
212 "Like ice-9 format, but without the memory consumption."
214 (apply simple-format (cons #f (cons dest rest)))
215 (apply simple-format (cons dest rest))))
218 ergonomic-simple-format)
221 (define-public (myd k v)
228 (define-public (print . args)
229 (apply format (cons (current-output-port) args)))
232 ;;; General settings.
234 ;;; Debugging evaluator is slower. This should have a more sensible
237 (if (or (ly:get-option 'verbose)
238 (ly:get-option 'trace-memory-frequency)
239 (ly:get-option 'trace-scheme-coverage))
241 (ly:set-option 'protected-scheme-parsing #f)
242 (debug-enable 'debug)
243 (debug-enable 'backtrace)
244 (read-enable 'positions)))
246 (if (ly:get-option 'trace-scheme-coverage)
249 (define-public parser #f)
251 (define music-string-to-path-backends
254 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
255 (ly:set-option 'music-strings-to-paths #t))
257 (define-public _ gettext)
259 (define-public (ly:load x)
260 (let* ((file-name (%search-load-path x)))
261 (if (ly:get-option 'verbose)
262 (ly:progress "[~A" file-name))
264 (ly:error (_ "cannot find: ~A") x))
265 (primitive-load file-name)
266 (if (ly:get-option 'verbose)
267 (ly:progress "]\n"))))
270 (let ((platform (string-tokenize
271 (vector-ref (uname) 0) char-set:letter+digit)))
272 (if (null? (cdr platform)) #f
273 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
276 (if (string-index x #\\)
278 (string-regexp-substitute
280 (string-regexp-substitute "\\\\" "/" x))))
282 (define-public (ly-getcwd)
283 (if (eq? PLATFORM 'windows)
287 (define-public (is-absolute? file-name)
288 (let ((file-name-length (string-length file-name)))
289 (if (= file-name-length 0)
291 (or (eq? (string-ref file-name 0) #\/)
292 (and (eq? PLATFORM 'windows)
293 (> file-name-length 2)
294 (eq? (string-ref file-name 1) #\:)
295 (eq? (string-ref file-name 2) #\/))))))
297 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
299 (define (type-check-list location signature arguments)
300 "Typecheck a list of arguments against a list of type predicates.
301 Print a message at LOCATION if any predicate failed."
302 (define (recursion-helper signature arguments count)
303 (define (helper pred? arg count)
304 (if (not (pred? arg))
309 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
310 count (type-name pred?) arg))
314 (if (null? signature)
316 (and (helper (car signature) (car arguments) count)
317 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
318 (recursion-helper signature arguments 1))
321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
322 ;; Safe definitions utility
327 (define-macro (define-safe-public arglist . body)
328 "Define a variable, export it, and mark it as safe, i.e. usable in
329 LilyPond safe mode. The syntax is the same as `define*-public'."
330 (define (get-symbol arg)
332 (get-symbol (car arg))
335 (let ((safe-symbol (get-symbol arglist)))
337 (define*-public ,arglist
339 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
343 (define-safe-public (lilypond-version)
345 (map (lambda (x) (if (symbol? x)
351 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
354 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
356 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
359 (define init-scheme-files
362 "define-event-classes.scm"
363 "define-music-types.scm"
366 "chord-ignatzek-names.scm"
368 "chord-generic-names.scm"
371 "music-functions.scm"
374 "define-music-properties.scm"
379 "parser-ly-from-scheme.scm"
380 "ly-syntax-constructors.scm"
382 "define-context-properties.scm"
383 "translation-functions.scm"
395 "predefined-fretboards.scm"
396 "define-markup-commands.scm"
397 "define-grob-properties.scm"
399 "define-grob-interfaces.scm"
400 "define-stencil-commands.scm"
404 "backend-library.scm"
408 ;; must be after everything has been defined
411 (for-each ly:load init-scheme-files)
413 (define-public r5rs-primary-predicates
414 `((,boolean? . "boolean")
415 (,char? . "character")
416 (,number? . "number")
419 (,procedure? . "procedure")
420 (,string? . "string")
421 (,symbol? . "symbol")
422 (,vector? . "vector")))
424 (define-public r5rs-secondary-predicates
425 `((,char-alphabetic? . "alphabetic character")
426 (,char-lower-case? . "lower-case character")
427 (,char-numeric? . "numeric character")
428 (,char-upper-case? . "upper-case character")
429 (,char-whitespace? . "whitespace character")
431 (,complex? . "complex number")
432 (,even? . "even number")
433 (,exact? . "exact number")
434 (,inexact? . "inexact number")
435 (,integer? . "integer")
436 (,negative? . "negative number")
437 (,odd? . "odd number")
438 (,positive? . "positive number")
439 (,rational? . "rational number")
440 (,real? . "real number")
446 (,input-port? . "input port")
447 (,output-port? . "output port")
449 ;; would this ever be used?
450 (,eof-object? . "end-of-file object")
453 (define-public guile-predicates
454 `((,hash-table? . "hash table")
457 (define-public lilypond-scheme-predicates
458 `((,boolean-or-symbol? . "boolean or symbol")
460 (,cheap-list? . "list")
461 (,grob-list? . "list of grobs")
462 ;; this is built on cheap-list
463 (,list-or-symbol? . "list or symbol")
464 (,markup? . "markup")
465 (,markup-command-list? . "markup command list")
466 (,markup-list? . "markup list")
467 (,moment-pair? . "pair of moment objects")
468 (,number-or-grob? . "number or grob")
469 (,number-or-string? . "number or string")
470 (,number-pair? . "pair of numbers")
471 (,rhythmic-location? . "rhythmic location")
472 (,scheme? . "any type")
473 (,string-or-pair? . "string or pair")
474 (,string-or-symbol? . "string or symbol")
477 (define-public lilypond-exported-predicates
479 (,ly:context? . "context")
480 (,ly:dimension? . "dimension, in staff space")
481 (,ly:dir? . "direction")
482 (,ly:dispatcher? . "dispatcher")
483 (,ly:duration? . "duration")
484 (,ly:font-metric? . "font metric")
485 (,ly:grob? . "graphical (layout) object")
486 (,ly:grob-array? . "array of grobs")
487 (,ly:input-location? . "input location")
489 (,ly:iterator? . "iterator")
490 (,ly:lily-lexer? . "lily-lexer")
491 (,ly:lily-parser? . "lily-parser")
492 (,ly:listener? . "listener")
493 (,ly:moment? . "moment")
494 (,ly:music? . "music")
495 (,ly:music-function? . "music function")
496 (,ly:music-list? . "list of music objects")
497 (,ly:music-output? . "music output")
498 (,ly:otf-font? . "OpenType font")
499 (,ly:output-def? . "output definition")
500 (,ly:page-marker? . "page marker")
501 (,ly:pango-font? . "pango font")
502 (,ly:paper-book? . "paper book")
503 (,ly:paper-system? . "paper-system Prob")
504 (,ly:pitch? . "pitch")
505 (,ly:prob? . "property object")
506 (,ly:score? . "score")
507 (,ly:simple-closure? . "simple closure")
508 (,ly:skyline? . "skyline")
509 (,ly:skyline-pair? . "pair of skylines")
510 (,ly:source-file? . "source file")
511 (,ly:spanner? . "spanner")
512 (,ly:stencil? . "stencil")
513 (,ly:stream-event? . "stream event")
514 (,ly:translator? . "translator")
515 (,ly:translator-group? . "translator group")
519 (set! type-p-name-alist
520 (append r5rs-primary-predicates
521 r5rs-secondary-predicates
523 lilypond-scheme-predicates
524 lilypond-exported-predicates))
527 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
530 (define (profile-measurements)
533 (list (- (+ (tms:cutime t)
535 (assoc-get 'gc-time-taken stats))
536 (assoc-get 'total-cells-allocated stats 0))))
538 (define (dump-profile base last this)
539 (let* ((outname (format "~a.profile" (dir-basename base ".ly")))
540 (diff (map (lambda (y) (apply - y)) (zip this last))))
541 (ly:progress "\nWriting timing to ~a..." outname)
542 (format (open-file outname "w")
543 "time: ~a\ncells: ~a\n"
544 (if (ly:get-option 'dump-cpu-profile)
549 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
550 ;; debug memory leaks
555 (define gc-protect-stat-count
558 (define-public (dump-live-object-stats outfile)
559 (for-each (lambda (x)
560 (format outfile "~a: ~a\n" (car x) (cdr x)))
561 (sort (gc-live-object-stats)
563 (string<? (car x) (car y))))))
565 (define-public (dump-gc-protects)
566 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
567 (let* ((protects (sort (hash-table->alist (ly:protects))
569 (< (object-address (car a))
570 (object-address (car b))))))
571 (out-file-name (string-append
572 "gcstat-" (number->string gc-protect-stat-count)
574 (outfile (open-file out-file-name "w")))
576 (display (format "Dumping GC statistics ~a...\n" out-file-name))
577 (display (map (lambda (y)
581 (format "~a (~a) = ~a\n" (object-address x) c x)
585 (not (symbol? (car x))))
588 (format outfile "\nprotected symbols: ~a\n"
589 (apply + (map (lambda (obj-count)
590 (if (symbol? (car obj-count))
595 ;; (display (ly:smob-protects))
597 (if (defined? 'gc-live-object-stats)
599 (display "Live object statistics: GC'ing\n")
603 (display "Asserting dead objects\n")
604 (ly:set-option 'debug-gc-assert-parsed-dead #t)
606 (ly:set-option 'debug-gc-assert-parsed-dead #f)
607 (set! stats (gc-live-object-stats))
608 (display "Dumping live object statistics.\n")
609 (dump-live-object-stats outfile)))
611 (let* ((stats (gc-stats)))
612 (for-each (lambda (sym)
615 gc-protect-stat-count
617 (assoc-get sym stats "?"))
620 '(protected-objects bytes-malloced cell-heap-size)))
622 (close-port outfile)))
624 (define (check-memory)
625 "Read `/proc/self' to check up on memory use."
626 (define (gulp-file name)
627 (let* ((file (open-input-file name))
628 (text (read-delimited "" file)))
632 (let* ((stat (gulp-file "/proc/self/status"))
633 (lines (string-split stat #\newline))
634 (interesting (filter identity
637 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
639 (mem (string->number (match:substring (car interesting) 1))))
640 (display (format "VMDATA: ~a\n" mem))
643 (begin (dump-gc-protects)
646 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
648 (define (multi-fork count)
649 "Split this process into COUNT helpers. Returns either a list of
650 PIDs or the number of the process."
651 (define (helper count acc)
653 (let* ((pid (primitive-fork)))
656 (helper (1- count) (cons pid acc))))
661 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
663 (define* (ly:exit status #:optional (silently #f) )
664 "Exit function for lilypond"
667 ((0) (ly:success "Compilation successfully completed"))
668 ((1) (ly:warning "Compilation completed with warnings or errors"))
669 (else (ly:message "")))
673 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
675 (define-public (lilypond-main files)
676 "Entry point for LilyPond."
677 (eval-string (ly:command-line-code))
678 (if (ly:get-option 'help)
679 (begin (ly:option-usage)
681 (if (ly:get-option 'show-available-fonts)
682 (begin (ly:font-config-display-fonts)
684 (if (ly:get-option 'gui)
689 (if (ly:get-option 'read-file-list)
692 (> (string-length s) 0))
695 (string-split (ly:gulp-file f) #\nl))
697 (if (and (number? (ly:get-option 'job-count))
698 (>= (length files) (ly:get-option 'job-count)))
699 (let* ((count (ly:get-option 'job-count))
700 (split-todo (split-list files count))
701 (joblist (multi-fork count))
703 (if (not (string-or-symbol? (ly:get-option 'log-file)))
704 (ly:set-option 'log-file "lilypond-multi-run"))
705 (if (number? joblist)
706 (begin (ly:set-option
707 'log-file (format "~a-~a"
708 (ly:get-option 'log-file) joblist))
709 (set! files (vector-ref split-todo joblist)))
710 (begin (ly:progress "\nForking into jobs: ~a\n" joblist)
713 (let* ((stat (cdr (waitpid pid))))
716 (acons (list-element-index joblist pid)
723 (logfile (format "~a-~a.log"
724 (ly:get-option 'log-file) job))
725 (log (ly:gulp-file logfile))
726 (len (string-length log))
727 (tail (substring log (max 0 (- len 1024)))))
728 (if (status:term-sig state)
731 (format (_ "job ~a terminated with signal: ~a")
732 job (status:term-sig state)))
734 (_ "logfile ~a (exit ~a):\n~a")
735 logfile (status:exit-val state) tail))))
738 (ly:error "Children ~a exited with errors."
740 ;; must overwrite individual entries
741 (if (ly:get-option 'dump-profile)
742 (dump-profile "lily-run-total"
743 '(0 0) (profile-measurements)))
748 (if (string-or-symbol? (ly:get-option 'log-file))
749 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
750 (let ((failed (lilypond-all files)))
751 (if (ly:get-option 'trace-scheme-coverage)
753 (coverage:show-all (lambda (f)
754 (string-contains f "lilypond")))))
756 (begin (ly:error (_ "failed files: ~S") (string-join failed))
762 (define-public (lilypond-all files)
764 (separate-logs (ly:get-option 'separate-log-files))
767 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
768 (format "~a.log" (ly:get-option 'log-file))
769 "/dev/tty") "a") #f))
770 (do-measurements (ly:get-option 'dump-profile))
771 (handler (lambda (key failed-file)
772 (set! failed (append (list failed-file) failed)))))
776 (let* ((start-measurements (if do-measurements
777 (profile-measurements)
779 (base (dir-basename x ".ly"))
780 (all-settings (ly:all-options)))
782 (ly:stderr-redirect (format "~a.log" base) "w"))
784 (format ping-log "Processing ~a\n" base))
785 (if (ly:get-option 'trace-memory-frequency)
786 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
787 (lilypond-file handler x)
788 (if start-measurements
789 (dump-profile x start-measurements (profile-measurements)))
790 (if (ly:get-option 'trace-memory-frequency)
791 (begin (mtrace:stop-trace)
792 (mtrace:dump-results base)))
793 (for-each (lambda (s)
794 (ly:set-option (car s) (cdr s)))
796 (ly:clear-anonymous-modules)
797 (ly:set-option 'debug-gc-assert-parsed-dead #t)
799 (ly:set-option 'debug-gc-assert-parsed-dead #f)
800 (if (ly:get-option 'debug-gc)
802 (ly:reset-all-fonts))))
805 ;; we want the failed-files notice in the aggregrate logfile.
807 (format ping-log "Failed files: ~a\n" failed))
808 (if (ly:get-option 'dump-profile)
809 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
812 (define (lilypond-file handler file-name)
813 (catch 'ly-file-failed
814 (lambda () (ly:parse-file file-name))
815 (lambda (x . args) (handler x file-name))))
817 (use-modules (scm editor))
819 (define-public (gui-main files)
821 (gui-no-files-handler))
822 (if (not (string? (ly:get-option 'log-file)))
823 (let* ((base (dir-basename (car files) ".ly"))
824 (log-name (string-append base ".log")))
825 (if (not (ly:get-option 'gui))
826 (ly:message (_ "Redirecting output to ~a...") log-name))
827 (ly:stderr-redirect log-name "w")
828 (ly:message "# -*-compilation-*-"))
829 (let ((failed (lilypond-all files)))
833 (ly:stderr-redirect "foo" "r")
834 (system (get-editor-command log-name 0 0 0))
835 (ly:error (_ "failed files: ~S") (string-join failed))
840 (define (gui-no-files-handler)
841 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
842 ;; FIXME: soft-code, localize
843 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
844 (cmd (get-editor-command welcome-ly 0 0 0)))
845 (ly:message (_ "Invoking `~a'...\n") cmd)