]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
Tie LilyPond, lexer and parser together more type-safely.
[lilypond.git] / lily / lexer.ll
1 %{ // -*-Fundamental-*-
2 /*
3   This file is part of LilyPond, the GNU music typesetter.
4
5   Copyright (C) 1996--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
6                  Jan Nieuwenhuizen <janneke@gnu.org>
7
8   LilyPond is free software: you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation, either version 3 of the License, or
11   (at your option) any later version.
12
13   LilyPond is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 /*
23   backup rules
24
25   after making a change to the lexer rules, run 
26       flex -b <this lexer file>
27   and make sure that 
28       lex.backup
29   contains no backup states, but only the reminder
30       Compressed tables always back up.
31  (don-t forget to rm lex.yy.cc :-)
32  */
33
34
35
36 #include <cstdio>
37 #include <cctype>
38 #include <cerrno>
39
40 /* Flex >= 2.5.29 fix; FlexLexer.h's multiple include bracing breaks
41    when building the actual lexer.  */
42
43 #define LEXER_CC
44
45 #include <iostream>
46 using namespace std;
47
48 #include "context-def.hh"
49 #include "duration.hh"
50 #include "international.hh"
51 #include "interval.hh"
52 #include "lily-guile.hh"
53 #include "lily-lexer.hh"
54 #include "lily-parser.hh"
55 #include "lilypond-version.hh"
56 #include "main.hh"
57 #include "music.hh"
58 #include "music-function.hh"
59 #include "parse-scm.hh"
60 #include "parser.hh"
61 #include "pitch.hh"
62 #include "source-file.hh"
63 #include "std-string.hh"
64 #include "string-convert.hh"
65 #include "version.hh"
66 #include "warn.hh"
67
68 /*
69 RH 7 fix (?)
70 */
71 #define isatty HORRIBLEKLUDGE
72
73 void strip_trailing_white (string&);
74 void strip_leading_white (string&);
75 string lyric_fudge (string s);
76 SCM lookup_markup_command (string s);
77 SCM lookup_markup_list_command (string s);
78 bool is_valid_version (string s);
79
80
81 #define start_quote()   \
82         yy_push_state (quote);\
83         yylval.string = new string
84
85 #define start_lyric_quote()     \
86         yy_push_state (lyric_quote);\
87         yylval.string = new string
88
89 #define yylval (*lexval_)
90
91 #define yylloc (*lexloc_)
92
93 #define YY_USER_ACTION  add_lexed_char (YYLeng ());
94
95
96 SCM scan_fraction (string);
97 SCM (* scm_parse_error_handler) (void *);
98
99
100
101 %}
102
103 %option c++
104 %option noyywrap
105 %option nodefault
106 %option debug
107 %option yyclass="Lily_lexer"
108 %option stack
109 %option never-interactive 
110 %option warn
111
112 %x extratoken
113 %x chords
114 %x figures
115 %x incl
116 %x lyrics
117 %x lyric_quote
118 %x longcomment
119 %x markup
120 %x notes
121 %x quote
122 %x sourcefileline
123 %x sourcefilename
124 %x version
125
126 A               [a-zA-Z\200-\377]
127 AA              {A}|_
128 N               [0-9]
129 AN              {AA}|{N}
130 ANY_CHAR        (.|\n)
131 PUNCT           [?!:'`]
132 ACCENT          \\[`'"^]
133 SPECIAL_CHAR            [&@]
134 NATIONAL        [\001-\006\021-\027\031\036]
135 TEX             {AA}|-|{PUNCT}|{ACCENT}|{NATIONAL}|{SPECIAL_CHAR}
136 DASHED_WORD             {A}({AN}|-)*
137 DASHED_KEY_WORD         \\{DASHED_WORD}
138
139
140
141 ALPHAWORD       {A}+
142 UNSIGNED        {N}+
143 E_UNSIGNED      \\{N}+
144 FRACTION        {N}+\/{N}+
145 INT             -?{UNSIGNED}
146 REAL            ({INT}\.{N}*)|(-?\.{N}+)
147 WHITE           [ \n\t\f\r]
148 HORIZONTALWHITE         [ \t]
149 BLACK           [^ \n\t\f\r]
150 RESTNAME        [rs]
151 NOTECOMMAND     \\{A}+
152 MARKUPCOMMAND   \\({A}|[-_])+
153 LYRICS          ({AA}|{TEX})[^0-9 \t\n\r\f]*
154 ESCAPED         [nt\\'"]
155 EXTENDER        __
156 HYPHEN          --
157 BOM_UTF8        \357\273\277
158
159 %%
160
161
162 <*>\r           {
163         // swallow and ignore carriage returns
164 }
165
166 <extratoken>{ANY_CHAR}  {
167   /* Generate a token without swallowing anything */
168
169   /* First unswallow the eaten character */
170   add_lexed_char (-YYLeng ());
171   yyless (0);
172
173   /* produce requested token */
174   int type = scm_to_int (scm_caar (extra_tokens_));
175   yylval.scm = scm_cdar (extra_tokens_);
176   extra_tokens_ = scm_cdr (extra_tokens_);
177   if (scm_is_null (extra_tokens_))
178     yy_pop_state ();
179
180   return type;
181 }
182
183 <extratoken><<EOF>>     {
184   /* Generate a token without swallowing anything */
185
186   /* produce requested token */
187   int type = scm_to_int (scm_caar (extra_tokens_));
188   yylval.scm = scm_cdar (extra_tokens_);
189   extra_tokens_ = scm_cdr (extra_tokens_);
190   if (scm_is_null (extra_tokens_))
191     yy_pop_state ();
192
193   return type;
194 }
195
196    /* Use the trailing context feature. Otherwise, the BOM will not be
197       found if the file starts with an identifier definition. */
198 <INITIAL,chords,lyrics,figures,notes>{BOM_UTF8}/.* {
199   if (this->lexloc_->line_number () != 1 || this->lexloc_->column_number () != 0)
200     {
201       LexerWarning (_ ("stray UTF-8 BOM encountered").c_str ());
202       // exit (1);
203     }
204   debug_output (_ ("Skipping UTF-8 BOM"));
205 }
206
207 <INITIAL,chords,figures,incl,lyrics,markup,notes>{
208   "%{"  {
209         yy_push_state (longcomment);
210   }
211   %[^{\n\r][^\n\r]*[\n\r]       {
212   }
213   %[^{\n\r]     { // backup rule
214   }
215   %[\n\r]       {
216   }
217   %[^{\n\r][^\n\r]*     {
218   }
219   {WHITE}+      {
220
221   }
222 }
223
224 <INITIAL,notes,figures,chords,markup>{
225         \"              {
226                 start_quote ();
227         }
228 }
229
230 <INITIAL,chords,lyrics,notes,figures>\\version{WHITE}*  {
231         yy_push_state (version);
232 }
233 <INITIAL,chords,lyrics,notes,figures>\\sourcefilename{WHITE}*   {
234         yy_push_state (sourcefilename);
235 }
236 <INITIAL,chords,lyrics,notes,figures>\\sourcefileline{WHITE}*   {
237         yy_push_state (sourcefileline);
238 }
239 <version>\"[^"]*\"     { /* got the version number */
240         string s (YYText () + 1);
241         s = s.substr (0, s.rfind ('\"'));
242
243         yy_pop_state ();
244
245         SCM top_scope = scm_car (scm_last_pair (scopes_));
246         scm_module_define (top_scope, ly_symbol2scm ("version-seen"), SCM_BOOL_T);
247
248         if (!is_valid_version (s))
249                 return INVALID;
250
251
252 }
253 <sourcefilename>\"[^"]*\"     {
254         string s (YYText () + 1);
255         s = s.substr (0, s.rfind ('\"'));
256
257         yy_pop_state ();
258         this->here_input().get_source_file ()->name_ = s;
259         message (_f ("Renaming input to: `%s'", s.c_str ()));
260         progress_indication ("\n");
261         scm_module_define (scm_car (scopes_),
262                      ly_symbol2scm ("input-file-name"),
263                      ly_string2scm (s));
264
265 }
266
267 <sourcefileline>{INT}   {
268         int i;
269         sscanf (YYText (), "%d", &i);
270
271         yy_pop_state ();
272         this->here_input ().get_source_file ()->set_line (here_input ().start (), i);
273 }
274
275 <version>{ANY_CHAR}     {
276         LexerError (_ ("quoted string expected after \\version").c_str ());
277         yy_pop_state ();
278 }
279 <sourcefilename>{ANY_CHAR}      {
280         LexerError (_ ("quoted string expected after \\sourcefilename").c_str ());
281         yy_pop_state ();
282 }
283 <sourcefileline>{ANY_CHAR}      {
284         LexerError (_ ("integer expected after \\sourcefileline").c_str ());
285         yy_pop_state ();
286 }
287 <longcomment>{
288         [^\%]*          {
289         }
290         \%*[^}%]*               {
291
292         }
293         "%"+"}"         {
294                 yy_pop_state ();
295         }
296 }
297
298
299 <INITIAL,chords,lyrics,notes,figures>\\maininput           {
300         if (!is_main_input_)
301         {
302                 start_main_input ();
303                 is_main_input_ = true;
304         }
305         else
306                 error (_ ("\\maininput not allowed outside init files"));
307 }
308
309 <INITIAL,chords,lyrics,figures,notes>\\include           {
310         yy_push_state (incl);
311 }
312 <incl>\"[^""]*\"   { /* got the include file name */
313         string s (YYText ()+1);
314         s = s.substr (0, s.rfind ('"'));
315
316         new_input (s, sources_);
317         yy_pop_state ();
318 }
319 <incl>\\{BLACK}*{WHITE}? { /* got the include identifier */
320         string s = YYText () + 1;
321         strip_trailing_white (s);
322         if (s.length () && (s[s.length () - 1] == ';'))
323           s = s.substr (0, s.length () - 1);
324
325         SCM sid = lookup_identifier (s);
326         if (scm_is_string (sid)) {
327                 new_input (ly_scm2string (sid), sources_);
328                 yy_pop_state ();
329         } else {
330             string msg (_f ("wrong or undefined identifier: `%s'", s ));
331
332             LexerError (msg.c_str ());
333             SCM err = scm_current_error_port ();
334             scm_puts ("This value was found in the table: ", err);
335             scm_display (sid, err);
336           }
337 }
338 <incl>(\$|#) { // scm for the filename
339         int n = 0;
340         Input hi = here_input();
341         hi.step_forward ();
342         SCM sval = ly_parse_scm (hi.start (), &n, hi,
343                 be_safe_global && is_main_input_, parser_);
344         sval = eval_scm (sval);
345
346         for (int i = 0; i < n; i++)
347         {
348                 yyinput ();
349         }
350         char_count_stack_.back () += n;
351
352         if (scm_is_string (sval)) {
353                 new_input (ly_scm2string (sval), sources_);
354                 yy_pop_state ();
355         } else {
356                 LexerError (_ ("string expected after \\include").c_str ());
357                 if (sval != SCM_UNDEFINED) {
358                         SCM err = scm_current_error_port ();
359                         scm_puts ("This value was found instead: ", err);
360                         scm_display (sval, err);
361                 }
362         }
363 }
364
365 <incl,version,sourcefilename>\"[^""]*   { // backup rule
366         error (_ ("end quote missing"));
367         exit (1);
368 }
369 <chords,notes,figures>{RESTNAME}        {
370         char const *s = YYText ();
371         yylval.scm = scm_from_locale_string (s);
372         return RESTNAME;
373 }
374 <chords,notes,figures>R         {
375         return MULTI_MEASURE_REST;
376 }
377 <INITIAL,chords,figures,lyrics,markup,notes>#   { //embedded scm
378         int n = 0;
379         Input hi = here_input();
380         hi.step_forward ();
381         SCM sval = ly_parse_scm (hi.start (), &n, hi,
382                 be_safe_global && is_main_input_, parser_);
383
384         if (sval == SCM_UNDEFINED)
385                 error_level_ = 1;
386
387         for (int i = 0; i < n; i++)
388         {
389                 yyinput ();
390         }
391         char_count_stack_.back () += n;
392
393         yylval.scm = sval;
394         return SCM_TOKEN;
395 }
396
397 <INITIAL,chords,figures,lyrics,markup,notes>\$  { //immediate scm
398         int n = 0;
399         Input hi = here_input();
400         hi.step_forward ();
401         SCM sval = ly_parse_scm (hi.start (), &n, hi,
402                 be_safe_global && is_main_input_, parser_);
403
404         for (int i = 0; i < n; i++)
405         {
406                 yyinput ();
407         }
408         char_count_stack_.back () += n;
409
410         sval = eval_scm (sval);
411                 
412         int token = scan_scm_id (sval);
413         if (!scm_is_eq (yylval.scm, SCM_UNSPECIFIED))
414           return token;
415 }
416
417 <INITIAL,notes,lyrics>{ 
418         \<\<    {
419                 return DOUBLE_ANGLE_OPEN;
420         }
421         \>\>    {
422                 return DOUBLE_ANGLE_CLOSE;
423         }
424 }
425
426 <INITIAL,notes>{
427         \<      {
428                 return ANGLE_OPEN;
429         }
430         \>      {
431                 return ANGLE_CLOSE;
432         }
433 }
434
435 <figures>{
436         _       {
437                 return FIGURE_SPACE;
438         }
439         \>              {
440                 return FIGURE_CLOSE;
441         }
442         \<      {
443                 return FIGURE_OPEN;
444         }
445 }
446
447 <notes,figures>{
448         {ALPHAWORD}     {
449                 return scan_bare_word (YYText ());
450         }
451
452         {NOTECOMMAND}   {
453                 return scan_escaped_word (YYText () + 1); 
454         }
455         {FRACTION}      {
456                 yylval.scm =  scan_fraction (YYText ());
457                 return FRACTION;
458         }
459         {UNSIGNED}/\/   | // backup rule
460         {UNSIGNED}              {
461                 yylval.scm = scm_c_read_string (YYText ());
462                 return UNSIGNED;
463         }
464         {E_UNSIGNED}    {
465                 yylval.i = String_convert::dec2int (string (YYText () +1));
466                 return E_UNSIGNED;
467         }
468 }
469
470 <quote,lyric_quote>{
471         \\{ESCAPED}     {
472                 *yylval.string += to_string (escaped_char (YYText ()[1]));
473         }
474         [^\\""]+        {
475                 *yylval.string += YYText ();
476         }
477         \"      {
478
479                 yy_pop_state ();
480
481                 /* yylval is union. Must remember STRING before setting SCM*/
482                 string *sp = yylval.string;
483                 yylval.scm = ly_string2scm (*sp);
484                 delete sp;
485                 return is_lyric_state () ? LYRICS_STRING : STRING;
486         }
487         .       {
488                 *yylval.string += YYText ();
489         }
490 }
491
492 <lyrics>{
493         \" {
494                 start_lyric_quote ();
495         }
496         {FRACTION}      {
497                 yylval.scm =  scan_fraction (YYText ());
498                 return FRACTION;
499         }
500         {UNSIGNED}/\/[^0-9] { // backup rule
501                 yylval.scm = scm_c_read_string (YYText ());
502                 return UNSIGNED;
503         }
504         {UNSIGNED}/\/   | // backup rule
505         {UNSIGNED}              {
506                 yylval.scm = scm_c_read_string (YYText ());
507                 return UNSIGNED;
508         }
509         {NOTECOMMAND}   {
510                 return scan_escaped_word (YYText () + 1);
511         }
512         {LYRICS} {
513                 /* ugr. This sux. */
514                 string s (YYText ()); 
515                 if (s == "__")
516                         return yylval.i = EXTENDER;
517                 if (s == "--")
518                         return yylval.i = HYPHEN;
519                 s = lyric_fudge (s);
520
521                 char c = s[s.length () - 1];
522                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
523                         here_input ().warning (
524                                 _ ("Brace found at end of lyric.  Did you forget a space?"));
525                 yylval.scm = ly_string2scm (s);
526
527
528                 return LYRICS_STRING;
529         }
530         . {
531                 return YYText ()[0];
532         }
533 }
534 <chords>{
535         {ALPHAWORD}     {
536                 return scan_bare_word (YYText ());
537         }
538         {NOTECOMMAND}   {
539                 return scan_escaped_word (YYText () + 1);
540         }
541         {FRACTION}      {
542                 yylval.scm =  scan_fraction (YYText ());
543                 return FRACTION;
544         }
545         {UNSIGNED}/\/[^0-9] { // backup rule
546                 yylval.scm = scm_c_read_string (YYText ());
547                 return UNSIGNED;
548         }
549         {UNSIGNED}/\/   | // backup rule
550         {UNSIGNED}              {
551                 yylval.scm = scm_c_read_string (YYText ());
552                 return UNSIGNED;
553         }
554         -  {
555                 return CHORD_MINUS;
556         }
557         :  {
558                 return CHORD_COLON;
559         }
560         \/\+ {
561                 return CHORD_BASS;
562         }
563         \/  {
564                 return CHORD_SLASH;
565         }
566         \^  {
567                 return CHORD_CARET;
568         }
569         . {
570                 return YYText ()[0];
571         }
572 }
573
574
575 <markup>{
576         \\score {
577                 return SCORE;
578         }
579         {MARKUPCOMMAND} {
580                 string str (YYText () + 1);
581
582                 int token_type = MARKUP_FUNCTION;
583                 SCM s = lookup_markup_command (str);
584
585                 // lookup-markup-command returns a pair with the car
586                 // being the function to call, and the cdr being the
587                 // call signature specified to define-markup-command,
588                 // a list of predicates.
589
590                 if (!scm_is_pair (s)) {
591                   // If lookup-markup-command was not successful, we
592                   // try lookup-markup-list-command instead.
593                   // If this fails as well, we just scan and return
594                   // the escaped word.
595                   s = lookup_markup_list_command (str);
596                   if (scm_is_pair (s))
597                     token_type = MARKUP_LIST_FUNCTION;
598                   else
599                     return scan_escaped_word (str);
600                 }
601
602                 // If the list of predicates is, say,
603                 // (number? number? markup?), then tokens
604                 // EXPECT_MARKUP EXPECT_SCM EXPECT_SCM EXPECT_NO_MORE_ARGS
605                 // will be generated.  Note that we have to push them
606                 // in reverse order, so the first token pushed in the
607                 // loop will be EXPECT_NO_MORE_ARGS.
608
609                 yylval.scm = scm_car(s);
610
611                 // yylval now contains the function to call as token
612                 // value (for token type MARKUP_FUNCTION or
613                 // MARKUP_LIST_FUNCTION).
614
615                 push_extra_token(EXPECT_NO_MORE_ARGS);
616                 s = scm_cdr(s);
617                 for (; scm_is_pair(s); s = scm_cdr(s)) {
618                   SCM predicate = scm_car(s);
619
620                   if (predicate == ly_lily_module_constant ("markup-list?"))
621                     push_extra_token(EXPECT_MARKUP_LIST);
622                   else if (predicate == ly_lily_module_constant ("markup?"))
623                     push_extra_token(EXPECT_MARKUP);
624                   else
625                     push_extra_token(EXPECT_SCM, predicate);
626                 }
627                 return token_type;
628         }
629         [{}]    {
630                 return YYText ()[0];
631         }
632         [^$#{}\"\\ \t\n\r\f]+ {
633                 string s (YYText ()); 
634
635                 char c = s[s.length () - 1];
636                 /* brace open is for not confusing dumb tools.  */
637                 if (c == '{' ||  c == '}')
638                         here_input ().warning (
639                                 _ ("Brace found at end of markup.  Did you forget a space?"));
640                 yylval.scm = ly_string2scm (s);
641
642
643                 return STRING;
644         }
645         .  {
646                 return YYText()[0];
647         }
648 }
649
650 <longcomment><<EOF>> {
651                 LexerError (_ ("EOF found inside a comment").c_str ());
652                 is_main_input_ = false; // should be safe , can't have \include in --safe.
653                 if (!close_input ())
654                   yyterminate (); // can't move this, since it actually rets a YY_NULL
655         }
656
657 <<EOF>> { if (is_main_input_)
658         {
659                 /* 2 = init.ly + current file.
660                    > because we're before closing, but is_main_input_ should
661                    reflect after.
662                 */ 
663                 is_main_input_ = include_stack_.size () > 2;
664                 if (!close_input ())
665                 /* Returns YY_NULL */
666                         yyterminate ();
667         }
668         else if (!close_input ())
669                 /* Returns YY_NULL */
670                 yyterminate ();
671 }
672
673 <INITIAL>{
674         {DASHED_WORD}   {
675                 return scan_bare_word (YYText ());
676         }
677         {DASHED_KEY_WORD}       {
678                 return scan_escaped_word (YYText () + 1);
679         }
680 }
681
682 -{UNSIGNED}     | // backup rule
683 {REAL}          {
684         yylval.scm = scm_c_read_string (YYText ());
685         return REAL;
686 }
687 -\.     { // backup rule
688         yylval.scm = scm_from_double (0.0);
689         return REAL;
690 }
691
692 {UNSIGNED}      {
693         yylval.scm = scm_c_read_string (YYText ());
694         return UNSIGNED;
695 }
696
697
698 [{}]    {
699
700         return YYText ()[0];
701 }
702 [*:=]           {
703         char c = YYText ()[0];
704
705         return c;
706 }
707
708 <INITIAL,notes,figures>.        {
709         return YYText ()[0];
710 }
711
712 <INITIAL,lyrics,notes,figures>\\. {
713     char c = YYText ()[1];
714
715     switch (c) {
716     case '>':
717         return E_ANGLE_CLOSE;
718     case '<':
719         return E_ANGLE_OPEN;
720     case '!':
721         return E_EXCLAMATION;
722     case '(':
723         return E_OPEN;
724     case ')':
725         return E_CLOSE;
726     case '[':
727         return E_BRACKET_OPEN;
728     case '+':
729         return E_PLUS;
730     case ']':
731         return E_BRACKET_CLOSE;
732     case '~':
733         return E_TILDE;
734     case '\\':
735         return E_BACKSLASH;
736
737     default:
738         return E_CHAR;
739     }
740 }
741
742 <*>.            {
743         string msg = _f ("invalid character: `%c'", YYText ()[0]);
744         LexerError (msg.c_str ());
745         return YYText ()[0];
746 }
747
748 %%
749
750 /* Make the lexer generate a token of the given type as the next token. 
751  TODO: make it possible to define a value for the token as well */
752 void
753 Lily_lexer::push_extra_token (int token_type, SCM scm)
754 {
755         if (scm_is_null (extra_tokens_))
756         {
757                 if (YY_START != extratoken)
758                         hidden_state_ = YY_START;
759                 yy_push_state (extratoken);
760         }
761         extra_tokens_ = scm_acons (scm_from_int (token_type), scm, extra_tokens_);
762 }
763
764 void
765 Lily_lexer::push_chord_state (SCM tab)
766 {
767         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
768         yy_push_state (chords);
769 }
770
771 void
772 Lily_lexer::push_figuredbass_state ()
773 {
774         yy_push_state (figures);
775 }
776
777 void
778 Lily_lexer::push_initial_state ()
779 {
780         yy_push_state (INITIAL);
781 }
782
783 void
784 Lily_lexer::push_lyric_state ()
785 {
786         yy_push_state (lyrics);
787 }
788
789 void
790 Lily_lexer::push_markup_state ()
791 {
792         yy_push_state (markup);
793 }
794
795 void
796 Lily_lexer::push_note_state (SCM tab)
797 {
798         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
799         yy_push_state (notes);
800 }
801
802 void
803 Lily_lexer::pop_state ()
804 {
805         if (YYSTATE == notes || YYSTATE == chords)
806                 pitchname_tab_stack_ = scm_cdr (pitchname_tab_stack_);
807
808         yy_pop_state ();
809 }
810
811 int
812 Lily_lexer::identifier_type (SCM sid)
813 {
814         int k = try_special_identifiers (&yylval.scm , sid);
815         return k >= 0  ? k : SCM_IDENTIFIER;
816 }
817
818
819 int
820 Lily_lexer::scan_escaped_word (string str)
821 {
822         // use more SCM for this.
823
824 //      SCM sym = ly_symbol2scm (str.c_str ());
825
826         int i = lookup_keyword (str);
827         if (i == MARKUP && is_lyric_state ())
828                 return LYRIC_MARKUP;
829         if (i != -1)
830                 return i;
831
832         SCM sid = lookup_identifier (str);
833         if (sid != SCM_UNDEFINED)
834                 return scan_scm_id (sid);
835
836         string msg (_f ("unknown escaped string: `\\%s'", str));        
837         LexerError (msg.c_str ());
838
839         yylval.scm = ly_string2scm (str);
840
841         return STRING;
842 }
843
844 int
845 Lily_lexer::scan_scm_id (SCM sid)
846 {
847         if (is_music_function (sid))
848         {
849                 int funtype = SCM_FUNCTION;
850
851                 yylval.scm = get_music_function_transform (sid);
852
853                 SCM s = scm_object_property (yylval.scm, ly_symbol2scm ("music-function-signature"));
854                 SCM cs = scm_car (s);
855
856                 if (scm_is_pair (cs))
857                 {
858                         cs = SCM_CAR (cs);
859                 }
860
861                 if (scm_is_eq (cs, ly_lily_module_constant ("ly:music?")))
862                         funtype = MUSIC_FUNCTION;
863                 else if (scm_is_eq (cs, ly_lily_module_constant ("ly:event?")))
864                         funtype = EVENT_FUNCTION;
865                 else if (ly_is_procedure (cs))
866                         funtype = SCM_FUNCTION;
867                 else programming_error ("Bad syntax function predicate");
868
869                 push_extra_token (EXPECT_NO_MORE_ARGS);
870                 for (s = scm_cdr (s); scm_is_pair (s); s = scm_cdr (s))
871                 {
872                         SCM optional = SCM_UNDEFINED;
873                         cs = scm_car (s);
874
875                         if (scm_is_pair (cs))
876                         {
877                                 optional = SCM_CDR (cs);
878                                 cs = SCM_CAR (cs);
879                         }
880                         
881                         if (cs == Pitch_type_p_proc)
882                                 push_extra_token (EXPECT_PITCH);
883                         else if (cs == Duration_type_p_proc)
884                                 push_extra_token (EXPECT_DURATION);
885                         else if (ly_is_procedure (cs))
886                                 push_extra_token (EXPECT_SCM, cs);
887                         else
888                         {
889                                 programming_error ("Function parameter without type-checking predicate");
890                                 continue;
891                         }
892                         if (!scm_is_eq (optional, SCM_UNDEFINED))
893                                 push_extra_token (EXPECT_OPTIONAL, optional);
894                 }
895                 return funtype;
896         }
897         yylval.scm = sid;
898         return identifier_type (sid);
899 }
900
901 int
902 Lily_lexer::scan_bare_word (string str)
903 {
904         SCM sym = ly_symbol2scm (str.c_str ());
905         if ((YYSTATE == notes) || (YYSTATE == chords)) {
906                 SCM handle = SCM_BOOL_F;
907                 if (scm_is_pair (pitchname_tab_stack_))
908                         handle = scm_hashq_get_handle (scm_car (pitchname_tab_stack_), sym);
909                 
910                 if (scm_is_pair (handle)) {
911                         yylval.scm = scm_cdr (handle);
912                         if (unsmob_pitch (yylval.scm)) 
913                             return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
914                         else if (scm_is_symbol (yylval.scm))
915                             return DRUM_PITCH;
916                 }
917                 else if ((YYSTATE == chords)
918                         && (handle = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
919                 {
920                     yylval.scm = scm_cdr (handle);
921                     return CHORD_MODIFIER;
922                 }
923                 if ((chord_repetition_.repetition_symbol_ != SCM_EOL)
924                     && to_boolean (scm_equal_p (chord_repetition_.repetition_symbol_, sym)))
925                         return CHORD_REPETITION;
926         }
927
928         yylval.scm = ly_string2scm (str);
929         return STRING;
930 }
931
932 int
933 Lily_lexer::get_state () const
934 {
935         if (YY_START == extratoken)
936                 return hidden_state_;
937         else
938                 return YY_START;
939 }
940
941 bool
942 Lily_lexer::is_note_state () const
943 {
944         return get_state () == notes;
945 }
946
947 bool
948 Lily_lexer::is_chord_state () const
949 {
950         return get_state () == chords;
951 }
952
953 bool
954 Lily_lexer::is_lyric_state () const
955 {
956         return get_state () == lyrics;
957 }
958
959 bool
960 Lily_lexer::is_figure_state () const
961 {
962         return get_state () == figures;
963 }
964
965 SCM
966 Lily_lexer::eval_scm (SCM readerdata)
967 {
968         SCM sval = SCM_UNDEFINED;
969
970         if (!SCM_UNBNDP (readerdata))
971         {
972                 sval = ly_eval_scm (scm_car (readerdata),
973                                     *unsmob_input (scm_cdr (readerdata)),
974                                     be_safe_global && is_main_input_,
975                                     parser_);
976         }
977
978         if (SCM_UNBNDP (sval))
979         {
980                 error_level_ = 1;
981                 return SCM_UNSPECIFIED;
982         }
983         return sval;
984 }
985
986
987
988 /*
989  urg, belong to string (_convert)
990  and should be generalised 
991  */
992 void
993 strip_leading_white (string&s)
994 {
995         ssize i = 0;
996         for (;  i < s.length (); i++)
997                 if (!isspace (s[i]))
998                         break;
999
1000         s = s.substr (i);
1001 }
1002
1003 void
1004 strip_trailing_white (string&s)
1005 {
1006         ssize i = s.length ();  
1007         while (i--) 
1008                 if (!isspace (s[i]))
1009                         break;
1010
1011         s = s.substr (0, i + 1);
1012 }
1013
1014
1015
1016 Lilypond_version oldest_version ("2.7.38");
1017
1018
1019 bool
1020 is_valid_version (string s)
1021 {
1022   Lilypond_version current ( MAJOR_VERSION "." MINOR_VERSION "." PATCH_LEVEL );
1023   Lilypond_version ver (s);
1024   if (int (ver) < oldest_version)
1025         {       
1026                 non_fatal_error (_f ("file too old: %s (oldest supported: %s)", ver.to_string (), oldest_version.to_string ()));
1027                 non_fatal_error (_ ("consider updating the input with the convert-ly script"));
1028                 return false;
1029         }
1030
1031   if (ver > current)
1032         {
1033                 non_fatal_error (_f ("program too old: %s (file requires: %s)",  current.to_string (), ver.to_string ()));
1034                 return false;
1035         }
1036   return true;
1037 }
1038         
1039
1040 /*
1041   substitute _ and \,
1042 */
1043 string
1044 lyric_fudge (string s)
1045 {
1046   char *chars = string_copy (s);
1047
1048   for (char *p = chars; *p ; p++)
1049     {
1050       if (*p == '_' && (p == chars || *(p-1) != '\\'))
1051         *p = ' ';
1052     }
1053   
1054   s = string (chars);
1055   delete[] chars;
1056
1057   ssize i = 0;  
1058   if ((i = s.find ("\\,")) != NPOS)   // change "\," to TeX's "\c "
1059     {
1060       * (((char*)s.c_str ()) + i + 1) = 'c';
1061       s = s.substr (0, i + 2) + " " + s.substr (i - 2);
1062     }
1063
1064   return s;
1065 }
1066
1067 /*
1068 Convert "NUM/DEN" into a '(NUM . DEN) cons.
1069 */
1070 SCM
1071 scan_fraction (string frac)
1072 {
1073         ssize i = frac.find ('/');
1074         string left = frac.substr (0, i);
1075         string right = frac.substr (i + 1, (frac.length () - i + 1));
1076
1077         int n = String_convert::dec2int (left);
1078         int d = String_convert::dec2int (right);
1079         return scm_cons (scm_from_int (n), scm_from_int (d));
1080 }
1081
1082 SCM
1083 lookup_markup_command (string s)
1084 {
1085         SCM proc = ly_lily_module_constant ("lookup-markup-command");
1086         return scm_call_1 (proc, ly_string2scm (s));
1087 }
1088
1089 SCM
1090 lookup_markup_list_command (string s)
1091 {
1092         SCM proc = ly_lily_module_constant ("lookup-markup-list-command");
1093         return scm_call_1 (proc, ly_string2scm (s));
1094 }
1095
1096 /* Shut up lexer warnings.  */
1097 #if YY_STACK_USED
1098
1099 static void
1100 yy_push_state (int)
1101 {
1102 }
1103
1104 static void
1105 yy_pop_state ()
1106 {
1107 }
1108
1109 static int
1110 yy_top_state ()
1111 {
1112   return 0;
1113 }
1114
1115 static void
1116 silence_lexer_warnings ()
1117 {
1118    (void) yy_start_stack_ptr;
1119    (void) yy_start_stack_depth;
1120    (void) yy_start_stack;
1121    (void) yy_push_state;
1122    (void) yy_pop_state;
1123    (void) yy_top_state;
1124    (void) silence_lexer_warnings;
1125 }
1126 #endif