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")
91 "how much verbosity for TTF font embedding?")
92 (show-available-fonts #f
93 "List font names available.")
94 (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
97 ;; need to do this in the beginning. Other parts of the
98 ;; Scheme init depend on these options.
102 (ly:add-option (car x) (cadr x) (caddr x)))
103 scheme-options-definitions)
107 (ly:set-option (car x) (cdr x)))
108 (eval-string (ly:command-line-options)))
112 (if (defined? 'set-debug-cell-accesses!)
113 (set-debug-cell-accesses! #f))
115 ;(set-debug-cell-accesses! 1000)
117 (use-modules (ice-9 regex)
130 (define-public fancy-format format)
131 (define-public (ergonomic-simple-format dest . rest)
132 "Like ice-9 format, but without the memory consumption."
135 (apply simple-format (cons #f (cons dest rest)))
136 (apply simple-format (cons dest rest))))
138 (define format ergonomic-simple-format)
141 (define-public (myd k v) (display k) (display ": ") (display v) (display ", ")
144 (define-public (print . args)
145 (apply format (cons (current-output-port) args)))
149 ;;; debugging evaluator is slower. This should
150 ;;; have a more sensible default.
152 (if (or (ly:get-option 'verbose)
153 (ly:get-option 'trace-memory-frequency)
154 (ly:get-option 'trace-scheme-coverage)
157 (ly:set-option 'protected-scheme-parsing #f)
158 (debug-enable 'debug)
159 (debug-enable 'backtrace)
160 (read-enable 'positions)))
163 (if (ly:get-option 'trace-scheme-coverage)
166 (define-public parser #f)
169 ;; gettext wrapper for guile < 1.7.2
170 (if (defined? 'gettext)
171 (define-public _ gettext)
172 (define-public _ ly:gettext))
174 (define-public (ly:load x)
175 (let* ((file-name (%search-load-path x)))
176 (if (ly:get-option 'verbose)
177 (ly:progress "[~A" file-name))
179 (ly:error (_ "cannot find: ~A") x))
180 (primitive-load file-name)
181 (if (ly:get-option 'verbose)
185 (let ((platform (string-tokenize
186 (vector-ref (uname) 0) char-set:letter+digit)))
187 (if (null? (cdr platform)) #f
188 (member (string-downcase (cadr platform)) '("95" "98" "me")))))
192 (define native-getcwd getcwd)
194 (if (string-index x #\\)
196 (string-regexp-substitute
198 (string-regexp-substitute "\\\\" "/" x))))
199 ;; FIXME: this prints a warning.
200 (define-public (ly-getcwd)
201 (slashify (native-getcwd))))
202 (else (define-public ly-getcwd getcwd)))
204 (define-public (is-absolute? file-name)
205 (let ((file-name-length (string-length file-name)))
206 (if (= file-name-length 0)
208 (or (eq? (string-ref file-name 0) #\/)
209 (and (eq? PLATFORM 'windows)
210 (> file-name-length 2)
211 (eq? (string-ref file-name 1) #\:)
212 (eq? (string-ref file-name 2) #\/))))))
214 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
216 (define (type-check-list location signature arguments)
217 "Typecheck a list of arguments against a list of type
218 predicates. Print a message at LOCATION if any predicate failed."
220 (define (recursion-helper signature arguments count)
221 (define (helper pred? arg count)
222 (if (not (pred? arg))
228 #f (_ "wrong type for argument ~a. Expecting ~a, found ~s")
229 count (type-name pred?) arg))
233 (if (null? signature)
235 (and (helper (car signature) (car arguments) count)
236 (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
238 (recursion-helper signature arguments 1))
240 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
244 ;;(define-public (output-framework) (write "hello\n"))
246 (define output-ps-module
247 (make-module 1021 (list (resolve-interface '(scm output-ps)))))
249 (define-public (ps-output-expression expr port)
250 (display (eval expr output-ps-module) port))
252 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
253 ;; Safe definitions utility
254 (define safe-objects (list))
256 (define-macro (define-safe-public arglist . body)
257 "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
258 The syntax is the same as `define*-public'."
259 (define (get-symbol arg)
261 (get-symbol (car arg))
263 (let ((safe-symbol (get-symbol arglist)))
265 (define*-public ,arglist
267 (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
271 (define-safe-public (lilypond-version)
273 (map (lambda (x) (if (symbol? x)
279 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
282 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
286 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
294 "define-event-classes.scm"
295 "define-music-types.scm"
298 "chord-ignatzek-names.scm"
300 "chord-generic-names.scm"
303 "music-functions.scm"
306 "define-music-properties.scm"
310 "parser-ly-from-scheme.scm"
311 "ly-syntax-constructors.scm"
313 "define-context-properties.scm"
314 "translation-functions.scm"
326 "predefined-fretboards.scm"
327 "define-markup-commands.scm"
328 "define-grob-properties.scm"
330 "define-grob-interfaces.scm"
331 "define-stencil-commands.scm"
335 "backend-library.scm"
338 ;; must be after everything has been defined
342 (for-each ly:load init-scheme-files)
345 (set! type-p-name-alist
347 (,boolean-or-symbol? . "boolean or symbol")
348 (,boolean? . "boolean")
350 (,grob-list? . "list of grobs")
351 (,hash-table? . "hash table")
352 (,input-port? . "input port")
353 (,integer? . "integer")
355 (,ly:context? . "context")
356 (,ly:dimension? . "dimension, in staff space")
357 (,ly:dir? . "direction")
358 (,ly:duration? . "duration")
359 (,ly:grob? . "layout object")
360 (,ly:input-location? . "input location")
361 (,ly:moment? . "moment")
362 (,ly:music? . "music")
363 (,ly:pitch? . "pitch")
364 (,ly:translator? . "translator")
365 (,ly:font-metric? . "font metric")
366 (,ly:simple-closure? . "simple closure")
367 (,markup-list? . "list of markups")
368 (,markup? . "markup")
369 (,ly:music-list? . "list of music")
370 (,number-or-grob? . "number or grob")
371 (,number-or-string? . "number or string")
372 (,number-pair? . "pair of numbers")
373 (,number? . "number")
374 (,output-port? . "output port")
376 (,procedure? . "procedure")
377 (,rhythmic-location? . "rhythmic location")
378 (,scheme? . "any type")
379 (,string? . "string")
380 (,symbol? . "symbol")
381 (,vector? . "vector")))
383 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
386 (define (profile-measurements)
393 (ly:assoc-get 'gc-time-taken stats))
395 (ly:assoc-get 'total-cells-allocated stats 0)
398 (define (dump-profile base last this)
400 ((outname (format "~a.profile" (dir-basename base ".ly")))
401 (diff (map (lambda (y) (apply - y)) (zip this last))))
403 (ly:progress "\nWriting timing to ~a..." outname)
404 (format (open-file outname "w")
405 "time: ~a\ncells: ~a\n"
406 (if (ly:get-option 'dump-cpu-profile)
413 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
416 (define gc-dumping #f)
417 (define gc-protect-stat-count 0)
419 (define-public (dump-live-object-stats outfile)
422 (format outfile "~a: ~a\n" (car x) (cdr x)))
423 (sort (gc-live-object-stats)
425 (string<? (car x) (car y))))))
427 (define-public (dump-gc-protects)
428 (set! gc-protect-stat-count (1+ gc-protect-stat-count))
429 (let* ((protects (sort
430 (hash-table->alist (ly:protects))
432 (< (object-address (car a))
433 (object-address (car b))))))
435 (out-file-name (string-append
436 "gcstat-" (number->string gc-protect-stat-count)
438 (outfile (open-file out-file-name "w")))
441 (display (format "Dumping GC statistics ~a...\n" out-file-name))
447 (format "~a (~a) = ~a\n" (object-address x) c x)
451 (not (symbol? (car x))))
455 (format outfile "\nprotected symbols: ~a\n"
456 (apply + (map (lambda (obj-count) (if (symbol? (car obj-count))
461 ;; (display (ly:smob-protects))
463 (if (defined? 'gc-live-object-stats)
465 (display "Live object statistics: GC'ing\n")
469 (display "Asserting dead objects\n")
470 (ly:set-option 'debug-gc-assert-parsed-dead #t)
472 (ly:set-option 'debug-gc-assert-parsed-dead #f)
474 (set! stats (gc-live-object-stats))
475 (display "Dumping live object statistics.\n")
476 (dump-live-object-stats outfile)))
486 gc-protect-stat-count
488 (let ((sym-stat (assoc sym stats)))
493 '(protected-objects bytes-malloced cell-heap-size
503 (define (check-memory)
504 "read /proc/self to check up on memory use."
505 (define (gulp-file name)
506 (let* ((file (open-input-file name))
507 (text (read-delimited "" file)))
511 ((stat (gulp-file "/proc/self/status"))
512 (lines (string-split stat #\newline))
513 (interesting (filter identity
516 (string-match "^VmData:[ \t]*([0-9]*) kB" l))
518 (mem (string->number (match:substring (car interesting) 1)))
522 (display (format "VMDATA: ~a\n" mem))
531 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
534 (define (multi-fork count)
535 "Split this process in COUNT helpers. Returns either a list of pids,
536 or the number of the process."
537 (define (helper count acc)
540 ((pid (primitive-fork)))
543 (helper (1- count) (cons pid acc))))
548 (define-public (lilypond-main files)
549 "Entry point for LilyPond."
551 (eval-string (ly:command-line-code))
553 (if (ly:get-option 'help)
558 (if (ly:get-option 'show-available-fonts)
560 (ly:font-config-display-fonts)
565 (if (ly:get-option 'gui)
573 (if (ly:get-option 'read-file-list)
576 (> (string-length s) 0))
578 (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
582 (if (and (number? (ly:get-option 'job-count))
583 (>= (length files) (ly:get-option 'job-count)))
585 ((count (ly:get-option 'job-count))
586 (split-todo (split-list files count))
587 (joblist (multi-fork count))
590 (if (not (string-or-symbol? (ly:get-option 'log-file)))
591 (ly:set-option 'log-file "lilypond-multi-run"))
593 (if (number? joblist)
596 'log-file (format "~a-~a"
597 (ly:get-option 'log-file) joblist))
598 (set! files (vector-ref split-todo joblist)))
601 (ly:progress "\nForking into jobs: ~a\n" joblist)
604 (let* ((stat (cdr (waitpid pid))))
608 (acons (list-element-index joblist pid)
616 (logfile (format "~a-~a.log"
617 (ly:get-option 'log-file) job))
618 (log (ly:gulp-file logfile))
619 (len (string-length log))
620 (tail (substring log (max 0 (- len 1024)))))
622 (if (status:term-sig state)
625 (format (_ "job ~a terminated with signal: ~a")
626 job (status:term-sig state)))
628 (_ "logfile ~a (exit ~a):\n~a")
629 logfile (status:exit-val state) tail))))
634 (ly:error "Children ~a exited with errors." (map car errors)))
636 ;; must overwrite individual entries
637 (if (ly:get-option 'dump-profile)
638 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
640 (exit (if (null? errors) 0 1))))))
642 (if (string-or-symbol? (ly:get-option 'log-file))
643 (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
645 (let ((failed (lilypond-all files)))
646 (if (ly:get-option 'trace-scheme-coverage)
648 (coverage:show-all (lambda (f) (string-contains f "lilypond"))
653 (ly:error (_ "failed files: ~S") (string-join failed))
656 ;; HACK: be sure to exit with single newline
660 (define-public (lilypond-all files)
662 (separate-logs (ly:get-option 'separate-log-files))
665 (open-file (if (string-or-symbol? (ly:get-option 'log-file))
666 (format "~a.log" (ly:get-option 'log-file))
667 "/dev/tty") "a") #f))
668 (do-measurements (ly:get-option 'dump-profile))
669 (handler (lambda (key failed-file)
670 (set! failed (append (list failed-file) failed)))))
676 ((start-measurements (if do-measurements
677 (profile-measurements)
679 (base (dir-basename x ".ly"))
680 (all-settings (ly:all-options)))
683 (ly:stderr-redirect (format "~a.log" base) "w"))
685 (format ping-log "Procesing ~a\n" base))
687 (if (ly:get-option 'trace-memory-frequency)
688 (mtrace:start-trace (ly:get-option 'trace-memory-frequency)))
690 (lilypond-file handler x)
691 (if start-measurements
692 (dump-profile x start-measurements (profile-measurements)))
694 (if (ly:get-option 'trace-memory-frequency)
697 (mtrace:dump-results base)))
701 (ly:set-option (car s) (cdr s)))
704 (ly:clear-anonymous-modules)
705 (ly:set-option 'debug-gc-assert-parsed-dead #t)
707 (ly:set-option 'debug-gc-assert-parsed-dead #f)
710 (if (ly:get-option 'debug-gc)
712 (if (= (random 40) 1)
713 (ly:reset-all-fonts)))))
717 ;; we want the failed-files notice in the aggregrate logfile.
719 (format ping-log "Failed files: ~a\n" failed))
721 (if (ly:get-option 'dump-profile)
722 (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
726 (define (lilypond-file handler file-name)
727 (catch 'ly-file-failed
728 (lambda () (ly:parse-file file-name))
729 (lambda (x . args) (handler x file-name))))
731 (use-modules (scm editor))
733 (define-public (gui-main files)
735 (gui-no-files-handler))
737 (if (not (string? (ly:get-option 'log-file)))
738 (let* ((base (dir-basename (car files) ".ly"))
739 (log-name (string-append base ".log")))
740 (if (not (ly:get-option 'gui))
741 (ly:message (_ "Redirecting output to ~a...") log-name))
742 (ly:stderr-redirect log-name "w")
743 (ly:message "# -*-compilation-*-"))
745 (let ((failed (lilypond-all files)))
749 (ly:stderr-redirect "foo" "r")
750 (system (get-editor-command log-name 0 0 0))
751 (ly:error (_ "failed files: ~S") (string-join failed))
756 (define (gui-no-files-handler)
757 (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
758 ;; FIXME: soft-code, localize
759 (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
760 (cmd (get-editor-command welcome-ly 0 0 0)))
761 (ly:message (_ "Invoking `~a'...") cmd)