1 ;;;; lily.scm -- toplevel Scheme stuff
3 ;;;; source file of the GNU LilyPond music typesetter
5 ;;;; (c) 1998--2008 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
8 ;; Internationalisation: (_i "to be translated") gets an entry in the
9 ;; POT file (gettext ) must be invoked explicitely to do the actual
11 ;;(define-macro (_i x) x)
12 ;;(define-macro-public _i (x) x)
13 ;;(define-public-macro _i (x) x)
15 (defmacro-public _i (x) x)
17 (read-enable 'positions)
20 (define-public PLATFORM
23 (car (string-tokenize (utsname:sysname (uname)))))))
25 (define scheme-options-definitions
30 ;; - [subject-]object-object-verb +"ing"
31 ;; - [subject-]-verb-object-object
33 (anti-alias-factor 1 "render at higher resolution and scale down result\nto prevent jaggies in PNG")
34 (backend ps "which backend to use by default; Options: eps, null, ps [default], scm, svg)")
35 (check-internal-types #f "check every property assignment for types")
36 (clip-systems #f "Generate cut-out snippets of a score")
37 (datadir #f "LilyPond prefix for data files (Readonly).")
38 (debug-gc #f "dump memory debugging statistics")
39 (debug-gc-assert-parsed-dead #f "for memory debugging:
40 ensure that all refs to parsed objects are dead. This is an internal option, and is switched on automatically for -ddebug-gc.")
41 (debug-lexer #f "debug the flex lexer")
42 (debug-page-breaking-scoring #f "dump scores for many different page breaking configurations")
43 (debug-parser #f "debug the bison parser")
44 (debug-property-callbacks #f "debug cyclic callback chains")
45 (debug-skylines #f "debug skylines")
46 (delete-intermediate-files #f
47 "delete unusable PostScript files")
48 (dump-profile #f "dump memory and time information for each file")
49 (dump-cpu-profile #f "dump timing information (system-dependent)")
50 (dump-signatures #f "dump output signatures of each system. Used for regression testing.")
52 (eps-box-padding #f "Pad EPS bounding box left edge. Guarantee alignment between systems in LaTeX.")
54 "load fonts via Ghostscript.")
55 (gs-load-lily-fonts #f
56 "load only lilypond fonts via Ghostscript.")
57 (gui #f "running from gui; redirect stderr to log file")
58 (help #f "show this help.")
59 (include-book-title-preview #t "include book-titles in preview images.")
60 (include-eps-fonts #t "Include fonts in separate-system EPS files.")
61 (job-count #f "Process in parallel")
62 (log-file #f "redirect output to log FILE.log")
63 (midi-extension ,(if (eq? PLATFORM 'windows)
66 "set the default file extension for MIDI")
69 "relative for simultaneous music works
70 similar to chord syntax")
71 (point-and-click #t "use point & click")
72 (paper-size "a4" "the default paper size")
73 (pixmap-format "png16m" "GS format to use for pixel images")
74 (preview #f "make a incipit image. ")
75 (print-pages #t "print pages normally. ")
76 (protected-scheme-parsing #t "continue when finding errors in inline
77 scheme are caught in the parser. If off, halt
78 on errors, and print a stack trace.")
79 (profile-property-accesses #f "keep statistics of get_property() calls.")
81 (resolution 101 "resolution for generating PNG bitmaps")
82 (read-file-list #f "Read files to be processed from command line arguments")
84 (safe #f "Run safely")
85 (strict-infinity-checking #f "If yes, crash on encountering Inf/NaN.")
86 (strip-output-dir #t "If yes, strip directories from input files.")
87 (separate-log-files #f "Output to FILE.log per file.")
88 (trace-memory-frequency #f "Record Scheme cell usage this many times per second, and dump to file.")
89 (trace-scheme-coverage #f "Record coverage of Scheme files")
90 (show-available-fonts #f
91 "List font names available.")
92 (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
95 ;; need to do this in the beginning. Other parts of the
96 ;; Scheme init depend on these options.
100 (ly:add-option (car x) (cadr x) (caddr x)))
101 scheme-options-definitions)
105 (ly:set-option (car x) (cdr x)))
106 (eval-string (ly:command-line-options)))
110 (if (defined? 'set-debug-cell-accesses!)
111 (set-debug-cell-accesses! #f))
113 ;(set-debug-cell-accesses! 1000)
115 (use-modules (ice-9 regex)
128 (define-public fancy-format format)
129 (define-public (ergonomic-simple-format dest . rest)
130 "Like ice-9 format, but without the memory consumption."
133 (apply simple-format (cons #f (cons dest rest)))
134 (apply simple-format (cons dest rest))))
136 (define format ergonomic-simple-format)
139 (define-public (myd k v) (display k) (display ": ") (display v) (display ", ")
142 (define-public (print . args)
143 (apply format (cons (current-output-port) args)))
147 ;;; debugging evaluator is slower. This should
148 ;;; have a more sensible default.
150 (if (or (ly:get-option 'verbose)
151 (ly:get-option 'trace-memory-frequency)
152 (ly:get-option 'trace-scheme-coverage)
155 (ly:set-option 'protected-scheme-parsing #f)
156 (debug-enable 'debug)
157 (debug-enable 'backtrace)
158 (read-enable 'positions)))
161 (if (ly:get-option 'trace-scheme-coverage)
164 (define-public parser #f)
167 ;; gettext wrapper for guile < 1.7.2
168 (if (defined? 'gettext)
169 (define-public _ gettext)
170 (define-public _ ly:gettext))
172 (define-public (ly:load x)
173 (let* ((file-name (%search-load-path x)))
174 (if (ly:get-option 'verbose)
175 (ly:progress "[~A" file-name))
177 (ly:error (_ "cannot find: ~A") x))
178 (primitive-load file-name)
179 (if (ly:get-option 'verbose)
183 (let ((platform (string-tokenize
184 (vector-ref (uname) 0) char-set:letter+digit)))
185 (if (null? (cdr platform)) #f
186 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
190 (define native-getcwd getcwd)
192 (if (string-index x #\\)
194 (string-regexp-substitute
196 (string-regexp-substitute "\\\\" "/" x))))
197 ;; FIXME: this prints a warning.
198 (define-public (ly-getcwd)
199 (slashify (native-getcwd))))
200 (else (define-public ly-getcwd getcwd)))
202 (define-public (is-absolute? file-name)
203 (let ((file-name-length (string-length file-name)))
204 (if (= file-name-length 0)
206 (or (eq? (string-ref file-name 0) #\/)
207 (and (eq? PLATFORM 'windows)
208 (> file-name-length 2)
209 (eq? (string-ref file-name 1) #\:)
210 (eq? (string-ref file-name 2) #\/))))))
212 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
214 (define (type-check-list location signature arguments)
215 "Typecheck a list of arguments against a list of type
216 predicates. Print a message at LOCATION if any predicate failed."
218 (define (recursion-helper signature arguments count)
219 (define (helper pred? arg count)
220 (if (not (pred? arg))
226 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
227 count (type-name pred?) arg))
231 (if (null? signature)
233 (and (helper (car signature) (car arguments) count)
234 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
236 (recursion-helper signature arguments 1))
238 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
242 ;;(define-public (output-framework) (write "hello\n"))
244 (define output-ps-module
245 (make-module 1021 (list (resolve-interface '(scm output-ps)))))
247 (define-public (ps-output-expression expr port)
248 (display (eval expr output-ps-module) port))
250 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
251 ;; Safe definitions utility
252 (define safe-objects (list))
254 (define-macro (define-safe-public arglist . body)
255 "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
256 The syntax is the same as `define*-public'."
257 (define (get-symbol arg)
259 (get-symbol (car arg))
261 (let ((safe-symbol (get-symbol arglist)))
263 (define*-public ,arglist
265 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
269 (define-safe-public (lilypond-version)
271 (map (lambda (x) (if (symbol? x)
277 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
280 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
284 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
292 "define-event-classes.scm"
293 "define-music-types.scm"
296 "chord-ignatzek-names.scm"
298 "chord-generic-names.scm"
301 "music-functions.scm"
304 "define-music-properties.scm"
308 "parser-ly-from-scheme.scm"
309 "ly-syntax-constructors.scm"
311 "define-context-properties.scm"
312 "translation-functions.scm"
324 "predefined-fretboards.scm"
325 "define-markup-commands.scm"
326 "define-grob-properties.scm"
328 "define-grob-interfaces.scm"
329 "define-stencil-commands.scm"
333 "backend-library.scm"
336 ;; must be after everything has been defined
340 (for-each ly:load init-scheme-files)
343 (set! type-p-name-alist
345 (,boolean-or-symbol? . "boolean or symbol")
346 (,boolean? . "boolean")
348 (,grob-list? . "list of grobs")
349 (,hash-table? . "hash table")
350 (,input-port? . "input port")
351 (,integer? . "integer")
353 (,ly:context? . "context")
354 (,ly:dimension? . "dimension, in staff space")
355 (,ly:dir? . "direction")
356 (,ly:duration? . "duration")
357 (,ly:grob? . "layout object")
358 (,ly:input-location? . "input location")
359 (,ly:moment? . "moment")
360 (,ly:music? . "music")
361 (,ly:pitch? . "pitch")
362 (,ly:translator? . "translator")
363 (,ly:font-metric? . "font metric")
364 (,ly:simple-closure? . "simple closure")
365 (,markup-list? . "list of markups")
366 (,markup? . "markup")
367 (,ly:music-list? . "list of music")
368 (,number-or-grob? . "number or grob")
369 (,number-or-string? . "number or string")
370 (,number-pair? . "pair of numbers")
371 (,number? . "number")
372 (,output-port? . "output port")
374 (,procedure? . "procedure")
375 (,rhythmic-location? . "rhythmic location")
376 (,scheme? . "any type")
377 (,string? . "string")
378 (,symbol? . "symbol")
379 (,vector? . "vector")))
381 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
384 (define (profile-measurements)
391 (ly:assoc-get 'gc-time-taken stats))
393 (ly:assoc-get 'total-cells-allocated stats 0)
396 (define (dump-profile base last this)
398 ((outname (format "~a.profile" (dir-basename base ".ly")))
399 (diff (map (lambda (y) (apply - y)) (zip this last))))
401 (ly:progress "\nWriting timing to ~a..." outname)
402 (format (open-file outname "w")
403 "time: ~a\ncells: ~a\n"
404 (if (ly:get-option 'dump-cpu-profile)
411 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
414 (define gc-dumping #f)
415 (define gc-protect-stat-count 0)
417 (define-public (dump-live-object-stats outfile)
420 (format outfile "~a: ~a\n" (car x) (cdr x)))
421 (sort (gc-live-object-stats)
423 (string<? (car x) (car y))))))
425 (define-public (dump-gc-protects)
426 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
427 (let* ((protects (sort
428 (hash-table->alist (ly:protects))
430 (< (object-address (car a))
431 (object-address (car b))))))
433 (out-file-name (string-append
434 "gcstat-" (number->string gc-protect-stat-count)
436 (outfile (open-file out-file-name "w")))
439 (display (format "Dumping GC statistics ~a...\n" out-file-name))
445 (format "~a (~a) = ~a\n" (object-address x) c x)
449 (not (symbol? (car x))))
453 (format outfile "\nprotected symbols: ~a\n"
454 (apply + (map (lambda (obj-count) (if (symbol? (car obj-count))
459 ;; (display (ly:smob-protects))
461 (if (defined? 'gc-live-object-stats)
463 (display "Live object statistics: GC'ing\n")
467 (display "Asserting dead objects\n")
468 (ly:set-option 'debug-gc-assert-parsed-dead #t)
470 (ly:set-option 'debug-gc-assert-parsed-dead #f)
472 (set! stats (gc-live-object-stats))
473 (display "Dumping live object statistics.\n")
474 (dump-live-object-stats outfile)))
484 gc-protect-stat-count
486 (let ((sym-stat (assoc sym stats)))
491 '(protected-objects bytes-malloced cell-heap-size
501 (define (check-memory)
502 "read /proc/self to check up on memory use."
503 (define (gulp-file name)
504 (let* ((file (open-input-file name))
505 (text (read-delimited "" file)))
509 ((stat (gulp-file "/proc/self/status"))
510 (lines (string-split stat #\newline))
511 (interesting (filter identity
514 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
516 (mem (string->number (match:substring (car interesting) 1)))
520 (display (format "VMDATA: ~a\n" mem))
529 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
532 (define (multi-fork count)
533 "Split this process in COUNT helpers. Returns either a list of pids,
534 or the number of the process."
535 (define (helper count acc)
538 ((pid (primitive-fork)))
541 (helper (1- count) (cons pid acc))))
546 (define-public (lilypond-main files)
547 "Entry point for LilyPond."
549 (eval-string (ly:command-line-code))
551 (if (ly:get-option 'help)
556 (if (ly:get-option 'show-available-fonts)
558 (ly:font-config-display-fonts)
563 (if (ly:get-option 'gui)
571 (if (ly:get-option 'read-file-list)
574 (> (string-length s) 0))
576 (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
580 (if (and (number? (ly:get-option 'job-count))
581 (>= (length files) (ly:get-option 'job-count)))
583 ((count (ly:get-option 'job-count))
584 (split-todo (split-list files count))
585 (joblist (multi-fork count))
588 (if (not (string-or-symbol? (ly:get-option 'log-file)))
589 (ly:set-option 'log-file "lilypond-multi-run"))
591 (if (number? joblist)
594 'log-file (format "~a-~a"
595 (ly:get-option 'log-file) joblist))
596 (set! files (vector-ref split-todo joblist)))
599 (ly:progress "\nForking into jobs: ~a\n" joblist)
602 (let* ((stat (cdr (waitpid pid))))
606 (acons (list-element-index joblist pid)
614 (logfile (format "~a-~a.log"
615 (ly:get-option 'log-file) job))
616 (log (ly:gulp-file logfile))
617 (len (string-length log))
618 (tail (substring log (max 0 (- len 1024)))))
620 (if (status:term-sig state)
623 (format (_ "job ~a terminated with signal: ~a")
624 job (status:term-sig state)))
626 (_ "logfile ~a (exit ~a):\n~a")
627 logfile (status:exit-val state) tail))))
632 (ly:error "Children ~a exited with errors." (map car errors)))
634 ;; must overwrite individual entries
635 (if (ly:get-option 'dump-profile)
636 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
638 (exit (if (null? errors) 0 1))))))
640 (if (string-or-symbol? (ly:get-option 'log-file))
641 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
643 (let ((failed (lilypond-all files)))
644 (if (ly:get-option 'trace-scheme-coverage)
646 (coverage:show-all (lambda (f) (string-contains f "lilypond"))
651 (ly:error (_ "failed files: ~S") (string-join failed))
654 ;; HACK: be sure to exit with single newline
658 (define-public (lilypond-all files)
660 (separate-logs (ly:get-option 'separate-log-files))
663 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
664 (format "~a.log" (ly:get-option 'log-file))
665 "/dev/tty") "a") #f))
666 (do-measurements (ly:get-option 'dump-profile))
667 (handler (lambda (key failed-file)
668 (set! failed (append (list failed-file) failed)))))
674 ((start-measurements (if do-measurements
675 (profile-measurements)
677 (base (dir-basename x ".ly"))
678 (all-settings (ly:all-options)))
681 (ly:stderr-redirect (format "~a.log" base) "w"))
683 (format ping-log "Procesing ~a\n" base))
685 (if (ly:get-option 'trace-memory-frequency)
686 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
688 (lilypond-file handler x)
689 (if start-measurements
690 (dump-profile x start-measurements (profile-measurements)))
692 (if (ly:get-option 'trace-memory-frequency)
695 (mtrace:dump-results base)))
699 (ly:set-option (car s) (cdr s)))
702 (ly:clear-anonymous-modules)
703 (ly:set-option 'debug-gc-assert-parsed-dead #t)
705 (ly:set-option 'debug-gc-assert-parsed-dead #f)
708 (if (ly:get-option 'debug-gc)
710 (if (= (random 40) 1)
711 (ly:reset-all-fonts)))))
715 ;; we want the failed-files notice in the aggregrate logfile.
717 (format ping-log "Failed files: ~a\n" failed))
719 (if (ly:get-option 'dump-profile)
720 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
724 (define (lilypond-file handler file-name)
725 (catch 'ly-file-failed
726 (lambda () (ly:parse-file file-name))
727 (lambda (x . args) (handler x file-name))))
729 (use-modules (scm editor))
731 (define-public (gui-main files)
733 (gui-no-files-handler))
735 (if (not (string? (ly:get-option 'log-file)))
736 (let* ((base (dir-basename (car files) ".ly"))
737 (log-name (string-append base ".log")))
738 (if (not (ly:get-option 'gui))
739 (ly:message (_ "Redirecting output to ~a...") log-name))
740 (ly:stderr-redirect log-name "w")
741 (ly:message "# -*-compilation-*-"))
743 (let ((failed (lilypond-all files)))
747 (ly:stderr-redirect "foo" "r")
748 (system (get-editor-command log-name 0 0 0))
749 (ly:error (_ "failed files: ~S") (string-join failed))
754 (define (gui-no-files-handler)
755 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
756 ;; FIXME: soft-code, localize
757 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
758 (cmd (get-editor-command welcome-ly 0 0 0)))
759 (ly:message (_ "Invoking `~a'...") cmd)