]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
don't exit in (check-memory) for only 100MB of VMDATA... We use MUCH more now.
[lilypond.git] / scm / lily.scm
1 ;;;; This file is part of LilyPond, the GNU music typesetter.
2 ;;;;
3 ;;;; Copyright (C) 1998--2011 Jan Nieuwenhuizen <janneke@gnu.org>
4 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
5 ;;;;
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.
10 ;;;;
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.
15 ;;;;
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/>.
18
19 ;; Internationalisation: (_i "to be translated") gets an entry in the
20 ;; POT file; (gettext ...) must be invoked explicitly to do the actual
21 ;; "translation".
22 ;;
23 ;; (define-macro (_i x) x)
24 ;; (define-macro-public _i (x) x)
25 ;; (define-public-macro _i (x) x)
26 ;; Abbrv-PWR!
27
28 (defmacro-public _i (x) x)
29
30 ;;; Boolean thunk - are we integrating Guile V2.0 or higher with LilyPond?
31 (define-public (guile-v2)
32   (string>? (version) "1.9.10"))
33
34 (read-enable 'positions)
35 (if (not (guile-v2))
36     (debug-enable 'debug)
37     (begin
38       (debug-enable 'backtrace)
39       (debug-set! show-file-name #t)))
40
41 (define-public PLATFORM
42   (string->symbol
43    (string-downcase
44     (car (string-tokenize (utsname:sysname (uname)))))))
45
46 (define scheme-options-definitions
47   `(
48     ;; NAMING: either
49
50     ;; - [subject-]object-object-verb +"ing"
51     ;; - [subject-]-verb-object-object
52
53     ;; Avoid overlong lines in `lilypond -dhelp'!  Strings should not
54     ;; be longer than 48 characters per line.
55
56     (anti-alias-factor 1
57 "Render at higher resolution (using given factor)
58 and scale down result to prevent jaggies in
59 PNG images.")
60     (aux-files #t
61 "Create .tex, .texi, .count files in the
62 EPS backend.")
63     (backend ps
64 "Select backend.  Possible values: 'eps, 'null,
65 'ps, 'scm, 'socket, 'svg.")
66     (check-internal-types #f
67 "Check every property assignment for types.")
68     (clip-systems #f
69 "Generate cut-out snippets of a score.")
70     (datadir #f
71 "LilyPond prefix for data files (read-only).")
72     (debug-gc #f
73 "Dump memory debugging statistics.")
74     (debug-gc-assert-parsed-dead #f
75 "For memory debugging: Ensure that all
76 references to parsed objects are dead.  This is
77 an internal option, and is switched on
78 automatically for `-ddebug-gc'.")
79     (debug-lexer #f
80 "Debug the flex lexer.")
81     (debug-page-breaking-scoring #f
82 "Dump scores for many different page breaking
83 configurations.")
84     (debug-parser #f
85 "Debug the bison parser.")
86     (debug-property-callbacks #f
87 "Debug cyclic callback chains.")
88     (debug-skylines #f
89 "Debug skylines.")
90     (delete-intermediate-files #t
91 "Delete unusable, intermediate PostScript files.")
92     (dump-profile #f
93 "Dump memory and time information for each file.")
94     (dump-cpu-profile #f
95 "Dump timing information (system-dependent).")
96     (dump-signatures #f
97 "Dump output signatures of each system.  Used for
98 regression testing.")
99     (eps-box-padding #f
100 "Pad left edge of the output EPS bounding box by
101 given amount (in mm).")
102     (gs-load-fonts #f
103 "Load fonts via Ghostscript.")
104     (gs-load-lily-fonts #f
105 "Load only LilyPond fonts via Ghostscript.")
106     (gui #f
107 "Run LilyPond from a GUI and redirect stderr to
108 a log file.")
109     (help #f
110 "Show this help.")
111     (include-book-title-preview #t
112 "Include book titles in preview images.")
113     (include-eps-fonts #t
114 "Include fonts in separate-system EPS files.")
115     (include-settings #f
116 "Include file for global settings, included before the score is processed.")
117     (job-count #f
118 "Process in parallel, using the given number of
119 jobs.")
120     (log-file #f
121 "If string FOO is given as argument, redirect
122 output to log file `FOO.log'.")
123     (midi-extension ,(if (eq? PLATFORM 'windows)
124                          "mid"
125                          "midi")
126 "Set the default file extension for MIDI output
127 file to given string.")
128     (music-strings-to-paths #f
129 "Convert text strings to paths when glyphs belong
130 to a music font.")
131     (old-relative #f
132 "Make \\relative mode for simultaneous music work
133 similar to chord syntax.")
134     (point-and-click #t
135 "Add point & click links to PDF output.")
136     (paper-size "a4"
137 "Set default paper size.")
138     (pixmap-format "png16m"
139 "Set GhostScript's output format for pixel images.")
140     (preview #f
141 "Create preview images also.")
142     (print-pages #t
143 "Print pages in the normal way.")
144     (protected-scheme-parsing #t
145 "Continue when errors in inline scheme are caught
146 in the parser.  If #f, halt on errors and print
147 a stack trace.")
148     (profile-property-accesses #f
149 "Keep statistics of get_property() calls.")
150     (resolution 101
151 "Set resolution for generating PNG pixmaps to
152 given value (in dpi).")
153     (read-file-list #f
154 "Specify name of a file which contains a list of
155 input files to be processed.")
156     (relative-includes #f
157 "When processing an \\include command, look for
158 the included file relative to the current file
159 (instead of the root file)")
160     (safe #f
161 "Run in safer mode.")
162     (separate-log-files #f
163 "For input files `FILE1.ly', `FILE2.ly', ...
164 output log data to files `FILE1.log',
165 `FILE2.log', ...")
166     (show-available-fonts #f
167 "List available font names.")
168     (strict-infinity-checking #f
169 "Force a crash on encountering Inf and NaN
170 floating point exceptions.")
171     (strip-output-dir #t
172 "Don't use directories from input files while
173 constructing output file names.")
174     (svg-woff #f
175 "Use woff font files in SVG backend.")
176     (trace-memory-frequency #f
177 "Record Scheme cell usage this many times per
178 second.  Dump results to `FILE.stacks' and
179 `FILE.graph'.")
180     (trace-scheme-coverage #f
181 "Record coverage of Scheme files in `FILE.cov'.")
182     (verbose ,(ly:verbose-output?)
183 "Verbose output, i.e. loglevel at least DEBUG (read-only).")
184     (warning-as-error #f
185 "Change all warning and programming_error
186 messages into errors.")
187     ))
188
189 ;; Need to do this in the beginning.  Other parts of the Scheme
190 ;; initialization depend on these options.
191
192 (for-each (lambda (x)
193             (ly:add-option (car x) (cadr x) (caddr x)))
194           scheme-options-definitions)
195
196 (for-each (lambda (x)
197             (ly:set-option (car x) (cdr x)))
198           (eval-string (ly:command-line-options)))
199
200 (debug-set! stack 0)
201
202 (if (defined? 'set-debug-cell-accesses!)
203     (set-debug-cell-accesses! #f))
204
205 ;;(set-debug-cell-accesses! 1000)
206
207 (use-modules (ice-9 regex)
208              (ice-9 safe)
209              (ice-9 format)
210              (ice-9 rdelim)
211              (ice-9 optargs)
212              (oop goops)
213              (srfi srfi-1)
214              (srfi srfi-13)
215              (srfi srfi-14)
216              (scm clip-region)
217              (scm memory-trace)
218              (scm coverage))
219
220 (define-public _ gettext)
221 ;;; There are new modules defined in Guile V2.0 which we need to use.
222 ;;
223 ;;  Modules and scheme files loaded by lily.scm use currying
224 ;;  in Guile V2 this needs a module which is not present in Guile V1.8
225 ;;
226
227 (cond
228   ((guile-v2)
229    (ly:debug (_ "Using (ice-9 curried-definitions) module\n"))
230    (use-modules (ice-9 curried-definitions)))
231   (else
232     (ly:debug (_ "Guile 1.8\n"))))
233
234 ;; TODO add in modules for V1.8.7 deprecated in V2.0 and integrated
235 ;; into Guile base code, like (ice-9 syncase).
236 ;;
237
238 (define-public fancy-format
239   format)
240
241 (define-public (ergonomic-simple-format dest . rest)
242   "Like ice-9's @code{format}, but without the memory consumption."
243   (if (string? dest)
244       (apply simple-format (cons #f (cons dest rest)))
245       (apply simple-format (cons dest rest))))
246
247 (define format
248   ergonomic-simple-format)
249
250 ;; my display
251 (define-public (myd k v)
252   (display k)
253   (display ": ")
254   (display v)
255   (display ", ")
256   v)
257
258 (define-public (print . args)
259   (apply format (cons (current-output-port) args)))
260
261
262 ;;; General settings.
263 ;;;
264 ;;; Debugging evaluator is slower.  This should have a more sensible
265 ;;; default.
266
267
268 (if (or (ly:get-option 'verbose)
269         (ly:get-option 'trace-memory-frequency)
270         (ly:get-option 'trace-scheme-coverage))
271     (begin
272       (ly:set-option 'protected-scheme-parsing #f)
273       (debug-enable 'backtrace)
274       (read-enable 'positions)))
275
276 (if (ly:get-option 'trace-scheme-coverage)
277     (coverage:enable))
278
279 (define-public parser #f)
280
281 (define music-string-to-path-backends
282   '(svg))
283
284 (if (memq (ly:get-option 'backend) music-string-to-path-backends)
285     (ly:set-option 'music-strings-to-paths #t))
286
287
288 (define-public (ly:load x)
289   (let* ((file-name (%search-load-path x)))
290     (ly:debug "[~A" file-name)
291     (if (not file-name)
292         (ly:error (_ "cannot find: ~A") x))
293     (primitive-load-path file-name)  ;; to support Guile V2 autocompile
294     ;; TODO: Any chance to use ly:debug here? Need to extend it to prevent
295     ;;       a newline in this case
296     (if (ly:get-option 'verbose)
297         (ly:progress "]\n"))))
298
299 (define-public DOS
300   (let ((platform (string-tokenize
301                    (vector-ref (uname) 0) char-set:letter+digit)))
302     (if (null? (cdr platform)) #f
303         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
304
305 (define (slashify x)
306   (if (string-index x #\\)
307       x
308       (string-regexp-substitute
309         "//*" "/"
310         (string-regexp-substitute "\\\\" "/" x))))
311
312 (define-public (ly-getcwd)
313   (if (eq? PLATFORM 'windows)
314       (slashify (getcwd))
315       (getcwd)))
316
317 (define-public (is-absolute? file-name)
318   (let ((file-name-length (string-length file-name)))
319     (if (= file-name-length 0)
320         #f
321         (or (eq? (string-ref file-name 0) #\/)
322             (and (eq? PLATFORM 'windows)
323                  (> file-name-length 2)
324                  (eq? (string-ref file-name 1) #\:)
325                  (eq? (string-ref file-name 2) #\/))))))
326
327 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
328 ;;; If necessary, emulate Guile V2 module_export_all! for Guile V1.8.n
329 (cond-expand
330  ((not guile-v2)
331   (define (module-export-all! mod)
332     (define (fresh-interface!)
333       (let ((iface (make-module)))
334         (set-module-name! iface (module-name mod))
335         ;; for guile 2: (set-module-version! iface (module-version mod))
336         (set-module-kind! iface 'interface)
337         (set-module-public-interface! mod iface)
338         iface))
339     (let ((iface (or (module-public-interface mod)
340                      (fresh-interface!))))
341       (set-module-obarray! iface (module-obarray mod))))))
342
343 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
344 (define (type-check-list location signature arguments)
345   "Typecheck a list of arguments against a list of type predicates.
346 Print a message at LOCATION if any predicate failed."
347   (define (recursion-helper signature arguments count)
348     (define (helper pred? arg count)
349       (if (not (pred? arg))
350           (begin
351             (ly:input-message
352              location
353              (format
354               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
355               count (type-name pred?) arg))
356             #f)
357           #t))
358
359     (if (null? signature)
360         #t
361         (and (helper (car signature) (car arguments) count)
362              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
363   (recursion-helper signature arguments 1))
364
365
366 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
367 ;; Safe definitions utility
368
369 (define safe-objects
370   (list))
371
372 (define-macro (define-safe-public arglist . body)
373   "Define a variable, export it, and mark it as safe, i.e. usable in
374 LilyPond safe mode.  The syntax is the same as `define*-public'."
375   (define (get-symbol arg)
376     (if (pair? arg)
377         (get-symbol (car arg))
378         arg))
379
380   (let ((safe-symbol (get-symbol arglist)))
381     `(begin
382        (define*-public ,arglist
383          ,@body)
384        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
385                                 safe-objects))
386        ,safe-symbol)))
387
388 (define-safe-public (lilypond-version)
389   (string-join
390    (map (lambda (x) (if (symbol? x)
391                         (symbol->string x)
392                         (number->string x)))
393         (ly:version))
394    "."))
395
396 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
397 ;; init pitch system
398
399 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
400
401 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
402 ;; other files.
403
404 ;;
405 ;;  List of Scheme files to be loaded into the (lily) module.
406 ;;
407 ;;  - Library definitions, need to be at the head of the list
408 (define init-scheme-files-lib
409   '("lily-library.scm"
410     "output-lib.scm"))
411 ;;  - Files containing definitions used later by other files later in load
412 (define init-scheme-files-used
413   '("markup-macros.scm"))
414 ;;  - Main body of files to be loaded
415 (define init-scheme-files-body
416   '("file-cache.scm"
417     "define-event-classes.scm"
418     "define-music-callbacks.scm"
419     "define-music-types.scm"
420     "define-note-names.scm"
421     "c++.scm"
422     "chord-entry.scm"
423     "stencil.scm"
424     "define-markup-commands.scm"
425     "markup.scm"
426     "modal-transforms.scm"
427     "chord-generic-names.scm"
428     "chord-ignatzek-names.scm"
429     "music-functions.scm"
430     "part-combiner.scm"
431     "autochange.scm"
432     "define-music-properties.scm"
433     "time-signature-settings.scm"
434     "auto-beam.scm"
435     "chord-name.scm"
436     "bezier-tools.scm"
437     "parser-ly-from-scheme.scm"
438     "ly-syntax-constructors.scm"
439
440     "define-context-properties.scm"
441     "translation-functions.scm"
442     "script.scm"
443     "midi.scm"
444     "layout-beam.scm"
445     "parser-clef.scm"
446     "layout-slur.scm"
447     "font.scm"
448     "encoding.scm"
449
450     "flag-styles.scm"
451     "fret-diagrams.scm"
452     "tablature.scm"
453     "harp-pedals.scm"
454     "define-woodwind-diagrams.scm"
455     "display-woodwind-diagrams.scm"
456     "predefined-fretboards.scm"
457     "define-grob-properties.scm"
458     "define-grobs.scm"
459     "define-grob-interfaces.scm"
460     "define-stencil-commands.scm"
461     "titling.scm"
462
463     "paper.scm"
464     "backend-library.scm"
465     "x11-color.scm"))
466 ;;  - Files to be loaded last
467 (define init-scheme-files-tail
468 ;;  - must be after everything has been defined
469   '("safe-lily.scm"))
470 ;;
471 ;; Now construct the load list
472 ;;
473 (define init-scheme-files
474   (append init-scheme-files-lib
475           init-scheme-files-used
476           init-scheme-files-body
477           init-scheme-files-tail))
478
479 (for-each ly:load init-scheme-files)
480
481 (define-public r5rs-primary-predicates
482   `((,boolean? . "boolean")
483     (,char? . "character")
484     (,number? . "number")
485     (,pair? . "pair")
486     (,port? . "port")
487     (,procedure? . "procedure")
488     (,string? . "string")
489     (,symbol? . "symbol")
490     (,vector? . "vector")))
491
492 (define-public r5rs-secondary-predicates
493   `((,char-alphabetic? . "alphabetic character")
494     (,char-lower-case? . "lower-case character")
495     (,char-numeric? . "numeric character")
496     (,char-upper-case? . "upper-case character")
497     (,char-whitespace? . "whitespace character")
498
499     (,complex? . "complex number")
500     (,even? . "even number")
501     (,exact? . "exact number")
502     (,inexact? . "inexact number")
503     (,integer? . "integer")
504     (,negative? . "negative number")
505     (,odd? . "odd number")
506     (,positive? . "positive number")
507     (,rational? . "rational number")
508     (,real? . "real number")
509     (,zero? . "zero")
510
511     (,list? . "list")
512     (,null? . "null")
513
514     (,input-port? . "input port")
515     (,output-port? . "output port")
516
517     ;; would this ever be used?
518     (,eof-object? . "end-of-file object")
519     ))
520
521 (define-public guile-predicates
522   `((,hash-table? . "hash table")
523   ))
524
525 (define-public lilypond-scheme-predicates
526   `((,boolean-or-symbol? . "boolean or symbol")
527     (,color? . "color")
528     (,cheap-list? . "list")
529     (,grob-list? . "list of grobs")
530     ;; this is built on cheap-list
531     (,list-or-symbol? . "list or symbol")
532     (,markup? . "markup")
533     (,markup-command-list? . "markup command list")
534     (,markup-list? . "markup list")
535     (,moment-pair? . "pair of moment objects")
536     (,number-or-grob? . "number or grob")
537     (,number-or-pair? . "number or pair")
538     (,number-or-string? . "number or string")
539     (,number-pair? . "pair of numbers")
540     (,rhythmic-location? . "rhythmic location")
541     (,scheme? . "any type")
542     (,string-or-pair? . "string or pair")
543     (,string-or-symbol? . "string or symbol")
544     ))
545
546 (define-public lilypond-exported-predicates
547   `((,ly:box? . "box")
548     (,ly:context? . "context")
549     (,ly:dimension? . "dimension, in staff space")
550     (,ly:dir? . "direction")
551     (,ly:dispatcher? . "dispatcher")
552     (,ly:duration? . "duration")
553     (,ly:font-metric? . "font metric")
554     (,ly:grob? . "graphical (layout) object")
555     (,ly:grob-array? . "array of grobs")
556     (,ly:input-location? . "input location")
557     (,ly:item? . "item")
558     (,ly:iterator? . "iterator")
559     (,ly:lily-lexer? . "lily-lexer")
560     (,ly:lily-parser? . "lily-parser")
561     (,ly:listener? . "listener")
562     (,ly:moment? . "moment")
563     (,ly:music? . "music")
564     (,ly:music-function? . "music function")
565     (,ly:music-list? . "list of music objects")
566     (,ly:music-output? . "music output")
567     (,ly:otf-font? . "OpenType font")
568     (,ly:output-def? . "output definition")
569     (,ly:page-marker? . "page marker")
570     (,ly:pango-font? . "pango font")
571     (,ly:paper-book? . "paper book")
572     (,ly:paper-system? . "paper-system Prob")
573     (,ly:pitch? . "pitch")
574     (,ly:prob? . "property object")
575     (,ly:score? . "score")
576     (,ly:simple-closure? . "simple closure")
577     (,ly:skyline? . "skyline")
578     (,ly:skyline-pair? . "pair of skylines")
579     (,ly:source-file? . "source file")
580     (,ly:spanner? . "spanner")
581     (,ly:stencil? . "stencil")
582     (,ly:stream-event? . "stream event")
583     (,ly:translator? . "translator")
584     (,ly:translator-group? . "translator group")
585     ))
586
587
588 (set! type-p-name-alist
589       (append r5rs-primary-predicates
590               r5rs-secondary-predicates
591               guile-predicates
592               lilypond-scheme-predicates
593               lilypond-exported-predicates))
594
595
596 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
597 ;; timing
598
599 (define (profile-measurements)
600   (let* ((t (times))
601          (stats (gc-stats)))
602     (list (- (+ (tms:cutime t)
603                 (tms:utime t))
604              (assoc-get 'gc-time-taken stats))
605           (assoc-get 'total-cells-allocated  stats 0))))
606
607 (define (dump-profile base last this)
608   (let* ((outname (format #f "~a.profile" (dir-basename base ".ly")))
609          (diff (map (lambda (y) (apply - y)) (zip this last))))
610     (ly:progress "\nWriting timing to ~a..." outname)
611     (format (open-file outname "w")
612             "time: ~a\ncells: ~a\n"
613             (if (ly:get-option 'dump-cpu-profile)
614                 (car diff)
615                 0)
616             (cadr diff))))
617
618 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
619 ;; debug memory leaks
620
621 (define gc-dumping
622   #f)
623
624 (define gc-protect-stat-count
625   0)
626
627 (define-public (dump-live-object-stats outfile)
628   (for-each (lambda (x)
629               (format outfile "~a: ~a\n" (car x) (cdr x)))
630             (sort (gc-live-object-stats)
631                   (lambda (x y)
632                     (string<? (car x) (car y))))))
633
634 (define-public (dump-gc-protects)
635   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
636   (let* ((protects (sort (hash-table->alist (ly:protects))
637                          (lambda (a b)
638                            (< (object-address (car a))
639                               (object-address (car b))))))
640         (out-file-name (string-append
641                        "gcstat-" (number->string gc-protect-stat-count)
642                        ".scm"))
643         (outfile (open-file out-file-name "w")))
644     (set! gc-dumping #t)
645     (ly:progress "Dumping GC statistics ~a...\n" out-file-name)
646     (for-each (lambda (y)
647                 (let ((x (car y))
648                       (c (cdr y)))
649                   (format outfile "~a (~a) = ~a\n" (object-address x) c x)))
650               (filter
651                (lambda (x)
652                  (not (symbol? (car x))))
653                protects))
654     (format outfile "\nprotected symbols: ~a\n"
655             (apply + (map (lambda (obj-count)
656                             (if (symbol? (car obj-count))
657                                 (cdr obj-count)
658                                 0))
659                           protects)))
660
661     ;; (display (ly:smob-protects))
662     (newline outfile)
663     (if (defined? 'gc-live-object-stats)
664         (let* ((stats #f))
665           (ly:progress "Live object statistics: GC'ing\n")
666           (ly:reset-all-fonts)
667           (gc)
668           (gc)
669           (ly:progress "Asserting dead objects\n")
670           (ly:set-option 'debug-gc-assert-parsed-dead #t)
671           (gc)
672           (ly:set-option 'debug-gc-assert-parsed-dead #f)
673           (set! stats (gc-live-object-stats))
674           (ly:progress "Dumping live object statistics.\n")
675           (dump-live-object-stats outfile)))
676     (newline outfile)
677     (let* ((stats (gc-stats)))
678       (for-each (lambda (sym)
679                   (format outfile "~a ~a ~a\n"
680                           gc-protect-stat-count
681                           sym
682                           (assoc-get sym stats "?")))
683                 '(protected-objects bytes-malloced cell-heap-size)))
684     (set! gc-dumping #f)
685     (close-port outfile)))
686
687 (define (check-memory)
688   "Read `/proc/self' to check up on memory use."
689   (define (gulp-file name)
690     (let* ((file (open-input-file name))
691            (text (read-delimited "" file)))
692       (close file)
693       text))
694
695   (let* ((stat (gulp-file "/proc/self/status"))
696          (lines (string-split stat #\newline))
697          (interesting (filter identity
698                               (map
699                                (lambda (l)
700                                  (string-match "^VmData:[ \t]*([0-9]*) kB" l))
701                                lines)))
702          (mem (string->number (match:substring (car interesting) 1))))
703     (format #t "VMDATA: ~a\n" mem)
704     (display (gc-stats))
705     (newline)
706     (if (> mem 500000)
707         (begin (dump-gc-protects)
708                (raise 1)))))
709
710 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
711
712 (define (multi-fork count)
713   "Split this process into COUNT helpers.  Returns either a list of
714 PIDs or the number of the process."
715   (define (helper count acc)
716     (if (> count 0)
717         (let* ((pid (primitive-fork)))
718               (if (= pid 0)
719                   (1- count)
720                   (helper (1- count) (cons pid acc))))
721         acc))
722
723   (helper count '()))
724
725 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
726
727 (define* (ly:exit status #:optional (silently #f))
728   "Exit function for lilypond"
729   (if (not silently)
730       (case status
731         ((0) (ly:basic-progress (_ "Success: compilation successfully completed")))
732         ((1) (ly:warning (_ "Compilation completed with warnings or errors")))
733         (else (ly:message ""))))
734   (exit status))
735
736 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
737
738 (define-public (lilypond-main files)
739   "Entry point for LilyPond."
740   (eval-string (ly:command-line-code))
741   (if (ly:get-option 'help)
742       (begin (ly:option-usage)
743              (ly:exit 0 #t)))
744   (if (ly:get-option 'show-available-fonts)
745       (begin (ly:font-config-display-fonts)
746              (ly:exit 0 #t)))
747   (if (ly:get-option 'gui)
748       (gui-main files))
749   (if (null? files)
750       (begin (ly:usage)
751              (ly:exit 2 #t)))
752   (if (ly:get-option 'read-file-list)
753       (set! files
754             (filter (lambda (s)
755                       (> (string-length s) 0))
756                     (apply append
757                            (map (lambda (f)
758                                   (string-split (ly:gulp-file f) #\nl))
759                                 files)))))
760   (if (and (number? (ly:get-option 'job-count))
761            (>= (length files) (ly:get-option 'job-count)))
762       (let* ((count (ly:get-option 'job-count))
763              (split-todo (split-list files count))
764              (joblist (multi-fork count))
765              (errors '()))
766         (if (not (string-or-symbol? (ly:get-option 'log-file)))
767             (ly:set-option 'log-file "lilypond-multi-run"))
768         (if (number? joblist)
769             (begin (ly:set-option
770                     'log-file (format #f "~a-~a"
771                                       (ly:get-option 'log-file) joblist))
772                     (set! files (vector-ref split-todo joblist)))
773             (begin (ly:progress "\nForking into jobs:  ~a\n" joblist)
774                    (for-each
775                     (lambda (pid)
776                       (let* ((stat (cdr (waitpid pid))))
777                         (if (not (= stat 0))
778                             (set! errors
779                                   (acons (list-element-index joblist pid)
780                                  stat errors)))))
781                     joblist)
782                    (for-each
783                     (lambda (x)
784                       (let* ((job (car x))
785                              (state (cdr x))
786                              (logfile (format #f "~a-~a.log"
787                                               (ly:get-option 'log-file) job))
788                              (log (ly:gulp-file logfile))
789                              (len (string-length log))
790                              (tail (substring  log (max 0 (- len 1024)))))
791                         (if (status:term-sig state)
792                             (ly:message
793                              "\n\n~a\n"
794                              (format #f (_ "job ~a terminated with signal: ~a")
795                                      job (status:term-sig state)))
796                             (ly:message
797                              (_ "logfile ~a (exit ~a):\n~a")
798                              logfile (status:exit-val state) tail))))
799                       errors)
800                      (if (pair? errors)
801                          (ly:error "Children ~a exited with errors."
802                                    (map car errors)))
803                      ;; must overwrite individual entries
804                      (if (ly:get-option 'dump-profile)
805                          (dump-profile "lily-run-total"
806                                        '(0 0) (profile-measurements)))
807                      (if (null? errors)
808                          (ly:exit 0 #f)
809                          (ly:exit 1 #f))))))
810
811   (if (string-or-symbol? (ly:get-option 'log-file))
812       (ly:stderr-redirect (format #f "~a.log" (ly:get-option 'log-file)) "w"))
813   (let ((failed (lilypond-all files)))
814     (if (ly:get-option 'trace-scheme-coverage)
815         (begin
816           (coverage:show-all (lambda (f)
817                                (string-contains f "lilypond")))))
818     (if (pair? failed)
819         (begin (ly:error (_ "failed files: ~S") (string-join failed))
820                (ly:exit 1 #f))
821         (begin
822           (ly:exit 0 #f)))))
823
824
825 (define-public (lilypond-all files)
826   (let* ((failed '())
827          (separate-logs (ly:get-option 'separate-log-files))
828          (ping-log
829           (if separate-logs
830               (open-file (if (string-or-symbol? (ly:get-option 'log-file))
831                              (format #f "~a.log" (ly:get-option 'log-file))
832                      "/dev/stderr") "a") #f))
833          (do-measurements (ly:get-option 'dump-profile))
834          (handler (lambda (key failed-file)
835                     (set! failed (append (list failed-file) failed)))))
836     (gc)
837     (for-each
838      (lambda (x)
839        (let* ((start-measurements (if do-measurements
840                                       (profile-measurements)
841                                       #f))
842               (base (dir-basename x ".ly"))
843               (all-settings (ly:all-options)))
844          (if separate-logs
845              (ly:stderr-redirect (format #f "~a.log" base) "w"))
846          (if ping-log
847              (format ping-log "Processing ~a\n" base))
848          (if (ly:get-option 'trace-memory-frequency)
849              (mtrace:start-trace  (ly:get-option 'trace-memory-frequency)))
850          (lilypond-file handler x)
851          (if start-measurements
852              (dump-profile x start-measurements (profile-measurements)))
853          (if (ly:get-option 'trace-memory-frequency)
854              (begin (mtrace:stop-trace)
855                     (mtrace:dump-results base)))
856          (for-each (lambda (s)
857                      (ly:set-option (car s) (cdr s)))
858                    all-settings)
859          (ly:set-option 'debug-gc-assert-parsed-dead #t)
860          (gc)
861          (ly:set-option 'debug-gc-assert-parsed-dead #f)
862          (if (ly:get-option 'debug-gc)
863              (dump-gc-protects)
864              (ly:reset-all-fonts))))
865      files)
866
867     ;; Ensure a notice re failed files is written to aggregate logfile.
868     (if ping-log
869         (format ping-log "Failed files: ~a\n" failed))
870     (if (ly:get-option 'dump-profile)
871         (dump-profile "lily-run-total" '(0 0) (profile-measurements)))
872     failed))
873
874 (define (lilypond-file handler file-name)
875   (catch 'ly-file-failed
876          (lambda () (ly:parse-file file-name))
877          (lambda (x . args) (handler x file-name))))
878
879 (use-modules (scm editor))
880
881 (define-public (gui-main files)
882   (if (null? files)
883       (gui-no-files-handler))
884   (if (not (string? (ly:get-option 'log-file)))
885       (let* ((base (dir-basename (car files) ".ly"))
886              (log-name (string-append base ".log")))
887         (if (not (ly:get-option 'gui))
888             (ly:message (_ "Redirecting output to ~a...") log-name))
889         (ly:stderr-redirect log-name "w")
890         (ly:message "# -*-compilation-*-"))
891       (let ((failed (lilypond-all files)))
892         (if (pair? failed)
893             (begin
894               ;; ugh
895               (ly:stderr-redirect "foo" "r")
896               (system (get-editor-command log-name 0 0 0))
897               (ly:error (_ "failed files: ~S") (string-join failed))
898               ;; not reached?
899               (exit 1))
900             (ly:exit 0 #f)))))
901
902 (define (gui-no-files-handler)
903   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
904          ;; FIXME: soft-code, localize
905          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
906          (cmd (get-editor-command welcome-ly 0 0 0)))
907     (ly:message (_ "Invoking `~a'...\n") cmd)
908     (system cmd)
909     (ly:exit 1 #f)))