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