]> git.donarmstrong.com Git - lilypond.git/blob - scm/lily.scm
dump profile info for test too.
[lilypond.git] / scm / lily.scm
1 ;;;; lily.scm -- toplevel Scheme stuff
2 ;;;;
3 ;;;;  source file of the GNU LilyPond music typesetter
4 ;;;; 
5 ;;;; (c) 1998--2006 Jan Nieuwenhuizen <janneke@gnu.org>
6 ;;;; Han-Wen Nienhuys <hanwen@xs4all.nl>
7
8
9 (define (define-scheme-options)
10   (for-each (lambda (x)
11               (ly:add-option (car x) (cadr x) (caddr x)))
12           
13             `(
14
15               ;; NAMING: either
16
17               ;; - [subject-]object-object-verb +"ing"
18               ;; - [subject-]-verb-object-object
19
20               (anti-alias-factor 1 "render at higher resolution and scale down result\nto prevent jaggies in PNG")
21               (check-internal-types #f "check every property assignment for types")
22               (clip-systems #f "Generate cut-out snippets of a score")
23               (debug-gc #f "dump memory debugging statistics")
24               (debug-gc-assert-parsed-dead #f "for memory debugging:
25 ensure that all refs to parsed objects are dead.  This is an internal option, and is switched on automatically for -ddebug-gc.") 
26               (debug-lexer #f "debug the flex lexer")
27               (debug-midi #f "generate human readable MIDI")
28               (debug-parser #f "debug the bison parser")
29               (debug-skylines #f "debug skylines")
30               (delete-intermediate-files #f
31                                          "delete unusable PostScript files")
32               (dump-profile #f "dump timing information for each file")
33               (dump-tweaks #f "dump page layout and tweaks for each score having the tweak-key layout property set.")
34               (dump-signatures #f "dump output signatures of each system")
35               
36               (eps-box-padding #f "Pad EPS bounding box left edge by this much to guarantee alignment between systems")
37
38               (gs-load-fonts #f
39                             "load fonts via Ghostscript.")
40               (gui #f "running from gui; redirect stderr to log file")
41
42               (include-book-title-preview #t "include book-titles in preview images.")
43               (include-eps-fonts #t "Include fonts in separate-system EPS files.")
44               (job-count #f "Process in parallel") 
45               (log-file #f "redirect output to log FILE.log")
46
47               (old-relative #f
48                             "relative for simultaneous music works
49 similar to chord syntax")
50               (object-keys #f
51                            "experimental mechanism for remembering tweaks")
52               (point-and-click #t "use point & click")
53               (paper-size "a4" "the default paper size")
54               (pixmap-format "png16m" "GS format to use for pixel images")
55               (protected-scheme-parsing #t "continue when finding errors in inline
56 scheme are caught in the parser. If off, halt 
57 on errors, and print a stack trace.")
58               (profile-property-accesses #f "keep statistics of get_property() calls.")
59               
60               (resolution 101 "resolution for generating PNG bitmaps")
61               (read-file-list #f "Read files to be processed from command line arguments")
62
63               (safe #f "Run safely")
64               (strict-infinity-checking #f "If yes, crash on encountering Inf/NaN")
65
66               (ttf-verbosity 0
67                              "how much verbosity for TTF font embedding?")
68
69               (show-available-fonts #f
70                                     "List  font names available.")
71
72               (verbose ,(ly:command-line-verbose?) "value for the --verbose flag")
73               )))
74
75
76 ;; need to do this in the beginning. Other parts of the
77 ;; Scheme init depend on these options.
78 ;;
79 (define-scheme-options)
80
81 (debug-set! stack 0)
82
83 (if (defined? 'set-debug-cell-accesses!)
84     (set-debug-cell-accesses! #f))
85
86                                         ;(set-debug-cell-accesses! 1000)
87
88 (use-modules (ice-9 regex)
89              (ice-9 safe)
90              (ice-9 optargs)
91              (oop goops)
92              (srfi srfi-1)
93              (srfi srfi-13)
94              (srfi srfi-14)
95              (scm clip-region)
96
97              )
98
99
100 ;; my display
101 (define-public (myd k v) (display k) (display ": ") (display v) (display ", "))
102
103 (define-public (print . args)
104   (apply format (cons (current-output-port) args)))
105
106
107 ;;; General settings
108 ;;; debugging evaluator is slower.  This should
109 ;;; have a more sensible default.
110
111 (if (ly:get-option 'verbose)
112     (begin
113       (ly:set-option 'protected-scheme-parsing #f)
114       (debug-enable 'debug)
115       (debug-enable 'backtrace)
116       (read-enable 'positions)))
117
118 (define-public tex-backend?
119   (member (ly:output-backend) '("texstr" "tex")))
120
121 (define-public parser #f)
122
123 (define-public (lilypond-version)
124   (string-join
125    (map (lambda (x) (if (symbol? x)
126                         (symbol->string x)
127                         (number->string x)))
128         (ly:version))
129    "."))
130
131
132 ;; TeX C++ code actually hooks into TEX_STRING_HASHLIMIT 
133 (define-public TEX_STRING_HASHLIMIT 10000000)
134
135
136
137 ;; gettext wrapper for guile < 1.7.2
138 (if (defined? 'gettext)
139     (define-public _ gettext)
140     (define-public _ ly:gettext))
141
142 (define-public (ly:load x)
143   (let* ((file-name (%search-load-path x)))
144     (if (ly:get-option 'verbose)
145         (ly:progress "[~A" file-name))
146     (if (not file-name)
147         (ly:error (_ "cannot find: ~A") x))
148     (primitive-load file-name)
149     (if (ly:get-option 'verbose)
150         (ly:progress "]"))))
151
152 ;; Cygwin
153 ;; #(CYGWIN_NT-5.1 Hostname 1.5.12(0.116/4/2) 2004-11-10 08:34 i686)
154 ;;
155 ;; Debian
156 ;; #(Linux hostname 2.4.27-1-686 #1 Fri Sep 3 06:28:00 UTC 2004 i686)
157 ;;
158 ;; Mingw
159 ;; #(Windows XP HOSTNAME build 2600 5.01 Service Pack 1 i686)
160 ;;
161
162 ;; ugh, code dup.
163 (define-public PLATFORM
164   (string->symbol
165    (string-downcase
166     (car (string-tokenize (vector-ref (uname) 0) char-set:letter)))))
167
168 (define-public DOS
169   (let ((platform (string-tokenize
170                    (vector-ref (uname) 0) char-set:letter+digit)))
171     (if (null? (cdr platform)) #f
172         (member (string-downcase (cadr platform)) '("95" "98" "me")))))
173
174 (case PLATFORM
175   ((windows)
176    (define native-getcwd getcwd)
177    (define (slashify x)
178      (if (string-index x #\\)
179          x
180          (string-regexp-substitute
181           "//*" "/"
182           (string-regexp-substitute "\\\\" "/" x))))
183    ;; FIXME: this prints a warning.
184    (define-public (ly-getcwd)
185      (slashify (native-getcwd))))
186   (else (define-public ly-getcwd getcwd)))
187
188 (define-public (is-absolute? file-name)
189   (let ((file-name-length (string-length file-name)))
190     (if (= file-name-length 0)
191         #f
192         (or (eq? (string-ref file-name 0) #\/)
193             (and (eq? PLATFORM 'windows)
194                  (> file-name-length 2)
195                  (eq? (string-ref file-name 1) #\:)
196                  (eq? (string-ref file-name 2) #\/))))))
197
198 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
199
200 (define (type-check-list location signature arguments)
201   "Typecheck a list of arguments against a list of type
202 predicates. Print a message at LOCATION if any predicate failed."
203
204   (define (recursion-helper signature arguments count) 
205     (define (helper pred? arg count) 
206       (if (not (pred? arg))
207
208           (begin
209             (ly:input-message
210              location
211              (format
212               #f (_ "wrong type for argument ~a.  Expecting ~a, found ~s")
213               count (type-name pred?) arg))
214             #f)
215           #t))
216
217     (if (null? signature)
218         #t
219         (and (helper (car signature) (car arguments) count)
220              (recursion-helper (cdr signature) (cdr arguments) (1+ count)))))
221
222   (recursion-helper signature arguments 1))
223
224 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
225 ;;  output
226
227
228 ;;(define-public (output-framework) (write "hello\n"))
229
230 (define output-tex-module
231   (make-module 1021 (list (resolve-interface '(scm output-tex)))))
232 (define output-ps-module
233   (make-module 1021 (list (resolve-interface '(scm output-ps)))))
234
235 (define-public (ps-output-expression expr port)
236   (display (eval expr output-ps-module) port))
237
238 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
239 ;; Safe definitions utility
240 (define safe-objects (list))
241
242 (define-macro (define-safe-public arglist . body)
243   "Define a variable, export it, and mark it as safe, ie usable in LilyPond safe mode.
244 The syntax is the same as `define*-public'."
245   (define (get-symbol arg)
246     (if (pair? arg)
247         (get-symbol (car arg))
248         arg))
249   (let ((safe-symbol (get-symbol arglist)))
250     `(begin
251        (define*-public ,arglist
252          ,@body)
253        (set! safe-objects (cons (cons ',safe-symbol ,safe-symbol)
254                                 safe-objects))
255        ,safe-symbol)))
256
257 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
258 ;; init pitch system
259
260 (ly:set-default-scale (ly:make-scale #(0 1 2 5/2 7/2 9/2 11/2)))
261
262
263
264 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
265 ;; other files.
266
267 (for-each ly:load
268           ;; load-from-path
269           '("lily-library.scm"
270             "file-cache.scm"
271             "define-event-classes.scm"
272             "define-music-types.scm"
273             "output-lib.scm"
274             "c++.scm"
275             "chord-ignatzek-names.scm"
276             "chord-entry.scm"
277             "chord-generic-names.scm"
278             "stencil.scm"
279             "markup.scm"
280             "music-functions.scm"
281             "part-combiner.scm"
282             "autochange.scm"
283             "define-music-properties.scm"
284             "auto-beam.scm"
285             "chord-name.scm"
286
287             "parser-ly-from-scheme.scm"
288             "ly-syntax-constructors.scm"
289             
290             "define-context-properties.scm"
291             "translation-functions.scm"
292             "script.scm"
293             "midi.scm"
294             "layout-beam.scm"
295             "parser-clef.scm"
296             "layout-slur.scm"
297             "font.scm"
298             "encoding.scm"
299             
300             "fret-diagrams.scm"
301             "define-markup-commands.scm"
302             "define-grob-properties.scm"
303             "define-grobs.scm"
304             "define-grob-interfaces.scm"
305             "define-stencil-commands.scm"
306             "titling.scm"
307             
308             "paper.scm"
309             "backend-library.scm"
310             "x11-color.scm"
311
312             ;; must be after everything has been defined
313             "safe-lily.scm"))
314
315
316 (set! type-p-name-alist
317       `(
318         (,boolean-or-symbol? . "boolean or symbol")
319         (,boolean? . "boolean")
320         (,char? . "char")
321         (,grob-list? . "list of grobs")
322         (,hash-table? . "hash table")
323         (,input-port? . "input port")
324         (,integer? . "integer")
325         (,list? . "list")
326         (,ly:context? . "context")
327         (,ly:dimension? . "dimension, in staff space")
328         (,ly:dir? . "direction")
329         (,ly:duration? . "duration")
330         (,ly:grob? . "layout object")
331         (,ly:input-location? . "input location")
332         (,ly:moment? . "moment")
333         (,ly:music? . "music")
334         (,ly:pitch? . "pitch")
335         (,ly:translator? . "translator")
336         (,ly:font-metric? . "font metric")
337         (,ly:simple-closure? . "simple closure")
338         (,markup-list? . "list of markups")
339         (,markup? . "markup")
340         (,ly:music-list? . "list of music")
341         (,number-or-grob? . "number or grob")
342         (,number-or-string? . "number or string")
343         (,number-pair? . "pair of numbers")
344         (,number? . "number")
345         (,output-port? . "output port")   
346         (,pair? . "pair")
347         (,procedure? . "procedure")
348         (,rhythmic-location? . "rhythmic location")
349         (,scheme? . "any type")
350         (,string? . "string")
351         (,symbol? . "symbol")
352         (,vector? . "vector")))
353
354 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
355 ;; timing
356
357 (define (profile-measurements)
358   (let* ((t (times))
359          (stats (gc-stats)))
360
361     (list
362      (- (+ (tms:utime t)
363            (tms:stime t))
364         (ly:assoc-get 'gc-time-taken stats))
365
366      ;; difficult to put memory amount stats into here.
367      
368      )))
369
370 (define (dump-profile name last this)
371   (let*
372       ((outname (format "~a.profile" (basename name ".ly")))
373        (diff (map (lambda (y) (apply - y)) (zip this last))))
374     
375     (ly:progress "\nWriting timing to ~a..." outname)
376     (format (open-file outname "w")
377             "time: ~a"
378             (car diff))))
379
380
381 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
382 ;; debug mem leaks
383
384 (define gc-dumping #f)
385 (define gc-protect-stat-count 0)
386 (define-public (dump-gc-protects)
387   (set! gc-protect-stat-count (1+ gc-protect-stat-count))
388   (let* ((protects (sort
389                     (hash-table->alist (ly:protects))
390                     (lambda (a b)
391                       (< (object-address (car a))
392                          (object-address (car b))))))
393
394          (out-file-name (string-append
395                          "gcstat-" (number->string gc-protect-stat-count)
396                          ".scm"))
397          (outfile    (open-file  out-file-name  "w")))
398
399     (set! gc-dumping #t)
400     (display (format "Dumping GC statistics ~a...\n" out-file-name))
401     (display
402      (map (lambda (y)
403             (let ((x (car y))
404                   (c (cdr y)))
405               (display 
406                (format "~a (~a) = ~a\n" (object-address x) c x)
407                outfile)))
408           (filter
409            (lambda (x)
410              (not (symbol? (car x))))
411            protects))
412      outfile)
413
414     (format outfile "\nprotected symbols: ~a\n"
415             (length (filter symbol?  (map car protects))))
416     
417              
418
419     ;; (display (ly:smob-protects))
420     (newline outfile)
421     (if (defined? 'gc-live-object-stats)
422         (let* ((stats #f))
423           (display "Live object statistics: GC'ing\n")
424           (ly:reset-all-fonts)
425           (gc)
426           (gc)
427           (display "Asserting dead objects\n")
428           (ly:set-option 'debug-gc-assert-parsed-dead #t)
429           (gc)
430           (ly:set-option 'debug-gc-assert-parsed-dead #f)
431
432           (set! stats (gc-live-object-stats))
433           (display "Dumping live object statistics.\n")
434           
435           (for-each
436            (lambda (x)
437              (format outfile "~a: ~a\n" (car x) (cdr x)))
438            (sort (gc-live-object-stats)
439                  (lambda (x y)
440                    (string<? (car x) (car y)))))))
441
442
443     (newline outfile)
444     (let*
445         ((stats (gc-stats)))
446       
447       (for-each
448        (lambda (sym)
449          (display
450           (format "~a ~a ~a\n"
451                   gc-protect-stat-count
452                   sym
453                   (let ((sym-stat (assoc sym stats)))
454                     (if sym-stat 
455                         (cdr sym-stat)
456                         "?")))
457           outfile))
458        '(protected-objects bytes-malloced cell-heap-size
459                            
460                            )))
461
462     (set! gc-dumping #f)
463     
464     ))
465
466 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
467
468
469 (define (multi-fork count)
470   (define (helper count acc)
471     (if (> count 0)
472       (let*
473           ((pid  (primitive-fork)))
474         (if (= pid 0)
475             (1- count)
476             (helper (1- count) (cons pid acc))))
477       acc))
478   (helper count '()))
479
480
481 (define-public (lilypond-main files)
482   "Entry point for LilyPond."
483   
484   (define (no-files-handler)
485     (ly:usage)
486     (exit 2))
487
488   (if (ly:get-option 'gui)
489       (gui-main files))
490
491   (if (null? files)
492       (no-files-handler))
493
494   (if (ly:get-option 'read-file-list)
495       (set! files
496             (filter (lambda (s)
497                       (> (string-length s) 0))
498                     (apply append
499                            (map (lambda (f) (string-split (ly:gulp-file f) #\nl))
500                                 files)))
501             ))
502   
503   (if (and (number? (ly:get-option 'job-count))
504            (> (length files) (ly:get-option 'job-count)))
505       
506       (let*
507           ((count (ly:get-option 'job-count))
508            (split-todo (split-list files count)) 
509            (joblist (multi-fork count))
510            (errors '()))
511
512         (if (not (string-or-symbol? (ly:get-option 'log-file)))
513             (ly:set-option 'log-file "lilypond-multi-run"))
514         
515         (if (number? joblist)
516             (begin
517               (ly:set-option 'log-file (format "~a-~a"
518                                                (ly:get-option 'log-file) joblist))
519               (set! files (vector-ref split-todo joblist)))
520
521             (begin
522               (ly:progress "\nForking into jobs:  ~a\n" joblist)
523               (for-each
524                (lambda (pid)
525                  (let* ((stat (cdr (waitpid pid))))
526
527                    (if (not (= stat 0))
528                        (set! errors (cons (list-element-index joblist pid) errors)))))
529                joblist)
530
531               (for-each
532                (lambda (x)
533                  (let* ((logfile  (format "~a-~a.log"
534                                           (ly:get-option 'log-file) x))
535                         (log (ly:gulp-file logfile))
536                         (len (string-length log))
537                         (tail (substring  log (max 0 (- len 1024)))))
538
539                    (display (format "\n\nlogfile ~a:\n\n ~a" logfile tail))))
540
541                errors)
542
543               (if (pair? errors)
544                   (ly:error "Children ~a exited with errors." errors))
545
546             (exit (if (null? errors) 0 1))))))
547               
548            
549   (if (string-or-symbol? (ly:get-option 'log-file))
550       (ly:stderr-redirect (format "~a.log" (ly:get-option 'log-file)) "w"))
551   
552   (let ((failed (lilypond-all files)))
553     (if (pair? failed)
554         (begin
555           (ly:error (_ "failed files: ~S") (string-join failed))
556           (exit 1))
557         (begin
558           ;; HACK: be sure to exit with single newline
559           (ly:message "")
560           (exit 0)))))
561
562 (define-public (lilypond-all files)
563
564
565   (if (ly:get-option 'show-available-fonts)
566       (begin
567         (ly:font-config-display-fonts)
568         (exit 0)
569         ))
570   
571   (let* ((failed '())
572          (start-measurements #f)
573          (handler (lambda (key failed-file)
574                     (set! failed (append (list failed-file) failed)))))
575
576     (for-each
577      (lambda (x)
578
579        (gc)
580        (set! start-measurements (profile-measurements))
581        (lilypond-file handler x)
582        (if (ly:get-option 'dump-profile)
583            (dump-profile x start-measurements (profile-measurements)))
584        
585        
586        (ly:clear-anonymous-modules)
587        (if (ly:get-option 'debug-gc)
588            (dump-gc-protects)
589            (if (= (random 40) 1)
590                (ly:reset-all-fonts))))
591
592      files)
593     failed))
594
595 (define (lilypond-file handler file-name)
596   (catch 'ly-file-failed
597          (lambda () (ly:parse-file file-name))
598          (lambda (x . args) (handler x file-name))))
599
600 (use-modules (scm editor))
601
602 (define-public (gui-main files)
603   (if (null? files)
604       (gui-no-files-handler))
605
606   (if (not (string? (ly:get-option 'log-file)))
607       (let* ((base (basename (car files) ".ly"))
608              (log-name (string-append base ".log")))
609         (if (not (ly:get-option 'gui))
610             (ly:message (_ "Redirecting output to ~a...") log-name))
611         (ly:stderr-redirect log-name "w")
612         (ly:message "# -*-compilation-*-"))
613     
614     (let ((failed (lilypond-all files)))
615       (if (pair? failed)
616           (begin
617             ;; ugh
618             (ly:stderr-redirect "foo" "r")
619             (system (get-editor-command log-name 0 0 0))
620             (ly:error (_ "failed files: ~S") (string-join failed))
621             ;; not reached?
622             (exit 1))
623           (exit 0)))))
624
625 (define (gui-no-files-handler)
626   (let* ((ly (string-append (ly:effective-prefix) "/ly/"))
627          ;; FIXME: soft-code, localize
628          (welcome-ly (string-append ly "Welcome_to_LilyPond.ly"))
629          (cmd (get-editor-command welcome-ly 0 0 0)))
630     (ly:message (_ "Invoking `~a'...") cmd)
631     (system cmd)
632     (exit 1)))