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