]> git.donarmstrong.com Git - lilypond.git/blob - Documentation/contributor/programming-work.itexi
Doc: CG remove ugly bars at end of lines in doc
[lilypond.git] / Documentation / contributor / programming-work.itexi
1 @c -*- coding: utf-8; mode: texinfo; -*-
2 @node Programming work
3 @chapter Programming work
4
5 @menu
6 * Overview of LilyPond architecture::
7 * LilyPond programming languages::
8 * Programming without compiling::
9 * Finding functions::
10 * Code style::
11 * Debugging LilyPond::
12 * Tracing object relationships::
13 * Adding or modifying features::
14 * Iterator tutorial::
15 * Engraver tutorial::
16 * Callback tutorial::
17 * LilyPond scoping::
18 * LilyPond miscellany::
19 @end menu
20
21 @node Overview of LilyPond architecture
22 @section Overview of LilyPond architecture
23
24 LilyPond processes the input file into graphical and musical output in a
25 number of stages.  This process, along with the types of routines that
26 accomplish the various stages of the process, is described in this section.  A
27 more complete description of the LilyPond architecture and internal program
28 execution is found in Erik Sandberg's
29 @uref{http://lilypond.org/web/images/thesis-erik-sandberg.pdf, master's
30 thesis}.
31
32 The first stage of LilyPond processing is @emph{parsing}.  In the parsing
33 process, music expressions in LilyPond input format are converted to music
34 expressions in Scheme format.  In Scheme format, a music expression is a list
35 in tree form, with nodes that indicate the relationships between various music
36 events.  The LilyPond parser is written in Bison.
37
38 The second stage of LilyPond processing is @emph{iterating}.  Iterating
39 assigns each music event to a context, which is the environment in which the
40 music will be finally engraved.  The context is responsible for all further
41 processing of the music.  It is during the iteration stage that contexts are
42 created as necessary to ensure that every note has a Voice type context (e.g.
43 Voice, TabVoice, DrumVoice, CueVoice, MensuralVoice, VaticanaVoice,
44 GregorianTranscriptionVoice), that the Voice type contexts exist in
45 appropriate Staff type contexts, and that parallel Staff type contexts exist
46 in StaffGroup type contexts.  In addition, during the iteration stage each
47 music event is assigned a moment, or a time in the music when the event
48 begins.
49
50 Each type of music event has an associated iterator.  Iterators are defined in
51 @file{*-iterator.cc}.  During iteration, an
52 event's iterator is called to deliver that music event to the appropriate
53 context(s).
54
55 The final stage of LilyPond processing is @emph{translation}.  During
56 translation, music events are prepared for graphical or midi output.  The
57 translation step is accomplished by the polymorphic base class Translator
58 through its two derived classes: Engraver (for graphical output) and
59 Performer (for midi output).
60
61 Translators are defined in C++ files named @file{*-engraver.cc}
62 and @file{*-performer.cc}.
63 Much of the work of translating is handled by Scheme functions,
64 which is one of the keys to LilyPond's exceptional flexibility.
65
66 @sourceimage{architecture-diagram,,,png}
67
68
69 @node LilyPond programming languages
70 @section LilyPond programming languages
71
72 Programming in LilyPond is done in a variety of programming languages.  Each
73 language is used for a specific purpose or purposes.  This section describes
74 the languages used and provides links to reference manuals and tutorials for
75 the relevant language.
76
77 @subsection C++
78
79 The core functionality of LilyPond is implemented in C++.
80
81 C++ is so ubiquitous that it is difficult to identify either a reference
82 manual or a tutorial.  Programmers unfamiliar with C++ will need to spend some
83 time to learn the language before attempting to modify the C++ code.
84
85 The C++ code calls Scheme/GUILE through the GUILE interface, which is
86 documented in the
87 @uref{http://www.gnu.org/software/guile/manual/html_node/index.html, GUILE
88   Reference Manual}.
89
90 @subsection Flex
91
92 The LilyPond lexer is implemented in Flex, an implementation of the Unix lex
93 lexical analyser generator.  Resources for Flex can be found
94 @uref{http://flex.sourceforge.net/, here}.
95
96 @subsection GNU Bison
97
98 The LilyPond parser is implemented in Bison, a GNU parser generator.  The
99 Bison homepage is found at @uref{http://www.gnu.org/software/bison/,
100 gnu.org}.  The manual (which includes both a reference and tutorial) is
101 @uref{http://www.gnu.org/software/bison/manual/index.html, available} in a
102 variety of formats.
103
104 @subsection GNU Make
105
106 GNU Make is used to control the compiling process and to build the
107 documentation and the website.  GNU Make documentation is available at
108 @uref{http://www.gnu.org/software/make/manual/, the GNU website}.
109
110 @subsection GUILE or Scheme
111
112 GUILE is the dialect of Scheme that is used as LilyPond's extension language.
113 Many extensions to LilyPond are written entirely in GUILE.  The
114 @uref{http://www.gnu.org/software/guile/manual/html_node/index.html,
115 GUILE Reference Manual} is available online.
116
117 @uref{http://mitpress.mit.edu/sicp/full-text/book/book.html, Structure and
118 Interpretation of Computer Programs}, a popular textbook used to teach
119 programming in Scheme is available in its entirety online.
120
121 An introduction to Guile/Scheme as used in LilyPond can be found in the
122 @rextend{Scheme tutorial}.
123
124 @subsection MetaFont
125
126 MetaFont is used to create LilyPond's musical fonts.  An unofficial
127 @uref{http://metafont.tutorial.free.fr/, METAFONT tutorial} is available.  The
128 @uref{http://www.ctex.org/documents/shredder/src/mfbook.pdf, METAFONTbook}
129 by Donald Knuth (TeX and MetaFont creator) is the most complete documentation
130 available for MetaFont.
131
132 @subsection PostScript
133
134 PostScript is used to generate graphical output.  A brief PostScript tutorial
135 is @uref{http://local.wasp.uwa.edu.au/~pbourke/dataformats/postscript/,
136 available online}.  The
137 @uref{http://www.adobe.com/devnet/postscript/pdfs/PLRM.pdf, PostScript Language
138 Reference} is available online in PDF format.
139
140 @subsection Python
141
142 Python is used for XML2ly and is used for building the documentation and the
143 website.
144
145 Python documentation is available at @uref{http://www.python.org/doc/,
146 python.org}.
147
148 @node Programming without compiling
149 @section Programming without compiling
150
151 Much of the development work in LilyPond takes place by changing @file{*.ly} or
152 @file{*.scm} files.  These changes can be made without compiling LilyPond.  Such
153 changes are described in this section.
154
155
156 @subsection Modifying distribution files
157
158 Much of LilyPond is written in Scheme or LilyPond input files.  These
159 files are interpreted when the program is run, rather than being compiled
160 when the program is built, and are present in all LilyPond distributions.
161 You will find @file{.ly} files in the @file{ly/} directory and the Scheme files in the
162 @file{scm/} directory.  Both Scheme files and @file{.ly} files can be modified and
163 saved with any text editor.  It's probably wise to make a backup copy of
164 your files before you modify them, although you can reinstall if the
165 files become corrupted.
166
167 Once you've modified the files, you can test the changes just by running
168 LilyPond on some input file.  It's a good idea to create a file that
169 demonstrates the feature you're trying to add.  This file will eventually
170 become a regression test and will be part of the LilyPond distribution.
171
172 @subsection Desired file formatting
173
174 Files that are part of the LilyPond distribution have Unix-style line
175 endings (LF), rather than DOS (CR+LF) or MacOS 9 and earlier (CR).  Make
176 sure you use the necessary tools to ensure that Unix-style line endings are
177 preserved in the patches you create.
178
179 Tab characters should not be included in files for distribution.  All
180 indentation should be done with spaces.  Most editors have settings to
181 allow the setting of tab stops and ensuring that no tab characters are
182 included in the file.
183
184 Scheme files and LilyPond files should be written according to standard
185 style guidelines.  Scheme file guidelines can be found at
186 @uref{http://community.schemewiki.org/?scheme-style}.  Following these
187 guidelines will make your code easier to read.  Both you and others that
188 work on your code will be glad you followed these guidelines.
189
190 For LilyPond files, you should follow the guidelines for LilyPond snippets
191 in the documentation.  You can find these guidelines at
192 @ref{Texinfo introduction and usage policy}.
193
194 @node Finding functions
195 @section Finding functions
196
197 When making changes or fixing bugs in LilyPond, one of the initial
198 challenges is finding out where in the code tree the functions to
199 be modified live.  With nearly 3000 files in the source tree,
200 trial-and-error searching is generally ineffective.  This section
201 describes a process for finding interesting code.
202
203 @subsection Using the ROADMAP
204
205 The file ROADMAP is located in the main directory of the lilypond source.
206 ROADMAP lists all of the directories in the LilyPond source tree, along
207 with a brief description of the kind of files found in each directory.
208 This can be a very helpful tool for deciding which directories to search
209 when looking for a function.
210
211
212 @subsection Using grep to search
213
214 Having identified a likely subdirectory to search, the grep utility can
215 be used to search for a function name.  The format of the grep command is
216
217 @example
218 grep -i functionName subdirectory/*
219 @end example
220
221 This command will search all the contents of the directory subdirectory/
222 and display every line in any of the files that contains
223 functionName.  The @code{-i} option makes @command{grep} ignore
224 case -- this can be very useful if you are not yet familiar with
225 our capitalization conventions.
226
227 The most likely directories to grep for function names are @file{scm/} for
228 scheme files, ly/ for lilypond input (@file{*.ly}) files, and @file{lily/} for C++
229 files.
230
231
232 @subsection Using git grep to search
233
234 If you have used git to obtain the source, you have access to a
235 powerful tool to search for functions.  The command:
236
237 @example
238 git grep functionName
239 @end example
240
241 will search through all of the files that are present in the git
242 repository looking for functionName.  It also presents the results
243 of the search using @code{less}, so the results are displayed one page
244 at a time.
245
246 @subsection Searching on the git repository at Savannah
247
248 You can also use the equivalent of git grep on the Savannah server.
249
250 @itemize
251
252 @item
253 Go to http://git.sv.gnu.org/gitweb/?p=lilypond.git
254
255 @item
256 In the pulldown box that says commit, select grep.
257
258 @item
259 Type functionName in the search box, and hit enter/return
260
261 @end itemize
262
263 This will initiate a search of the remote git repository.
264
265
266 @node Code style
267 @section Code style
268
269 This section describes style guidelines for LilyPond
270 source code.
271
272 @menu
273 * Languages::
274 * Filenames::
275 * Indentation::
276 * Naming conventions::
277 * Broken code::
278 * Code comments::
279 * Handling errors::
280 * Localization::
281 @end menu
282
283
284 @node Languages
285 @subsection Languages
286
287 C++ and Python are preferred.  Python code should use PEP 8.
288
289
290 @node Filenames
291 @subsection Filenames
292
293 Definitions of classes that are only accessed via pointers (*) or
294 references (&) shall not be included as include files.
295
296 @verbatim
297    filenames
298
299         ".hh"   Include files
300              ".cc"      Implementation files
301              ".icc"     Inline definition files
302              ".tcc"     non inline Template defs
303
304    in emacs:
305
306              (setq auto-mode-alist
307                    (append '(("\\.make$" . makefile-mode)
308                         ("\\.cc$" . c++-mode)
309                         ("\\.icc$" . c++-mode)
310                         ("\\.tcc$" . c++-mode)
311                         ("\\.hh$" . c++-mode)
312                         ("\\.pod$" . text-mode)
313                         )
314                       auto-mode-alist))
315 @end verbatim
316
317 The class Class_name is coded in @q{class-name.*}
318
319
320 @node Indentation
321 @subsection Indentation
322
323 Standard GNU coding style is used.  In emacs:
324
325 @verbatim
326              (add-hook 'c++-mode-hook
327                   '(lambda() (c-set-style "gnu")
328                      ))
329 @end verbatim
330
331 If you like using font-lock, you can also add this to your
332 @q{.emacs}:
333
334 @verbatim
335              (setq font-lock-maximum-decoration t)
336              (setq c++-font-lock-keywords-3
337                    (append
338                     c++-font-lock-keywords-3
339                     '(("\\b\\(a-zA-Z_?+_\\)\\b" 1 font-lock-variable-name-face) ("\\b\\(A-Z?+a-z_?+\\)\\b" 1 font-lock-type-face))
340                     ))
341 @end verbatim
342
343 Some source files may not currently have proper indenting.  If this
344 is the case, it is desirable to fix the improper indenting when the
345 file is modified, with the hope of continually improving the code.
346
347
348 @subheading Indenting files with fixcc.py
349
350 LilyPond provides a python script that will correct the indentation
351 on a c++ file:
352
353 @example
354 scripts/auxiliar/fixcc.py lily/my-test-file.cc
355 @end example
356
357 Be sure you replace @file{my-test-file.cc} with the name of the file
358 that you edited.
359
360 If you are editing a file that contains an ADD_TRANSLATOR or ADD_INTERFACE
361 macro, the fixcc.py script will move the final parenthesis up one line
362 from where it should be.  Please check the end of the file before
363 you run fixcc.py, and then put the final parenthesis and semicolon
364 back on a line by themselves.
365
366
367 @subheading Indenting files with emacs in script mode
368
369 @c email to wl@gnu.org when I get here.
370
371 @warning{this is pending some confirmation on -devel.  July 2009 -gp}
372
373 Command-line script to format stuff with emacs:
374
375 @smallexample
376 #!/bin/sh
377 emacs $1 -batch --eval '(indent-region (point-min) (point-max) nil)' -f save-buffer
378 @end smallexample
379
380 (that's all on one line)
381
382 Save it as a shell script, then run on the file(s) you modified.
383
384 @subheading Indenting with vim
385
386 Although emacs indentation is the LilyPond standard, acceptable
387 indentation can usually be accomplished with vim.  Some hints for
388 vim are as follows:
389
390 A workable .vimrc:
391
392 @verbatim
393 set cindent
394 set smartindent
395 set autoindent
396 set expandtab
397 set softtabstop=2
398 set shiftwidth=2
399 filetype plugin indent on
400 set incsearch
401 set ignorecase smartcase
402 set hlsearch
403 set confirm
404 set statusline=%F%m%r%h%w\ %{&ff}\ %Y\ [ASCII=\%03.3b]\ [HEX=\%02.2B]\ %04l,%04v\ %p%%\ [LEN=%L]
405 set laststatus=2
406 set number
407 " Remove trailing whitespace on write
408 autocmd BufWritePre * :%s/\s\+$//e
409 @end verbatim
410
411 With this .vimrc, files can be reindented automatically by highlighting
412 the lines to be indented in visual mode (use V to enter visual mode)
413 and pressing =.
414
415 A scheme.vim file will help improve the indentation.  This one
416 was suggested by Patrick McCarty.  It should be saved in
417 ~/.vim/after/syntax/scheme.vim.
418
419 @verbatim
420 " Additional Guile-specific 'forms'
421 syn keyword schemeSyntax define-public define*-public
422 syn keyword schemeSyntax define* lambda* let-keywords*
423 syn keyword schemeSyntax defmacro defmacro* define-macro
424 syn keyword schemeSyntax defmacro-public defmacro*-public
425 syn keyword schemeSyntax use-modules define-module
426 syn keyword schemeSyntax define-method define-class
427
428 " Additional LilyPond-specific 'forms'
429 syn keyword schemeSyntax define-markup-command define-markup-list-command
430 syn keyword schemeSyntax define-safe-public define-music-function
431 syn keyword schemeSyntax def-grace-function
432
433 " All of the above should influence indenting too
434 set lw+=define-public,define*-public
435 set lw+=define*,lambda*,let-keywords*
436 set lw+=defmacro,defmacro*,define-macro
437 set lw+=defmacro-public,defmacro*-public
438 set lw+=use-modules,define-module
439 set lw+=define-method,define-class
440 set lw+=define-markup-command,define-markup-list-command
441 set lw+=define-safe-public,define-music-function
442 set lw+=def-grace-function
443
444 " These forms should not influence indenting
445 set lw-=if
446 set lw-=set!
447
448 " Try to highlight all ly: procedures
449 syn match schemeFunc "ly:[^) ]\+"
450 @end verbatim
451
452
453 @node Naming conventions
454 @subsection Naming Conventions
455
456 Naming conventions have been established for LilyPond
457 source code.
458
459 @subheading Classes and Types
460
461 Classes begin with an uppercase letter, and words
462 in class names are separated with @code{_}:
463
464 @verbatim
465 This_is_a_class
466 @end verbatim
467
468 @subheading Members
469
470 Member variable names end with an underscore:
471
472 @verbatim
473 Type Class::member_
474 @end verbatim
475
476 @subheading Macros
477
478 Macro names should be written in uppercase completely,
479 with words separated by @code{_}:
480
481 @verbatim
482 THIS_IS_A_MACRO
483 @end verbatim
484
485 @subheading Variables
486
487 Variable names should be complete words, rather than abbreviations.
488 For example, it is preferred to use @code{thickness} rather than
489 @code{th} or @code{t}.
490
491 Multi-word variable names in C++ should have the words separated
492 by the underscore character (@q{_}):
493
494 @verbatim
495 cxx_multiword_variable
496 @end verbatim
497
498 Multi-word variable names in Scheme should have the words separated
499 by a hyphen (@q{-}):
500
501 @verbatim
502 scheme-multiword-variable
503 @end verbatim
504
505 @node Broken code
506 @subsection Broken code
507
508 Do not write broken code.  This includes hardwired dependencies,
509 hardwired constants, slow algorithms and obvious limitations.  If
510 you can not avoid it, mark the place clearly, and add a comment
511 explaining shortcomings of the code.
512
513 Ideally, the comment marking the shortcoming would include
514 TODO, so that it is marked for future fixing.
515
516 We reject broken-in-advance on principle.
517
518
519 @node Code comments
520 @subsection Code comments
521
522 Comments may not be needed if descriptive variable names are used
523 in the code and the logic is straightforward.  However, if the
524 logic is difficult to follow, and particularly if non-obvious
525 code has been included to resolve a bug, a comment describing
526 the logic and/or the need for the non-obvious code should be included.
527
528 There are instances where the current code could be commented better.
529 If significant time is required to understand the code as part of
530 preparing a patch, it would be wise to add comments reflecting your
531 understanding to make future work easier.
532
533
534 @node Handling errors
535 @subsection Handling errors
536
537 As a general rule, you should always try to continue computations,
538 even if there is some kind of error.  When the program stops, it
539 is often very hard for a user to pinpoint what part of the input
540 causes an error.  Finding the culprit is much easier if there is
541 some viewable output.
542
543 So functions and methods do not return errorcodes, they never
544 crash, but report a programming_error and try to carry on.
545
546 Error and warning messages need to be localized.
547
548
549 @node Localization
550 @subsection Localization
551
552 This document provides some guidelines to help programmers write
553 proper user
554 messages.  To help translations, user messages must follow
555 uniform conventions.  Follow these rules when coding for LilyPond.
556 Hopefully, this can be replaced by general GNU guidelines in the
557 future.  Even better would be to have an English (en_BR, en_AM)
558 guide helping programmers writing consistent messages for all GNU
559 programs.
560
561 Non-preferred messages are marked with `+'.  By convention,
562 ungrammatical examples are marked with `*'.  However, such ungrammatical
563 examples may still be preferred.
564
565 @itemize
566
567 @item
568 Every message to the user should be localized (and thus be marked
569 for localization).  This includes warning and error messages.
570
571 @item
572 Do not localize/gettextify:
573
574 @itemize
575 @item
576 `programming_error ()'s
577
578 @item
579 `programming_warning ()'s
580
581 @item
582 debug strings
583
584 @item
585 output strings (PostScript, TeX, etc.)
586
587 @end itemize
588
589 @item
590 Messages to be localized must be encapsulated in `_ (STRING)' or
591 `_f (FORMAT, ...)'. E.g.:
592
593 @example
594 warning (_ ("need music in a score"));
595 error (_f ("cannot open file: `%s'", file_name));
596 @end example
597
598 In some rare cases you may need to call `gettext ()' by hand.  This
599 happens when you pre-define (a list of) string constants for later
600 use.  In that case, you'll probably also need to mark these string
601 constants for translation, using `_i (STRING)'.  The `_i' macro is
602 a no-op, it only serves as a marker for `xgettext'.
603
604 @example
605 char const* messages[] = @{
606   _i ("enable debugging output"),
607   _i ("ignore lilypond version"),
608   0
609 @};
610
611 void
612 foo (int i)
613 @{
614   puts (gettext (messages i));
615 @}
616 @end example
617
618 See also @file{flower/getopt-long.cc} and @file{lily/main.cc}.
619
620 @item
621 Do not use leading or trailing whitespace in messages.  If you need
622 whitespace to be printed, prepend or append it to the translated
623 message
624
625 @example
626 message ("Calculating line breaks..." + " ");
627 @end example
628
629 @item
630 Error or warning messages displayed with a file name and line
631 number never start with a capital, eg,
632
633 @example
634 foo.ly: 12: not a duration: 3
635 @end example
636
637 Messages containing a final verb, or a gerund (`-ing'-form) always
638 start with a capital.  Other (simpler) messages start with a
639 lowercase letter
640
641 @example
642 Processing foo.ly...
643 `foo': not declared.
644 Not declaring: `foo'.
645 @end example
646
647 @item
648 Avoid abbreviations or short forms, use `cannot' and `do not'
649 rather than `can't' or `don't'
650 To avoid having a number of different messages for the same
651 situation, well will use quoting like this `"message: `%s'"' for all
652 strings.  Numbers are not quoted:
653
654 @example
655 _f ("cannot open file: `%s'", name_str)
656 _f ("cannot find character number: %d", i)
657 @end example
658
659 @item
660 Think about translation issues.  In a lot of cases, it is better to
661 translate a whole message.  English grammar must not be imposed on the
662 translator.  So, instead of
663
664 @example
665 stem at  + moment.str () +  does not fit in beam
666 @end example
667
668 have
669
670 @example
671 _f ("stem at %s does not fit in beam", moment.str ())
672 @end example
673
674 @item
675 Split up multi-sentence messages, whenever possible.  Instead of
676
677 @example
678 warning (_f ("out of tune!  Can't find: `%s'", "Key_engraver"));
679 warning (_f ("cannot find font `%s', loading default", font_name));
680 @end example
681
682 rather say:
683
684 @example
685 warning (_ ("out of tune:"));
686 warning (_f ("cannot find: `%s', "Key_engraver"));
687 warning (_f ("cannot find font: `%s', font_name));
688 warning (_f ("Loading default font"));
689 @end example
690
691 @item
692 If you must have multiple-sentence messages, use full punctuation.
693 Use two spaces after end of sentence punctuation.  No punctuation
694 (esp. period) is used at the end of simple messages.
695
696 @example
697 _f ("Non-matching braces in text `%s', adding braces", text)
698 _ ("Debug output disabled.  Compiled with NPRINT.")
699 _f ("Huh?  Not a Request: `%s'.  Ignoring.", request)
700 @end example
701
702 @item
703 Do not modularize too much; words frequently cannot be translated
704 without context.  It is probably safe to treat most occurrences of
705 words like stem, beam, crescendo as separately translatable words.
706
707 @item
708 When translating, it is preferable to put interesting information
709 at the end of the message, rather than embedded in the middle.
710 This especially applies to frequently used messages, even if this
711 would mean sacrificing a bit of eloquency.  This holds for original
712 messages too, of course.
713
714 @example
715 en: cannot open: `foo.ly'
716 +   nl: kan `foo.ly' niet openen (1)
717 kan niet openen: `foo.ly'*   (2)
718 niet te openen: `foo.ly'*    (3)
719 @end example
720
721
722 The first nl message, although grammatically and stylistically
723 correct, is not friendly for parsing by humans (even if they speak
724 dutch).  I guess we would prefer something like (2) or (3).
725
726 @item
727 Do not run make po/po-update with GNU gettext < 0.10.35
728
729 @end itemize
730
731
732
733 @node Debugging LilyPond
734 @section Debugging LilyPond
735
736 The most commonly used tool for debugging LilyPond is the GNU
737 debugger gdb.  The gdb tool is used for investigating and debugging
738 core Lilypond code written in C++.  Another tool is available for
739 debugging Scheme code using the Guile debugger.  This section
740 describes how to use both gdb and the Guile Debugger.
741
742 @menu
743 * Debugging overview::
744 * Debugging C++ code::
745 * Debugging Scheme code::
746 @end menu
747
748 @node Debugging overview
749 @subsection Debugging overview
750
751 Using a debugger simplifies troubleshooting in at least two ways.
752
753 First, breakpoints can be set to pause execution at any desired point.
754 Then, when execution has paused, debugger commands can be issued to
755 explore the values of various variables or to execute functions.
756
757 Second, the debugger can display a stack trace, which shows the
758 sequence in which functions have been called and the arguments
759 passed to the called functions.
760
761 @node Debugging C++ code
762 @subsection Debugging C++ code
763
764 The GNU debugger, gdb, is the principal tool for debugging C++ code.
765
766 @subheading Compiling LilyPond for use with gdb
767
768 In order to use gdb with LilyPond, it is necessary to compile
769 LilyPond with debugging information.  This is accomplished by running
770 the following commands in the main LilyPond source directory.
771
772 @example
773 ./configure  --disable-optimising
774 make
775 @end example
776
777 This will create a version of LilyPond containing debugging
778 information that will allow the debugger to tie the source code
779 to the compiled code.
780
781 You should not do @var{make install} if you want to use a debugger
782 with LilyPond.  The @var{make install} command will strip debugging
783 information from the LilyPond binary.
784
785 @subheading Typical gdb usage
786
787 Once you have compiled the Lilypond image with the necessary
788 debugging information it will have been written to a location in a
789 subfolder of your current working directory:
790
791 @example
792 out/bin/lilypond
793 @end example
794
795 This is important as you will need to let gdb know where to find the
796 image containing the symbol tables.  You can invoke gdb from the
797 command line using the following:
798
799 @example
800 gdb out/bin/lilypond
801 @end example
802 @noindent
803 This loads the LilyPond symbol tables into gdb.  Then, to run
804 LilyPond on @file{test.ly} under the debugger, enter the following:
805
806 @example
807 run test.ly
808 @end example
809
810 @noindent
811 at the gdb prompt.
812
813 As an alternative to running gdb at the command line you may try
814 a graphical interface to gdb such as ddd:
815
816 @example
817 ddd out/bin/lilypond
818 @end example
819
820 You can also use sets of standard gdb commands stored in a .gdbinit
821 file (see next section).
822
823 @subheading Typical .gdbinit files
824
825 The behavior of gdb can be readily customized through the use of a
826 @var{.gdbinit} file.  A @var{.gdbinit} file is a file named
827 @var{.gdbinit} (notice the @qq{.} at the beginning of the file name)
828 that is placed in a user's home directory.
829
830 The @var{.gdbinit} file below is from Han-Wen.  It sets breakpoints
831 for all errors and defines functions for displaying scheme objects
832 (ps), grobs (pgrob), and parsed music expressions (pmusic).
833
834 @example
835 file lily/out/lilypond
836 b programming_error
837 b Grob::programming_error
838
839 define ps
840    print ly_display_scm($arg0)
841 end
842 define pgrob
843   print ly_display_scm($arg0->self_scm_)
844   print ly_display_scm($arg0->mutable_property_alist_)
845   print ly_display_scm($arg0->immutable_property_alist_)
846   print ly_display_scm($arg0->object_alist_)
847 end
848 define pmusic
849   print ly_display_scm($arg0->self_scm_)
850   print ly_display_scm($arg0->mutable_property_alist_)
851   print ly_display_scm($arg0->immutable_property_alist_)
852 end
853 @end example
854
855 @node Debugging Scheme code
856 @subsection Debugging Scheme code
857
858 Scheme code can be developed using the Guile command line
859 interpreter @code{top-repl}.  You can either investigate
860 interactively using just Guile or you can use the debugging
861 tools available within Guile.
862
863 @subheading Using Guile interactively with LilyPond
864
865 In order to experiment with Scheme programming in the LilyPond
866 environment, it is necessary to have a Guile interpreter that
867 has all the LilyPond modules loaded.  This requires the following
868 steps.
869
870 First, define a Scheme symbol for the active module in the @file{.ly} file:
871
872 @example
873 #(module-define! (resolve-module '(guile-user))
874                  'lilypond-module (current-module))
875 @end example
876
877 Now place a Scheme function in the @file{.ly} file that gives an
878 interactive Guile prompt:
879
880 @example
881 #(top-repl)
882 @end example
883
884 When the @file{.ly} file is compiled, this causes the compilation to be
885 interrupted and an interactive guile prompt to appear.  Once the
886 guile prompt appears, the LilyPond active module must be set as the
887 current guile module:
888
889 @example
890 guile> (set-current-module lilypond-module)
891 @end example
892
893 You can demonstrate these commands are operating properly by typing the name
894 of a LilyPond public scheme function to check it has been defined:
895
896 @example
897 guile> fret-diagram-verbose-markup
898 #<procedure fret-diagram-verbose-markup (layout props marking-list)>
899 @end example
900
901 If the LilyPond module has not been correctly loaded, an error
902 message will be generated:
903
904 @example
905 guile> fret-diagram-verbose-markup
906 ERROR: Unbound variable: fret-diagram-verbose-markup
907 ABORT: (unbound-variable)
908 @end example
909
910 Once the module is properly loaded, any valid LilyPond Scheme
911 expression can be entered at the interactive prompt.
912
913 After the investigation is complete, the interactive guile
914 interpreter can be exited:
915
916 @example
917 guile> (quit)
918 @end example
919
920 The compilation of the @file{.ly} file will then continue.
921
922 @subheading Using the Guile debugger
923
924 To set breakpoints and/or enable tracing in Scheme functions, put
925
926 @example
927 \include "guile-debugger.ly"
928 @end example
929
930 in your input file after any scheme procedures you have defined in
931 that file.  This will invoke the Guile command-line after having set
932 up the environment for the debug command-line.  When your input file
933 is processed, a guile prompt will be displayed.  You may now enter
934 commands to set up breakpoints and enable tracing by the Guile debugger.
935
936 @subheading Using breakpoints
937
938 At the guile prompt, you can set breakpoints with
939 the @code{set-break!} procedure:
940
941 @example
942 guile> (set-break! my-scheme-procedure)
943 @end example
944
945 Once you have set the desired breakpoints, you exit the guile repl frame
946 by typing:
947
948 @example
949 guile> (quit)
950 @end example
951
952 Then, when one of the scheme routines for which you have set
953 breakpoints is entered, guile will interrupt execution in a debug
954 frame.  At this point you will have access to Guile debugging
955 commands.  For a listing of these commands, type:
956
957 @example
958 debug> help
959 @end example
960
961 Alternatively you may code the breakpoints in your Lilypond source
962 file using a command such as:
963
964 @example
965 #(set-break! my-scheme-procedure)
966 @end example
967
968 immediately after the @code{\include} statement.  In this case the
969 breakpoint will be set straight after you enter the @code{(quit)}
970 command at the guile prompt.
971
972 Embedding breakpoint commands like this is particularly useful if
973 you want to look at how the Scheme procedures in the @file{.scm}
974 files supplied with LilyPond work.  To do this, edit the file in
975 the relevant directory to add this line near the top:
976
977 @example
978 (use-modules (scm guile-debugger))
979 @end example
980
981 Now you can set a breakpoint after the procedure you are interested
982 in has been declared.  For example, if you are working on routines
983 called by @var{print-book-with} in @file{lily-library.scm}:
984
985 @example
986 (define (print-book-with parser book process-procedure)
987   (let* ((paper (ly:parser-lookup parser '$defaultpaper))
988          (layout (ly:parser-lookup parser '$defaultlayout))
989          (outfile-name (get-outfile-name parser)))
990     (process-procedure book paper layout outfile-name)))
991
992 (define-public (print-book-with-defaults parser book)
993   (print-book-with parser book ly:book-process))
994
995 (define-public (print-book-with-defaults-as-systems parser book)
996   (print-book-with parser book ly:book-process-to-systems))
997
998 @end example
999
1000 At this point in the code you could add this to set a breakpoint at
1001 print-book-with:
1002
1003 @example
1004 (set-break! print-book-with)
1005 @end example
1006
1007 @subheading Tracing procedure calls and evaluator steps
1008
1009 Two forms of trace are available:
1010
1011 @example
1012 (set-trace-call! my-scheme-procedure)
1013 @end example
1014
1015 and
1016
1017 @example
1018 (set-trace-subtree! my-scheme-procedure)
1019 @end example
1020
1021 @code{set-trace-call!} causes Scheme to log a line to the standard
1022 output to show when the procedure is called and when it exits.
1023
1024 @code{set-trace-subtree!} traces every step the Scheme evaluator
1025 performs in evaluating the procedure.
1026
1027 @node Tracing object relationships
1028 @section Tracing object relationships
1029
1030 Understanding the LilyPond source often boils down to figuring out what
1031 is happening to the Grobs.  Where (and why) are they being created,
1032 modified and destroyed? Tracing Lily through a debugger in order to
1033 identify these relationships can be time-consuming and tedious.
1034
1035 In order to simplify this process, a facility has been added to
1036 display the grobs that are created and the properties that are set
1037 and modified.  Although it can be complex to get set up, once set up
1038 it easily provides detailed information about the life of grobs
1039 in the form of a network graph.
1040
1041 Each of the steps necessary to use the graphviz utility
1042 is described below.
1043
1044 @enumerate
1045
1046 @item Installing graphviz
1047
1048 In order to create the graph of the object relationships, it is
1049 first necessary to install Graphviz.  graphviz is available for a
1050 number of different platforms:
1051
1052 @example
1053 @uref{http://www.graphviz.org/Download..php}
1054 @end example
1055
1056 @item Modifying config.make
1057
1058 In order for the Graphviz tool to work, config.make must be modified.
1059 It is probably a good idea to first save a copy of config.make under
1060 a different name.  Then, edit config.make by removing every occurrence
1061 of @code{-DNDEBUG}.
1062
1063 @item Rebuilding LilyPond
1064
1065 The executable code of LilyPond must be rebuilt from scratch:
1066
1067 @example
1068 make -C lily clean && make -C lily
1069 @end example
1070
1071 @item Create a graphviz-compatible @file{.ly} file
1072
1073 In order to use the graphviz utility, the @file{.ly} file must include
1074 @file{ly/graphviz-init.ly}, and should then specify the
1075 grobs and symbols that should be tracked.  An example of this
1076 is found in @file{input/regression/graphviz.ly}.
1077
1078 @item Run lilypond with output sent to a log file
1079
1080 The Graphviz data is sent to stderr by lilypond, so it is
1081 necessary to redirect stderr to a logfile:
1082
1083 @example
1084 lilypond graphviz.ly 2> graphviz.log
1085 @end example
1086
1087 @item Edit the logfile
1088
1089 The logfile has standard lilypond output, as well as the Graphviz
1090 output data.  Delete everything from the beginning of the file
1091 up to but not including the first occurrence of @code{digraph}.
1092
1093 Also, delete the final liypond message about successs from the end
1094 of the file.
1095
1096 @item Process the logfile with @code{dot}
1097
1098 The directed graph is created from the log file with the program
1099 @code{dot}:
1100
1101 @example
1102 dot -Tpdf graphviz.log > graphviz.pdf
1103 @end example
1104
1105 @end enumerate
1106
1107 The pdf file can then be viewed with any pdf viewer.
1108
1109 When compiled without @code{-DNDEBUG}, lilypond may run slower
1110 than normal.  The original configuration can be restored by either
1111 renaming the saved copy of @code{config.make} or rerunning
1112 @code{configure}.  Then rebuild lilypond with
1113
1114 @example
1115 make -C lily clean && make -C lily
1116 @end example
1117
1118
1119 @node Adding or modifying features
1120 @section Adding or modifying features
1121
1122 When a new feature is to be added to LilyPond, it is necessary to
1123 ensure that the feature is properly integrated to maintain
1124 its long-term support.  This section describes the steps necessary
1125 for feature addition and modification.
1126
1127
1128 @menu
1129 * Write the code::
1130 * Write regression tests::
1131 * Write convert-ly rule::
1132 * Automatically update documentation::
1133 * Manually update documentation::
1134 * Edit changes.tely::
1135 * Verify successful build::
1136 * Verify regression tests::
1137 * Post patch for comments::
1138 * Push patch::
1139 * Closing the issues::
1140 @end menu
1141
1142 @node Write the code
1143 @subsection Write the code
1144
1145 You should probably create a new git branch for writing the code, as that
1146 will separate it from the master branch and allow you to continue
1147 to work on small projects related to master.
1148
1149 Please be sure to follow the rules for programming style discussed
1150 earlier in this chapter.
1151
1152
1153 @node Write regression tests
1154 @subsection Write regression tests
1155
1156 In order to demonstrate that the code works properly, you will
1157 need to write one or more regression tests.  These tests are
1158 typically @file{.ly} files that are found in @file{input/regression}.
1159
1160 Regression tests should be as brief as possible to demonstrate the
1161 functionality of the code.
1162
1163 Regression tests should generally cover one issue per test.  Several
1164 short, single-issue regression tests are preferred to a single, long,
1165 multiple-issue regression test.
1166
1167 Use existing regression tests as templates to demonstrate the type of
1168 header information that should be included in a regression test.
1169
1170
1171 @node Write convert-ly rule
1172 @subsection Write convert-ly rule
1173
1174 If the modification changes the input syntax, a convert-ly rule
1175 should be written to automatically update input files from older
1176 versions.
1177
1178 convert-ly rules are found in python/convertrules.py
1179
1180 If possible, the convert-ly rule should allow automatic updating
1181 of the file.  In some cases, this will not be possible, so the
1182 rule will simply point out to the user that the feature needs
1183 manual correction.
1184
1185 @subsubheading Updating version numbers
1186
1187 If a development release occurs between you writing your patch and
1188 having it approved+pushed, you will need to update the version
1189 numbers in your tree.  This can be done with:
1190
1191 @example
1192 scripts/auxiliar/update-patch-version old.version.number new.version.number
1193 @end example
1194
1195 It will change all files in git, so use with caution and examine
1196 the resulting diff.
1197
1198
1199 @node Automatically update documentation
1200 @subsection Automatically update documentation
1201
1202 @command{convert-ly} should be used to update the documentation,
1203 the snippets, and the regression tests.  This not only makes the
1204 necessary syntax changes, it also tests the @command{convert-ly}
1205 rules.
1206
1207 The automatic updating is performed by moving to the top-level
1208 source directory, then running:
1209
1210 @example
1211 scripts/auxiliar/update-with-convert-ly.sh
1212 @end example
1213
1214 If you did an out-of-tree build, pass in the relative path:
1215
1216 @example
1217 BUILD_DIR=../build-lilypond/ scripts/auxiliar/update-with-convert-ly.sh
1218 @end example
1219
1220
1221 @node Manually update documentation
1222 @subsection Manually update documentation
1223
1224 Where the convert-ly rule is not able to automatically update the inline
1225 lilypond code in the documentation (i.e. if a NOT_SMART rule is used), the
1226 documentation must be manually updated.  The inline snippets that require
1227 changing must be changed in the English version of the docs and all
1228 translated versions.  If the inline code is not changed in the
1229 translated documentation, the old snippets will show up in the
1230 English version of the documentation.
1231
1232 Where the convert-ly rule is not able to automatically update snippets
1233 in Documentation/snippets/, those snippets must be manually updated.
1234 Those snippets should be copied to Documentation/snippets/new.  The
1235 comments at the top of the snippet describing its automatic generation
1236 should be removed.  All translated texidoc strings should be removed.
1237 The comment @qq{% begin verbatim} should be removed.  The syntax of
1238 the snippet should then be manually edited.
1239
1240 Where snippets in Documentation/snippets are made obsolete, the snippet
1241 should be copied to Documentation/snippets/new.  The comments and
1242 texidoc strings should be removed as described above.  Then the body
1243 of the snippet should be changed to:
1244
1245 @example
1246 \markup @{
1247   This snippet is deprecated as of version X.Y.Z and
1248   will be removed from the documentation.
1249 @}
1250 @end example
1251
1252 @noindent
1253 where X.Y.Z is the version number for which the convert-ly rule was
1254 written.
1255
1256 Update the snippet files by running:
1257
1258 @example
1259 scripts/auxiliar/makelsr.py
1260 @end example
1261
1262 Where the convert-ly rule is not able to automatically update regression
1263 tests, the regression tests in input/regression should be manually
1264 edited.
1265
1266 Although it is not required, it is helpful if the developer
1267 can write relevant material for inclusion in the Notation
1268 Reference.  If the developer does not feel qualified to write
1269 the documentation, a documentation editor will be able to
1270 write it from the regression tests.  The text that is added to
1271 or removed from the documentation should be changed only in
1272 the English version.
1273
1274
1275 @node Edit changes.tely
1276 @subsection Edit changes.tely
1277
1278 An entry should be added to Documentation/changes.tely to describe
1279 the feature changes to be implemented.  This is especially important
1280 for changes that change input file syntax.
1281
1282 Hints for changes.tely entries are given at the top of the file.
1283
1284 New entries in changes.tely go at the top of the file.
1285
1286 The changes.tely entry should be written to show how the new change
1287 improves LilyPond, if possible.
1288
1289
1290 @node Verify successful build
1291 @subsection Verify successful build
1292
1293 When the changes have been made, successful completion must be
1294 verified by doing
1295
1296 @example
1297 make all
1298 make doc
1299 @end example
1300
1301 When these commands complete without error, the patch is
1302 considered to function successfully.
1303
1304 Developers on Windows who are unable to build LilyPond should
1305 get help from a Linux or OSX developer to do the make tests.
1306
1307
1308 @node Verify regression tests
1309 @subsection Verify regression tests
1310
1311 In order to avoid breaking LilyPond, it is important to verify that
1312 the regression tests succeed, and that no unwanted changes are
1313 introduced into the output.  This process is described in
1314 @ref{Regtest comparison}.
1315
1316 @subheading Typical developer's edit/compile/test cycle
1317
1318 TODO: is @code{[-j@var{X} CPU_COUNT=@var{X}]} useful for
1319 @code{test-baseline}, @code{check}, @code{clean},
1320 @code{test-redo}?  Neil Puttock says it is useful for
1321 everything but @code{clean}, which is disk-limited.
1322 Need to check formally.
1323
1324 @itemize
1325 @item
1326 Initial test:
1327
1328 @example
1329 make [-j@var{X}]
1330 make test-baseline
1331 make [-j@var{X} CPU_COUNT=@var{X}] check
1332 @end example
1333
1334 @item
1335 Edit/compile/test cycle:
1336
1337 @example
1338 @emph{## edit source files, then...}
1339
1340 make clean                    @emph{## only if needed (see below)}
1341 make [-j@var{X}]                    @emph{## only if needed (see below)}
1342 make test-redo                @emph{## redo files differing from baseline}
1343 make [-j@var{X} CPU_COUNT=@var{X}] check  @emph{## CPU_COUNT here?}
1344 @end example
1345
1346 @item
1347 Reset:
1348
1349 @example
1350 make test-clean
1351 @end example
1352 @end itemize
1353
1354 If you modify any source files that have to be compiled (such as
1355 @file{.cc} or @file{.hh} files in @file{flower/} or @file{lily/}),
1356 then you must run @command{make} before @command{make test-redo},
1357 so @command{make} can compile the modified files and relink all
1358 the object files.  If you only modify files which are interpreted,
1359 like those in the @file{scm/} and @file{ly/} directories, then
1360 @command{make} is not needed before @command{make test-redo}.
1361
1362 TODO:  Fix the following paragraph.  You can do @command{rm mf/out/*}
1363 instead of make clean, and you can probably do
1364 @command{make -C  mf/ clean} as well, but I haven't checked it -- cds
1365
1366 Also, if you modify any font definitions in the @file{mf/}
1367 directory then you must run @command{make clean} and
1368 @command{make} before running @command{make test-redo}.  This will
1369 recompile everything, whether modified or not, and takes a lot
1370 longer.
1371
1372 Running @command{make@tie{}check} will leave an HTML page
1373 @file{out/test-results/index.html}.  This page shows all the
1374 important differences that your change introduced, whether in the
1375 layout, MIDI, performance or error reporting.
1376
1377
1378
1379
1380 @node Post patch for comments
1381 @subsection Post patch for comments
1382
1383 See @ref{Uploading a patch for review}.
1384
1385
1386 @node Push patch
1387 @subsection Push patch
1388
1389 Once all the comments have been addressed, the patch can be pushed.
1390
1391 If the author has push privileges, the author will push the patch.
1392 Otherwise, a developer with push privileges will push the patch.
1393
1394
1395 @node Closing the issues
1396 @subsection Closing the issues
1397
1398 Once the patch has been pushed, all the relevant issues should be
1399 closed.
1400
1401 On Rietveld, the author should log in an close the issue either by
1402 using the @q{Edit Issue} link, or by clicking the circled x icon
1403 to the left of the issue name.
1404
1405 If the changes were in response to a feature request on the Google
1406 issue tracker for LilyPond, the author should change the status to
1407 Fixed and a tag @q{fixed_x_y_z} should be added, where the patch was
1408 fixed in version x.y.z.  If
1409 the author does not have privileges to change the status, an email
1410 should be sent to bug-lilypond requesting the BugMeister to change
1411 the status.
1412
1413
1414 @node Iterator tutorial
1415 @section Iterator tutorial
1416
1417 TODO -- this is a placeholder for a tutorial on iterators
1418
1419 Iterators are routines written in C++ that process music expressions
1420 and sent the music events to the appropriate engravers and/or
1421 performers.
1422
1423
1424 @node Engraver tutorial
1425 @section Engraver tutorial
1426
1427 Engravers are C++ classes that catch music events and
1428 create the appropriate grobs for display on the page.  Though the
1429 majority of engravers are responsible for the creation of a single grob,
1430 in some cases (e.g. @code{New_fingering_engraver}), several different grobs
1431 may be created.
1432
1433 Engravers listen for events and acknowledge grobs.  Events are passed to
1434 the engraver in time-step order during the iteration phase.  Grobs are
1435 made available to the engraver when they are created by other engravers
1436 during the iteration phase.
1437
1438
1439 @menu
1440 * Useful methods for information processing::
1441 * Translation process::
1442 * Preventing garbage collection for SCM member variables::
1443 * Listening to music events::
1444 * Acknowledging grobs::
1445 * Engraver declaration/documentation::
1446 @end menu
1447
1448 @node Useful methods for information processing
1449 @subsection Useful methods for information processing
1450
1451 An engraver inherits the following public methods from the Translator
1452 base class, which can be used to process listened events and acknowledged
1453 grobs:
1454
1455 @itemize
1456 @item @code{virtual void initialize ()}
1457 @item @code{void start_translation_timestep ()}
1458 @item @code{void process_music ()}
1459 @item @code{void process_acknowledged ()}
1460 @item @code{void stop_translation_timestep ()}
1461 @item @code{virtual void finalize ()}
1462 @end itemize
1463
1464 These methods are listed in order of translation time, with
1465 @code{initialize ()} and @code{finalize ()} bookending the whole
1466 process.  @code{initialize ()} can be used for one-time initialization
1467 of context properties before translation starts, whereas
1468 @code{finalize ()} is often used to tie up loose ends at the end of
1469 translation: for example, an unterminated spanner might be completed
1470 automatically or reported with a warning message.
1471
1472
1473 @node Translation process
1474 @subsection Translation process
1475
1476 At each timestep in the music, translation proceeds by calling the
1477 following methods in turn:
1478
1479 @code{start_translation_timestep ()} is called before any user
1480 information enters the translators, i.e., no property operations
1481 (\set, \override, etc.) or events have been processed yet.
1482
1483 @code{process_music ()} and @code{process_acknowledged ()} are called
1484 after all events in the current time step have been heard, or all
1485 grobs in the current time step have been acknowledged.  The latter
1486 tends to be used exclusively with engravers which only acknowledge
1487 grobs, whereas the former is the default method for main processing
1488 within engravers.
1489
1490 @code{stop_translation_timestep ()} is called after all user
1491 information has been processed prior to beginning the translation for
1492 the next timestep.
1493
1494
1495 @node Preventing garbage collection for SCM member variables
1496 @subsection Preventing garbage collection for SCM member variables
1497
1498 In certain cases, an engraver might need to ensure private Scheme
1499 variables (with type SCM) do not get swept away by Guile's garbage
1500 collector: for example, a cache of the previous key signature which
1501 must persist between timesteps.  The method
1502 @code{virtual derived_mark () const} can be used in such cases:
1503
1504 @example
1505 Engraver_name::derived_mark ()
1506 @{
1507   scm_gc_mark (private_scm_member_)
1508 @}
1509 @end example
1510
1511
1512 @node Listening to music events
1513 @subsection Listening to music events
1514
1515 External interfaces to the engraver are implemented by protected
1516 macros including one or more of the following:
1517
1518 @itemize
1519 @item @code{DECLARE_TRANSLATOR_LISTENER (event_name)}
1520 @item @code{IMPLEMENT_TRANSLATOR_LISTENER (Engraver_name, event_name)}
1521 @end itemize
1522
1523 @noindent
1524 where @var{event_name} is the type of event required to provide the
1525 input the engraver needs and @var{Engraver_name} is the name of the
1526 engraver.
1527
1528 Following declaration of a listener, the method is implemented as follows:
1529
1530 @example
1531 IMPLEMENT_TRANSLATOR_LISTENER (Engraver_name, event_name)
1532 void
1533 Engraver_name::listen_event_name (Stream event *event)
1534 @{
1535   ...body of listener method...
1536 @}
1537 @end example
1538
1539
1540 @node Acknowledging grobs
1541 @subsection Acknowledging grobs
1542
1543 Some engravers also need information from grobs as they are created
1544 and as they terminate.  The mechanism and methods to obtain this
1545 information are set up by the macros:
1546
1547 @itemize
1548 @item @code{DECLARE_ACKNOWLEDGER (grob_interface)}
1549 @item @code{DECLARE_END_ACKNOWLEDGER (grob_interface)}
1550 @end itemize
1551
1552 where @var{grob_interface} is an interface supported by the
1553 grob(s) which should be acknowledged.  For example, the following
1554 code would declare acknowledgers for a @code{NoteHead} grob (via the
1555 @code{note-head-interface}) and any grobs which support the
1556 @code{side-position-interface}:
1557
1558 @example
1559 @code{DECLARE_ACKNOWLEDGER (note_head)}
1560 @code{DECLARE_ACKNOWLEDGER (side_position)}
1561 @end example
1562
1563 The @code{DECLARE_END_ACKNOWLEDGER ()} macro sets up a spanner-specific
1564 acknowledger which will be called whenever a spanner ends.
1565
1566 Following declaration of an acknowledger, the method is coded as follows:
1567
1568 @example
1569 void
1570 Engraver_name::acknowledge_interface_name (Grob_info info)
1571 @{
1572   ...body of acknowledger method...
1573 @}
1574 @end example
1575
1576
1577 @node Engraver declaration/documentation
1578 @subsection Engraver declaration/documentation
1579
1580 An engraver must have a public macro
1581
1582 @itemize
1583 @item @code{TRANSLATOR_DECLARATIONS (Engraver_name)}
1584 @end itemize
1585
1586 @noindent
1587 where @code{Engraver_name} is the name of the engraver.  This
1588 defines the common variables and methods used by every engraver.
1589
1590 At the end of the engraver file, one or both of the following
1591 macros are generally called to document the engraver in the
1592 Internals Reference:
1593
1594 @itemize
1595 @item @code{ADD_ACKNOWLEDGER (Engraver_name, grob_interface)}
1596 @item @code{ADD_TRANSLATOR (Engraver_name, Engraver_doc,
1597     Engraver_creates, Engraver_reads, Engraver_writes)}
1598 @end itemize
1599
1600 @noindent
1601 where @code{Engraver_name} is the name of the engraver, @code{grob_interface}
1602 is the name of the interface that will be acknowledged,
1603 @code{Engraver_doc} is a docstring for the engraver,
1604 @code{Engraver_creates} is the set of grobs created by the engraver,
1605 @code{Engraver_reads} is the set of properties read by the engraver,
1606 and @code{Engraver_writes} is the set of properties written by
1607 the engraver.
1608
1609 The @code{ADD_ACKNOWLEDGER} and @code{ADD_TRANSLATOR} macros use a
1610 non-standard indentation system.  Each interface, grob, read property,
1611 and write property is on its own line, and the closing parenthesis
1612 and semicolon for the macro all occupy a separate line beneath the final
1613 interface or write property.  See existing engraver files for more
1614 information.
1615
1616
1617 @node Callback tutorial
1618 @section Callback tutorial
1619
1620 TODO -- This is a placeholder for a tutorial on callback functions.
1621
1622 @node LilyPond scoping
1623 @section LilyPond scoping
1624
1625 The Lilypond language has a concept of scoping, i.e. you can do
1626
1627 @example
1628 foo = 1
1629
1630 #(begin
1631    (display (+ foo 2)))
1632 @end example
1633
1634 @noindent with @code{\paper}, @code{\midi} and @code{\header} being
1635 nested scope inside the @file{.ly} file-level scope.  @w{@code{foo = 1}}
1636 is translated in to a scheme variable definition.
1637
1638 This implemented using modules, with each scope being an anonymous
1639 module that imports its enclosing scope's module.
1640
1641 Lilypond's core, loaded from @file{.scm} files, is usually placed in the
1642 @code{lily} module, outside the @file{.ly} level.  In the case of
1643
1644 @example
1645 lilypond a.ly b.ly
1646 @end example
1647
1648 @noindent
1649 we want to reuse the built-in definitions, without changes effected in
1650 user-level @file{a.ly} leaking into the processing of @file{b.ly}.
1651
1652 The user-accessible definition commands have to take care to avoid
1653 memory leaks that could occur when running multiple files.  All
1654 information belonging to user-defined commands and markups is stored in
1655 a manner that allows it to be garbage-collected when the module is
1656 dispersed, either by being stored module-locally, or in weak hash
1657 tables.
1658
1659 @node LilyPond miscellany
1660 @section LilyPond miscellany
1661
1662 This is a place to dump information that may be of use to developers
1663 but doesn't yet have a proper home.  Ideally, the length of this section
1664 would become zero as items are moved to other homes.
1665
1666
1667 @menu
1668 * Spacing algorithms::
1669 * Info from Han-Wen email::
1670 * Music functions and GUILE debugging::
1671 @end menu
1672
1673 @node Spacing algorithms
1674 @subsection Spacing algorithms
1675
1676 Here is information from an email exchange about spacing algorithms.
1677
1678 On Thu, 2010-02-04 at 15:33 -0500, Boris Shingarov wrote:
1679 I am experimenting with some modifications to the line breaking code,
1680 and I am stuck trying to understand how some of it works.  So far my
1681 understanding is that Simple_spacer operates on a vector of Grobs, and
1682 it is a well-known Constrained-QP problem (rods = constraints, springs
1683 = quadratic function to minimize).  What I don't understand is, if the
1684 spacer operates at the level of Grobs, which are built at an earlier
1685 stage in the pipeline, how are the changes necessitated by differences
1686 in line breaking, taken into account?  in other words, if I take the
1687 last measure of a line and place it on the next line, it is not just a
1688 matter of literally moving that graphic to where the start of the next
1689 line is, but I also need to draw a clef, key signature, and possibly
1690 other fundamental things -- but at that stage in the rendering
1691 pipeline, is it not too late??
1692
1693 Joe Neeman answered:
1694
1695 We create lots of extra grobs (eg. a BarNumber at every bar line) but
1696 most of them are not drawn.  See the break-visibility property in
1697 item-interface.
1698
1699
1700 @node Info from Han-Wen email
1701 @subsection Info from Han-Wen email
1702
1703 In 2004, Douglas Linhardt decided to try starting a document that would
1704 explain LilyPond architecture and design principles.  The material below
1705 is extracted from that email, which can be found at
1706 @uref{http://thread.gmane.org/gmane.comp.gnu.lilypond.devel/2992}.
1707 The headings reflect questions from Doug or comments from Han-Wen;
1708 the body text are Han-Wen's answers.
1709
1710 @subheading Figuring out how things work.
1711
1712 I must admit that when I want to know how a program works, I use grep
1713 and emacs and dive into the source code.  The comments and the code
1714 itself are usually more revealing than technical documents.
1715
1716 @subheading What's a grob, and how is one used?
1717
1718 Graphical object - they are created from within engravers, either as
1719 Spanners (derived class) -slurs, beams- or Items (also a derived
1720 class) -notes, clefs, etc.
1721
1722 There are two other derived classes System (derived from Spanner,
1723 containing a "line of music") and Paper_column (derived from Item, it
1724 contains all items that happen at the same moment).  They are separate
1725 classes because they play a special role in the linebreaking process.
1726
1727 @subheading What's a smob, and how is one used?
1728
1729 A C(++) object that is encapsulated so it can be used as a Scheme
1730 object.  See GUILE info, "19.3 Defining New Types (Smobs)"
1731
1732 @@subheading When is each C++ class constructed and used
1733
1734 @itemize
1735
1736 @item
1737 Music classes
1738
1739 In the parser.yy see the macro calls MAKE_MUSIC_BY_NAME().
1740
1741 @item
1742 Contexts
1743
1744 Constructed during "interpreting" phase.
1745
1746 @item
1747 Engravers
1748
1749 Executive branch of Contexts, plugins that create grobs, usually one
1750 engraver per grob type.  Created  together with context.
1751
1752 @item
1753 Layout Objects
1754
1755 = grobs
1756
1757 @item
1758 Grob Interfaces
1759
1760 These are not C++ classes per se.  The idea of a Grob interface hasn't
1761 crystallized well.  ATM, an interface is a symbol, with a bunch of grob
1762 properties.  They are not objects that are created or destroyed.
1763
1764 @item
1765 Iterators
1766
1767 Objects that walk through different music classes, and deliver events
1768 in a synchronized way, so that notes that play together are processed
1769 at the same moment and (as a result) end up on the same horizontal position.
1770
1771 Created during interpreting phase.
1772
1773 BTW, the entry point for interpreting is ly:run-translator
1774 (ly_run_translator on the C++ side)
1775
1776 @end itemize
1777
1778 @subheading Can you get to Context properties from a Music object?
1779
1780 You can create music object with a Scheme function that reads context
1781 properties (the \applycontext syntax).  However, that function is
1782 executed during Interpreting, so you can not really get Context
1783 properties from Music objects, since music objects are not directly
1784 connected to Contexts.  That connection is made by the  Music_iterators
1785
1786 @subheading Can you get to Music properties from a Context object?
1787
1788 Yes, if you are given the music object within a Context
1789 object.  Normally, the music objects enter Contexts in synchronized
1790 fashion, and the synchronization is done by Music_iterators.
1791
1792 @subheading What is the relationship between C++ classes and Scheme objects?
1793
1794 Smobs are C++ objects in Scheme.  Scheme objects (lists, functions) are
1795 manipulated from C++ as well using the GUILE C function interface
1796 (prefix: scm_)
1797
1798 @subheading How do Scheme procedures get called from C++ functions?
1799
1800 scm_call_*, where * is an integer from 0 to 4.
1801 Also scm_c_eval_string (), scm_eval ()
1802
1803 @subheading How do C++ functions get called from Scheme procedures?
1804
1805 Export a C++ function to Scheme with LY_DEFINE.
1806
1807 @subheading What is the flow of control in the program?
1808
1809 Good question.  Things used to be clear-cut, but we have Scheme
1810 and SMOBs now, which means that interactions do not follow a very
1811 rigid format anymore.  See below for an overview, though.
1812
1813 @subheading Does the parser make Scheme procedure calls or C++ function calls?
1814
1815 Both.  And the Scheme calls can call C++ and vice versa.  It's nested,
1816 with the SCM datatype as lubrication between the interactions
1817
1818 (I think the word "lubrication" describes the process better than the
1819 traditional word "glue")
1820
1821 @subheading How do the front-end and back-end get started?
1822
1823 Front-end: a file is parsed, the rest follows from that.  Specifically,
1824
1825 Parsing leads to a Music + Music_output_def object (see parser.yy,
1826 definition of toplevel_expression )
1827
1828 A Music + Music_output_def object leads to a Global_context object (see
1829 ly_run_translator ())
1830
1831 During interpreting, Global_context + Music leads to a bunch of
1832 Contexts (see Global_translator::run_iterator_on_me ()).
1833
1834 After interpreting, Global_context contains a Score_context (which
1835 contains staves, lyrics etc.) as a child.  Score_context::get_output ()
1836 spews a Music_output object (either a Paper_score object for notation
1837 or Performance object for MIDI).
1838
1839 The Music_output object is the entry point for the backend (see
1840 ly_render_output ()).
1841
1842 The main steps of the backend itself are in
1843
1844 @itemize
1845
1846 @item
1847 @file{paper-score.cc} , Paper_score::process_
1848
1849 @item
1850 @file{system.cc} , System::get_lines()
1851
1852 @item
1853 The step, where things go from grobs to output, is in
1854 System::get_line(): each grob delivers a Stencil (a Device
1855 independent output description), which is interpreted by our
1856 outputting backends (@file{scm/output-tex.scm} and
1857 @file{scm/output-ps.scm}) to produce TeX and PS.
1858
1859 @end itemize
1860
1861 Interactions between grobs and putting things into .tex and .ps files
1862 have gotten a little more complex lately.  Jan has implemented
1863 page-breaking, so now the backend also involves Paper_book,
1864 Paper_lines and other things.  This area is still heavily in flux, and
1865 perhaps not something you should want to look at.
1866
1867 @subheading How do the front-end and back-end communicate?
1868
1869 There is no communication from backend to front-end.  From front-end to
1870 backend is simply the program flow: music + definitions gives
1871 contexts, contexts yield output, after processing, output is written
1872 to disk.
1873
1874 @subheading Where is the functionality associated with KEYWORDs?
1875
1876 See @file{my-lily-lexer.cc} (keywords, there aren't that many)
1877 and @file{ly/*.ly} (most of the other backslashed @code{/\words} are identifiers)
1878
1879 @subheading What Contexts/Properties/Music/etc. are available when they are processed?
1880
1881 What do you mean exactly with this question?
1882
1883 See @file{ly/engraver-init.ly} for contexts,
1884 see @file{scm/define-*.scm} for other objects.
1885
1886 @subheading How do you decide if something is a Music, Context, or Grob property?
1887 Why is part-combine-status a Music property when it seems (IMO)
1888 to be related to the Staff context?
1889
1890 The Music_iterators and Context communicate through two channels
1891
1892 Music_iterators can set and read context properties, idem for
1893 Engravers and Contexts
1894
1895 Music_iterators can send "synthetic" music events (which aren't in
1896 the input) to a context.  These are caught by Engravers.  This is
1897 mostly a one way communication channel.
1898
1899 part-combine-status is part of such a synthetic event, used by
1900 Part_combine_iterator to communicate with Part_combine_engraver.
1901
1902
1903 @subheading Deciding between context and music properties
1904
1905 I'm adding a property to affect how \autochange works.  It seems to
1906 me that it should be a context property, but the Scheme autochange
1907 procedure has a Music argument.  Does this mean I should use
1908 a Music property?
1909
1910 \autochange is one of these extra strange beasts: it requires
1911 look-ahead to decide when to change staves.  This is achieved by
1912 running the interpreting step twice (see
1913 @file{scm/part-combiner.scm} , at the bottom), and
1914 storing the result of the first step (where to switch
1915 staves) in a Music property.  Since you want to influence that
1916 where-to-switch list, your must affect the code in
1917 make-autochange-music (@file{scm/part-combiner.scm}).
1918 That code is called directly from the parser and there are no
1919 official "parsing properties" yet, so there is no generic way
1920 to tune \autochange.  We would have to invent something new
1921 for this, or add a separate argument,
1922
1923 @example
1924     \autochange #around-central-C ..music..
1925 @end example
1926
1927 @noindent
1928 where around-central-C is some function that is called from
1929 make-autochange-music.
1930
1931 @subheading More on context and music properties
1932
1933 From Neil Puttock, in response to a question about transposition:
1934
1935 Context properties (using \set & \unset) are tied to engravers: they
1936 provide information relevant to the generation of graphical objects.
1937
1938 Since transposition occurs at the music interpretation stage, it has
1939 no direct connection with engravers: the pitch of a note is fixed
1940 before a notehead is created.  Consider the following minimal snippet:
1941
1942 @example
1943 @{ c' @}
1944 @end example
1945
1946 This generates (simplified) a NoteEvent, with its pitch and duration
1947 as event properties,
1948
1949 @example
1950 (make-music
1951   'NoteEvent
1952   'duration
1953   (ly:make-duration 2 0 1 1)
1954   'pitch
1955   (ly:make-pitch 0 0 0)
1956 @end example
1957
1958 which the Note_heads_engraver hears.  It passes this information on to
1959 the NoteHead grob it creates from the event, so the head's correct
1960 position and duration-log can be determined once it's ready for
1961 printing.
1962
1963 If we transpose the snippet,
1964
1965 @example
1966 \transpose c d @{ c' @}
1967 @end example
1968
1969 the pitch is changed before it reaches the engraver (in fact, it
1970 happens just after the parsing stage with the creation of a
1971 TransposedMusic music object):
1972
1973 @example
1974 (make-music
1975  'NoteEvent
1976  'duration
1977  (ly:make-duration 2 0 1 1)
1978  'pitch
1979  (ly:make-pitch 0 1 0)
1980 @end example
1981
1982 You can see an example of a music property relevant to transposition:
1983 untransposable.
1984
1985 @example
1986 \transpose c d @{ c'2 \withMusicProperty #'untransposable ##t c' @}
1987 @end example
1988
1989 -> the second c' remains untransposed.
1990
1991 Take a look at @file{lily/music.cc} to see where the transposition takes place.
1992
1993
1994 @subheading How do I tell about the execution environment?
1995
1996 I get lost figuring out what environment the code I'm looking at is in when it
1997 executes.  I found both the C++ and Scheme autochange code.  Then I was trying
1998 to figure out where the code got called from.  I finally figured out that the
1999 Scheme procedure was called before the C++ iterator code, but it took me a
2000 while to figure that out, and I still didn't know who did the calling in the
2001 first place.  I only know a little bit about Flex and Bison, so reading those
2002 files helped only a little bit.
2003
2004 @emph{Han-Wen:} GDB can be of help here.  Set a breakpoint in C++, and run.  When you
2005 hit the breakpoint, do a backtrace.  You can inspect Scheme objects
2006 along the way by doing
2007
2008 @example
2009 p ly_display_scm(obj)
2010 @end example
2011
2012 this will display OBJ through GUILE.
2013
2014 @node Music functions and GUILE debugging
2015 @subsection Music functions and GUILE debugging
2016
2017 Ian Hulin was trying to do some debugging in music functions, and
2018 came up with the following question
2019
2020 HI all,
2021 I'm working on the Guile Debugger Stuff, and would like to try
2022 debugging a music function definition such as:
2023
2024 @example
2025 conditionalMark = #(define-music-function (parser location) ()
2026     #@{ \tag #'instrumental-part @{\mark \default@}  #@} )
2027 @end example
2028
2029 It appears conditionalMark does not get set up as an
2030 equivalent of a Scheme
2031
2032 @example
2033 (define conditionalMark = define-music-function(parser location () ...
2034 @end example
2035
2036 @noindent
2037 although something gets defined because Scheme apparently recognizes
2038
2039 @example
2040 #(set-break! conditionalMark)
2041 @end example
2042
2043 @noindent
2044 later on in the file without signalling any Guile errors.
2045
2046 However the breakpoint trap is never encountered as
2047 define-music-function passed things on to ly:make-music-function,
2048 which is really C++ code ly_make_music_function, so Guile never
2049 finds out about the breakpoint.
2050
2051 Han-Wen answered as follows:
2052
2053 You can see the definition by doing
2054
2055 @example
2056 #(display conditionalMark)
2057 @end example
2058
2059 noindent
2060 inside the @file{.ly} file.
2061
2062 The breakpoint failing may have to do with the call sequence.  See
2063 @file{parser.yy}, run_music_function().  The function is called directly from
2064 C++, without going through the GUILE evaluator, so I think that is why
2065 there is no debugger trap.