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