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