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