]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-parser.cc
* lily/include/object-key-undumper.hh (Module): new file.
[lilypond.git] / lily / lily-parser.cc
1 /*
2   lily-parser.cc -- implement Lily_parser
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2004 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7        Jan Nieuwenhuizen <janneke@gnu.org>
8 */
9
10
11 #include "book.hh"
12 #include "lilypond-key.hh"
13 #include "context-selector.hh"
14 #include "grob-selector.hh"
15 #include "file-name.hh"
16 #include "file-path.hh"
17 #include "lily-version.hh"
18 #include "ly-module.hh"
19 #include "main.hh"
20 #include "lily-lexer.hh"
21 #include "lily-parser.hh"
22 #include "output-def.hh"
23 #include "paper-book.hh"
24 #include "parser.hh"
25 #include "score.hh"
26 #include "source.hh"
27 #include "warn.hh"
28
29
30 Lily_parser::Lily_parser (Sources *sources)
31 {
32   book_count_ = 0;
33   score_count_ = 0;
34   lexer_ = 0;
35   sources_ = sources;
36   default_duration_ = Duration (2, 0);
37   error_level_ = 0;
38   last_beam_start_ = SCM_EOL;
39
40   smobify_self ();
41 }
42
43 Lily_parser::Lily_parser (Lily_parser const &src)
44 {
45   book_count_ = src.book_count_;
46   score_count_ = src.score_count_;
47   lexer_ = 0;
48   sources_ = src.sources_;
49   default_duration_ = src.default_duration_;
50   error_level_ = src.error_level_;
51   last_beam_start_ = src.last_beam_start_;
52
53   smobify_self ();
54   if (src.lexer_)
55     lexer_ = new Lily_lexer (*src.lexer_);
56
57   scm_gc_unprotect_object (lexer_->self_scm ());
58 }
59
60 Lily_parser::~Lily_parser ()
61 {
62 }
63
64 #include "ly-smobs.icc"
65
66 IMPLEMENT_SMOBS (Lily_parser);
67 IMPLEMENT_TYPE_P (Lily_parser, "ly:lily-parser?");
68 IMPLEMENT_DEFAULT_EQUAL_P (Lily_parser);
69
70 SCM
71 Lily_parser::mark_smob (SCM s)
72 {
73   Lily_parser *parser = (Lily_parser*) SCM_CELL_WORD_1 (s);
74   return (parser->lexer_) ? parser->lexer_->self_scm () : SCM_EOL;
75 }
76
77 int
78 Lily_parser::print_smob (SCM s, SCM port, scm_print_state*)
79 {
80   scm_puts ("#<my_lily_parser ", port);
81   Lily_parser *parser = (Lily_parser*) SCM_CELL_WORD_1 (s);
82   (void) parser;
83   scm_puts (" >", port);
84   return 1;
85 }
86
87
88 /* Process one .ly file, or book.  */
89 void
90 Lily_parser::parse_file (String init, String name, String out_name)
91 {
92   lexer_ = new Lily_lexer (sources_);
93   scm_gc_unprotect_object (lexer_->self_scm ());
94   // TODO: use $parser 
95   lexer_->set_identifier (ly_symbol2scm ("parser"),
96                           self_scm ());
97   output_basename_ = out_name;
98   
99   lexer_->main_input_name_ = name;
100
101   progress_indication (_ ("Parsing..."));
102   progress_indication ("\n");
103
104   set_yydebug (0);
105
106   lexer_->new_input (init, sources_);
107 #ifdef TWEAK
108   File_name f (name);
109   String s = global_path.find (f.base_ + ".twy");
110   if (s == "")
111     Grob_selector::set_tweaks (SCM_EOL);
112   else
113     {
114       s = gulp_file_to_string (s, false);
115       SCM tweaks = scm_eval_string (scm_makfrom0str (s.to_str0 ()));
116       Grob_selector::set_tweaks (tweaks);
117     }
118   Context_selector::set_tweaks (SCM_EOL);
119 #endif  
120
121   /* Read .ly IN_FILE, lex, parse, write \score blocks from IN_FILE to
122      OUT_FILE (unless IN_FILE redefines output file name).  */
123   do_yyparse ();
124
125   if (!define_spots_.is_empty ())
126     {
127       define_spots_.top ().warning (_ ("Braces don't match"));
128       error_level_ = 1;
129     }
130
131   error_level_ = error_level_ | lexer_->error_level_;
132   lexer_ = 0;
133 }
134
135 void
136 Lily_parser::parse_string (String ly_code)
137 {
138   Lily_lexer * parent = lexer_;
139   lexer_ = (parent == 0 ? new Lily_lexer (sources_)
140             : new Lily_lexer (*parent));
141   scm_gc_unprotect_object (lexer_->self_scm ());
142
143
144   SCM oldmod = scm_current_module ();
145   scm_set_current_module (scm_car (lexer_->scopes_));
146   
147   // TODO: use $parser 
148   lexer_->set_identifier (ly_symbol2scm ("parser"),
149                           self_scm ());
150   
151   lexer_->main_input_name_ = "<string>";
152   lexer_->main_input_b_ = true;
153
154   set_yydebug (0);
155   lexer_->new_input (lexer_->main_input_name_, ly_code, sources_);
156   do_yyparse ();
157   
158   if (!define_spots_.is_empty ())
159     {
160       define_spots_.top ().warning (_ ("Braces don't match"));
161       error_level_ = 1;
162     }
163
164   error_level_ = error_level_ | lexer_->error_level_;
165
166   scm_set_current_module (oldmod);
167   lexer_ = 0;
168 }
169
170 void
171 Lily_parser::push_spot ()
172 {
173   define_spots_.push (here_input ());
174 }
175
176 char const *
177 Lily_parser::here_str0 () const
178 {
179   return lexer_->here_str0 ();
180 }
181
182 void
183 Lily_parser::parser_error (String s)
184 {
185   here_input ().error (s);
186   error_level_ = 1;
187 }
188
189 Input
190 Lily_parser::pop_spot ()
191 {
192   return define_spots_.pop ();
193 }
194
195 Input
196 Lily_parser::here_input () const
197 {
198   /*
199     Parsing looks ahead , so we really want the previous location of the
200     lexer, not lexer_->here_input ().
201   */
202   
203   /*
204     Actually, that gets very icky when there are white space, because
205     the line-numbers are all wrong.  Let's try the character before
206     the current token. That gets the right result for note/duration
207     stuff, but doesn't mess up for errors in the 1st token of the
208     line.
209   */
210   Input hi (lexer_->here_input ());
211
212   char const * bla = hi.defined_str0_;
213   if (hi.line_number () > 1
214       || hi.column_number () > 1)
215     bla --;
216   
217   return Input (hi.source_file_, bla);
218 }
219
220
221 /****************************************************************/
222
223
224 /*
225   junkme?
226  */
227 bool store_locations_global_b;
228
229 /* Do not append `!' suffix, since 1st argument is not modified. */
230 LY_DEFINE (ly_set_point_and_click, "ly:set-point-and-click",
231            1, 0, 0, (SCM what),
232           "Set the options for Point-and-click source specials output. The\n"
233 "argument is a symbol.  Possible options are @code{none} (no source specials),\n"
234 "@code{line} and @code{line-column}")
235 {
236   /* UGH. */
237   SCM val = SCM_BOOL_F;
238   if (ly_symbol2scm ("line-column") == what)
239     val = ly_scheme_function ("line-column-location");
240   else if (what == ly_symbol2scm ("line"))
241     val = ly_scheme_function ("line-location");
242
243   scm_module_define (global_lily_module, ly_symbol2scm ("point-and-click"),
244                      val);
245   store_locations_global_b = ly_c_procedure_p (val);
246   return SCM_UNSPECIFIED;
247 }
248
249 LY_DEFINE (ly_parse_file, "ly:parse-file",
250            1, 0, 0, (SCM name),
251            "Parse a single @code{.ly} file.  "
252            "Upon failure, throw @code{ly-file-failed} key.")
253 {
254   SCM_ASSERT_TYPE (scm_is_string (name), name, SCM_ARG1, __FUNCTION__, "string");
255   char const *file = scm_i_string_chars (name);
256   char const *extensions[] = {"ly", "", 0};
257
258   String file_name = global_path.find (file, extensions);
259
260   /* By default, use base name of input file for output file name,
261      write output to cwd; do not use root and directory parts of input
262      file name.  */
263   File_name out_file_name (file_name);
264
265   global_path.append (out_file_name.dir_);
266   
267   out_file_name.ext_ = "";
268   out_file_name.root_ = "";
269   out_file_name.dir_ = "";
270
271   if (!output_name_global.is_empty ())
272     out_file_name = File_name (output_name_global);
273   
274   String init;
275   if (!init_name_global.is_empty ())
276     init = init_name_global;
277   else
278     init = "init.ly";
279
280   String out_file = out_file_name.to_string ();
281
282   if (init.length () && global_path.find (init).is_empty ())
283     {
284       warning (_f ("can't find init file: `%s'", init));
285       warning (_f ("(search path: `%s')",
286                    global_path.to_string ().to_str0 ()));
287       exit (2);
288     }
289
290   if ((file_name != "-") && global_path.find (file_name).is_empty ())
291     {
292       warning (_f ("can't find file: `%s'", file_name));
293       scm_throw (ly_symbol2scm ("ly-file-failed"),
294                  scm_list_1 (scm_makfrom0str (file_name.to_str0 ())));
295     }
296   else
297     {
298       Sources sources;
299       sources.set_path (&global_path);
300   
301       progress_indication (_f ("Processing `%s'", file_name.to_str0 ()));
302       progress_indication ("\n");
303
304       Lily_parser *parser = new Lily_parser (&sources);
305
306       parser->parse_file (init, file_name, out_file);
307
308       bool error = parser->error_level_;
309       scm_gc_unprotect_object (parser->self_scm ());
310       parser = 0;
311       if (error)
312         /* TODO: pass renamed input file too.  */
313         scm_throw (ly_symbol2scm ("ly-file-failed"),
314                    scm_list_1 (scm_makfrom0str (file_name.to_str0 ())));
315     }
316   return SCM_UNSPECIFIED;
317 }
318
319 LY_DEFINE (ly_parse_string, "ly:parse-string",
320            1, 0, 0, (SCM ly_code),
321            "Parse the string LY_CODE.  "
322            "Upon failure, throw @code{ly-file-failed} key.")
323 {
324   SCM_ASSERT_TYPE (scm_is_string (ly_code), ly_code, SCM_ARG1, __FUNCTION__, "string");
325   
326   Sources sources;
327   sources.set_path (&global_path);
328   Lily_parser *parser = new Lily_parser (&sources);
329   scm_module_define (global_lily_module, ly_symbol2scm ("parser"),
330                      parser->self_scm ());
331   parser->parse_string (ly_scm2string (ly_code));
332   scm_gc_unprotect_object (parser->self_scm ());
333   parser = 0;
334   
335   return SCM_UNSPECIFIED;
336 }
337
338 LY_DEFINE (ly_clone_parser, "ly:clone-parser",
339            1, 0, 0, (SCM parser_smob),
340            "Return a clone of PARSER_SMOB.")
341 {
342   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
343   Lily_parser *clone = new Lily_parser (*parser);
344
345   /* FIXME: should copy scopes too. */
346   return scm_gc_unprotect_object (clone->self_scm ());
347 }
348
349 LY_DEFINE (ly_parser_define, "ly:parser-define",
350            3, 0, 0, (SCM parser_smob, SCM symbol, SCM val),
351            "Bind SYMBOL to VAL in PARSER_SMOB's module.")
352 {
353   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
354   SCM_ASSERT_TYPE (scm_is_symbol (symbol), symbol, SCM_ARG2, __FUNCTION__, "symbol");
355   SCM_ASSERT_TYPE (parser, parser_smob, SCM_ARG2, __FUNCTION__, "parser");  
356
357   parser->lexer_->set_identifier (scm_symbol_to_string (symbol), val);
358   return SCM_UNSPECIFIED;
359 }
360
361 LY_DEFINE (ly_parser_lookup, "ly:parser-lookup",
362            2, 0, 0, (SCM parser_smob, SCM symbol),
363            "Lookup @var{symbol} in @var{parser_smob}'s module.  "
364            "Undefined is '().")
365 {
366   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
367
368   SCM_ASSERT_TYPE (scm_is_symbol (symbol), symbol, SCM_ARG2, __FUNCTION__, "symbol");
369   SCM_ASSERT_TYPE (parser, parser_smob, SCM_ARG2, __FUNCTION__, "parser");  
370
371   SCM val= parser->lexer_->lookup_identifier (ly_scm2string (scm_symbol_to_string (symbol)));
372   if (val != SCM_UNDEFINED)
373     return val;
374   else
375     return SCM_EOL;
376 }
377
378 LY_DEFINE (ly_parser_parse_string, "ly:parser-parse-string",
379            2, 0, 0, (SCM parser_smob, SCM ly_code),
380            "Parse the string LY_CODE with PARSER_SMOB."
381            "Upon failure, throw @code{ly-file-failed} key.")
382 {
383   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
384
385   SCM_ASSERT_TYPE (parser, parser_smob, SCM_ARG1, __FUNCTION__, "parser");
386   SCM_ASSERT_TYPE (scm_is_string (ly_code), ly_code, SCM_ARG2, __FUNCTION__, "string");
387   
388   parser->parse_string (ly_scm2string (ly_code));
389   
390   return SCM_UNSPECIFIED;
391 }
392
393 Output_def*
394 get_layout (Lily_parser *parser)
395 {
396   SCM id = parser->lexer_->lookup_identifier ("$defaultlayout");
397   Output_def *layout = unsmob_output_def (id);
398   layout = layout ? layout->clone () : new Output_def;
399   layout->set_variable (ly_symbol2scm ("is-layout"), SCM_BOOL_T);
400
401   return layout;
402 }
403
404
405 Output_def*
406 get_midi (Lily_parser *parser)
407 {
408   SCM id = parser->lexer_->lookup_identifier ("$defaultmidi");
409   Output_def *layout = unsmob_output_def (id);
410   layout = layout ? layout->clone () : new Output_def;
411   layout->set_variable (ly_symbol2scm ("is-midi"), SCM_BOOL_T);
412   return layout;
413 }
414
415
416 Output_def*
417 get_paper (Lily_parser *parser)
418 {
419   SCM id = parser->lexer_->lookup_identifier ("$defaultpaper");
420   Output_def *layout = unsmob_output_def (id);
421
422   layout = layout ? dynamic_cast<Output_def*> (layout->clone ()) : new Output_def;
423   layout->set_variable (ly_symbol2scm ("is-paper"), SCM_BOOL_T);
424   return layout;
425 }
426
427
428 /* TODO: move this to Scheme?  Why take the parser arg, and all the back
429    & forth between scm and c++? */
430 LY_DEFINE (ly_parser_print_score, "ly:parser-print-score",
431            2, 0, 0,
432            (SCM parser_smob, SCM score_smob),
433            "Print score, i.e., the classic way.")
434 {
435   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
436   Score *score = unsmob_score (score_smob);
437
438   Object_key * key = new Lilypond_general_key (0, score->user_key_, 0);
439   
440   if (score->error_found_)
441     return SCM_UNSPECIFIED;
442   
443   SCM_ASSERT_TYPE (parser, parser_smob, SCM_ARG1, __FUNCTION__, "parser");
444   SCM_ASSERT_TYPE (score, score_smob, SCM_ARG2, __FUNCTION__, "score");
445
446   SCM header = ly_c_module_p (score->header_) ? score->header_
447     : parser->lexer_->lookup_identifier ("$globalheader");
448   
449   File_name outname (parser->output_basename_);
450   int *c = &parser->book_count_;
451   if (*c)
452     outname.base_ += "-" + to_string (*c);
453   (*c)++;
454
455   SCM os = scm_makfrom0str (outname.to_string ().to_str0 ());
456   SCM paper = get_paper (parser)->self_scm ();
457   for (int i = 0; i < score->defs_.size (); i++)
458     default_rendering (score->get_music (), score->defs_[i]->self_scm (),
459                        paper,
460                        header, os,
461                        key->self_scm ());
462
463   if (score->defs_.is_empty ())
464     {
465       Output_def *layout = get_layout (parser);
466       default_rendering (score->get_music(), layout->self_scm (),
467                          get_paper (parser)->self_scm (),
468                          header, os, key->self_scm ());
469       scm_gc_unprotect_object (layout->self_scm ());
470     }
471
472   scm_gc_unprotect_object (key->self_scm ());
473   return SCM_UNSPECIFIED;
474 }
475
476
477 LY_DEFINE (ly_parser_set_note_names, "ly:parser-set-note-names",
478            2, 0, 0, (SCM parser, SCM names),
479            "Replace current note names in @var{parser}. "
480            "@var{names} is an alist of symbols.  "
481            "This only has effect if the current mode is notes.")
482 {
483   Lily_parser *p = unsmob_my_lily_parser (parser);
484   SCM_ASSERT_TYPE(p, parser, SCM_ARG1, __FUNCTION__, "Lilypond parser");
485
486   if (p->lexer_->is_note_state ())
487     {
488       p->lexer_->pop_state ();
489       p->lexer_->push_note_state (alist_to_hashq (names));
490     }
491
492   return SCM_UNSPECIFIED;
493 }
494
495 LY_DEFINE (ly_parser_print_book, "ly:parser-print-book",
496            2, 0, 0, (SCM parser_smob, SCM book_smob),
497            "Print book.")
498 {
499   Lily_parser *parser = unsmob_my_lily_parser (parser_smob);
500   Book *book = unsmob_book (book_smob);
501   Output_def *bp = unsmob_output_def (parser->lexer_->lookup_identifier ("$defaultpaper"));
502   
503   SCM_ASSERT_TYPE (parser, parser_smob, SCM_ARG1, __FUNCTION__, "Lilypond parser");
504   SCM_ASSERT_TYPE (book, book_smob, SCM_ARG2, __FUNCTION__, "Book");
505   
506   /*  ugh. changing argument.*/
507   book->paper_ = bp;
508   
509   File_name outname (parser->output_basename_);
510   int *c = &parser->book_count_;
511   if (*c)
512     outname.base_ += "-" + to_string (*c);
513   (*c)++;
514
515   Output_def *layout = get_layout (parser);
516   Paper_book* pb = book->process (outname.to_string (), layout);
517   
518   if (pb)
519     {
520       pb->output (outname.to_string ());
521       scm_gc_unprotect_object (pb->self_scm ());
522     }
523
524   scm_gc_unprotect_object (layout->self_scm ());
525   return SCM_UNSPECIFIED;
526 }
527