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