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