]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
Merge branch 'master' into lilypond/translation
[lilypond.git] / lily / lexer.ll
1 %{ // -*- mode: c++; c-file-style: "linux" -*-
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 /* Mode and indentation are at best a rough approximation based on TAB
23  * formatting (reasonable for compatibility with unspecific editor
24  * modes as Flex modes are hard to find) and need manual correction
25  * frequently.  Without a reasonably dependable way of formatting a
26  * Flex file sensibly, there is little point in trying to fix the
27  * inconsistent state of indentation.
28  */
29
30 /*
31   backup rules
32
33   after making a change to the lexer rules, run 
34       flex -b <this lexer file>
35   and make sure that 
36       lex.backup
37   contains no backup states, but only the reminder
38       Compressed tables always back up.
39  (don-t forget to rm lex.yy.cc :-)
40  */
41
42
43
44 #include <cstdio>
45 #include <cctype>
46 #include <cerrno>
47
48 /* Flex >= 2.5.29 fix; FlexLexer.h's multiple include bracing breaks
49    when building the actual lexer.  */
50
51 #define LEXER_CC
52
53 #include <iostream>
54 using namespace std;
55
56 #include "context-def.hh"
57 #include "duration.hh"
58 #include "international.hh"
59 #include "interval.hh"
60 #include "lily-guile.hh"
61 #include "lily-lexer.hh"
62 #include "lily-parser.hh"
63 #include "lilypond-version.hh"
64 #include "main.hh"
65 #include "music.hh"
66 #include "music-function.hh"
67 #include "parse-scm.hh"
68 #include "parser.hh"
69 #include "pitch.hh"
70 #include "source-file.hh"
71 #include "std-string.hh"
72 #include "string-convert.hh"
73 #include "version.hh"
74 #include "warn.hh"
75
76 /*
77 RH 7 fix (?)
78 */
79 #define isatty HORRIBLEKLUDGE
80
81 void strip_trailing_white (string&);
82 void strip_leading_white (string&);
83 string lyric_fudge (string s);
84 SCM lookup_markup_command (string s);
85 SCM lookup_markup_list_command (string s);
86 bool is_valid_version (string s);
87
88
89 #define start_quote()   \
90         yy_push_state (quote);\
91         yylval.string = new string
92
93 #define start_lyric_quote()     \
94         yy_push_state (lyric_quote);\
95         yylval.string = new string
96
97 #define yylval (*lexval_)
98
99 #define yylloc (*lexloc_)
100
101 #define YY_USER_ACTION  add_lexed_char (YYLeng ());
102
103
104 SCM scan_fraction (string);
105 SCM (* scm_parse_error_handler) (void *);
106
107
108
109 %}
110
111 %option c++
112 %option noyywrap
113 %option nodefault
114 %option debug
115 %option yyclass="Lily_lexer"
116 %option stack
117 %option never-interactive 
118 %option warn
119
120 %x extratoken
121 %x chords
122 %x figures
123 %x incl
124 %x lyrics
125 %x lyric_quote
126 %x longcomment
127 %x markup
128 %x notes
129 %x quote
130 %x sourcefileline
131 %x sourcefilename
132 %x version
133
134 /* The strategy concerning multibyte characters is to accept them but
135  * call YYText_utf8 for patterns that might contain them, in order to
136  * get a single code path responsible for flagging non-UTF-8 input:
137  * Patterns for accepting only valid UTF-8 without backing up are
138  * really hard to do and complex, and if nice error messages are
139  * wanted, one would need patterns catching the invalid input as well.
140  *
141  * Since editors and operating environments don't necessarily behave
142  * reasonably in the presence of mixed encodings, we flag encoding
143  * errors also in identifiers, comments, and strings where it would be
144  * conceivable to just transparently work with the byte string.  But
145  * the whole point of caring about UTF-8 in here at all is too avoid
146  * stranger errors later when input passes into backends or log files
147  * or console output or error messages.
148  */
149
150 A               [a-zA-Z\200-\377]
151 AA              {A}|_
152 N               [0-9]
153 AN              {AA}|{N}
154 ANY_CHAR        (.|\n)
155 PUNCT           [?!:'`]
156 ACCENT          \\[`'"^]
157 SPECIAL_CHAR            [&@]
158 NATIONAL        [\001-\006\021-\027\031\036]
159 TEX             {AA}|-|{PUNCT}|{ACCENT}|{NATIONAL}|{SPECIAL_CHAR}
160 DASHED_WORD             {A}({AN}|-)*
161 DASHED_KEY_WORD         \\{DASHED_WORD}
162
163
164
165 ALPHAWORD       {A}+
166 UNSIGNED        {N}+
167 E_UNSIGNED      \\{N}+
168 FRACTION        {N}+\/{N}+
169 INT             -?{UNSIGNED}
170 REAL            ({INT}\.{N}*)|(-?\.{N}+)
171 WHITE           [ \n\t\f\r]
172 HORIZONTALWHITE         [ \t]
173 BLACK           [^ \n\t\f\r]
174 RESTNAME        [rs]
175 NOTECOMMAND     \\{A}+
176 MARKUPCOMMAND   \\({A}|[-_])+
177 LYRICS          ({AA}|{TEX})[^0-9 \t\n\r\f]*
178 ESCAPED         [nt\\'"]
179 EXTENDER        __
180 HYPHEN          --
181 BOM_UTF8        \357\273\277
182
183 %%
184
185
186 <*>\r           {
187         // swallow and ignore carriage returns
188 }
189
190 <extratoken>{ANY_CHAR}  {
191   /* Generate a token without swallowing anything */
192
193   /* First unswallow the eaten character */
194   add_lexed_char (-YYLeng ());
195   yyless (0);
196
197   /* produce requested token */
198   int type = scm_to_int (scm_caar (extra_tokens_));
199   yylval.scm = scm_cdar (extra_tokens_);
200   extra_tokens_ = scm_cdr (extra_tokens_);
201   if (scm_is_null (extra_tokens_))
202     yy_pop_state ();
203
204   return type;
205 }
206
207 <extratoken><<EOF>>     {
208   /* Generate a token without swallowing anything */
209
210   /* produce requested token */
211   int type = scm_to_int (scm_caar (extra_tokens_));
212   yylval.scm = scm_cdar (extra_tokens_);
213   extra_tokens_ = scm_cdr (extra_tokens_);
214   if (scm_is_null (extra_tokens_))
215     yy_pop_state ();
216
217   return type;
218 }
219
220    /* Use the trailing context feature. Otherwise, the BOM will not be
221       found if the file starts with an identifier definition. */
222 <INITIAL,chords,lyrics,figures,notes>{BOM_UTF8}/.* {
223   if (this->lexloc_->line_number () != 1 || this->lexloc_->column_number () != 0)
224     {
225       LexerWarning (_ ("stray UTF-8 BOM encountered").c_str ());
226       // exit (1);
227     }
228   debug_output (_ ("Skipping UTF-8 BOM"));
229 }
230
231 <INITIAL,chords,figures,incl,lyrics,markup,notes>{
232   "%{"  {
233         yy_push_state (longcomment);
234   }
235   %[^{\n\r][^\n\r]*[\n\r]       {
236           (void) YYText_utf8 ();
237   }
238   %[^{\n\r]     { // backup rule
239           (void) YYText_utf8 ();
240   }
241   %[\n\r]       {
242   }
243   %[^{\n\r][^\n\r]*     {
244           (void) YYText_utf8 ();
245   }
246   {WHITE}+      {
247
248   }
249 }
250
251 <INITIAL,notes,figures,chords,markup>{
252         \"              {
253                 start_quote ();
254         }
255 }
256
257 <INITIAL,chords,lyrics,notes,figures>\\version{WHITE}*  {
258         yy_push_state (version);
259 }
260 <INITIAL,chords,lyrics,notes,figures>\\sourcefilename{WHITE}*   {
261         yy_push_state (sourcefilename);
262 }
263 <INITIAL,chords,lyrics,notes,figures>\\sourcefileline{WHITE}*   {
264         yy_push_state (sourcefileline);
265 }
266 <version>\"[^"]*\"     { /* got the version number */
267         string s (YYText_utf8 () + 1);
268         s = s.substr (0, s.rfind ('\"'));
269
270         yy_pop_state ();
271
272         SCM top_scope = scm_car (scm_last_pair (scopes_));
273         scm_module_define (top_scope, ly_symbol2scm ("version-seen"), SCM_BOOL_T);
274
275         if (!is_valid_version (s))
276                 return INVALID;
277
278
279 }
280 <sourcefilename>\"[^"]*\"     {
281         string s (YYText_utf8 () + 1);
282         s = s.substr (0, s.rfind ('\"'));
283
284         yy_pop_state ();
285         this->here_input().get_source_file ()->name_ = s;
286         message (_f ("Renaming input to: `%s'", s.c_str ()));
287         progress_indication ("\n");
288         scm_module_define (scm_car (scopes_),
289                      ly_symbol2scm ("input-file-name"),
290                      ly_string2scm (s));
291
292 }
293
294 <sourcefileline>{INT}   {
295         int i;
296         sscanf (YYText (), "%d", &i);
297
298         yy_pop_state ();
299         this->here_input ().get_source_file ()->set_line (here_input ().start (), i);
300 }
301
302 <version>{ANY_CHAR}     {
303         LexerError (_ ("quoted string expected after \\version").c_str ());
304         yy_pop_state ();
305 }
306 <sourcefilename>{ANY_CHAR}      {
307         LexerError (_ ("quoted string expected after \\sourcefilename").c_str ());
308         yy_pop_state ();
309 }
310 <sourcefileline>{ANY_CHAR}      {
311         LexerError (_ ("integer expected after \\sourcefileline").c_str ());
312         yy_pop_state ();
313 }
314 <longcomment>{
315         [^\%]*          {
316                 (void) YYText_utf8 ();
317         }
318         \%*[^}%]*               {
319                 (void) YYText_utf8 ();
320         }
321         "%"+"}"         {
322                 yy_pop_state ();
323         }
324 }
325
326
327 <INITIAL,chords,lyrics,notes,figures>\\maininput           {
328         if (!is_main_input_)
329         {
330                 start_main_input ();
331                 is_main_input_ = true;
332         }
333         else
334                 error (_ ("\\maininput not allowed outside init files"));
335 }
336
337 <INITIAL,chords,lyrics,figures,notes>\\include           {
338         yy_push_state (incl);
339 }
340 <incl>\"[^""]*\"   { /* got the include file name */
341         string s (YYText_utf8 ()+1);
342         s = s.substr (0, s.rfind ('"'));
343
344         new_input (s, sources_);
345         yy_pop_state ();
346 }
347 <incl>\\{BLACK}*{WHITE}? { /* got the include identifier */
348         string s = YYText_utf8 () + 1;
349         strip_trailing_white (s);
350         if (s.length () && (s[s.length () - 1] == ';'))
351           s = s.substr (0, s.length () - 1);
352
353         SCM sid = lookup_identifier (s);
354         if (scm_is_string (sid)) {
355                 new_input (ly_scm2string (sid), sources_);
356                 yy_pop_state ();
357         } else {
358             string msg (_f ("wrong or undefined identifier: `%s'", s ));
359
360             LexerError (msg.c_str ());
361             SCM err = scm_current_error_port ();
362             scm_puts ("This value was found in the table: ", err);
363             scm_display (sid, err);
364           }
365 }
366 <incl>(\$|#) { // scm for the filename
367         int n = 0;
368         Input hi = here_input();
369         hi.step_forward ();
370         SCM sval = ly_parse_scm (hi.start (), &n, hi,
371                 be_safe_global && is_main_input_, parser_);
372         sval = eval_scm (sval);
373
374         for (int i = 0; i < n; i++)
375         {
376                 yyinput ();
377         }
378         char_count_stack_.back () += n;
379
380         if (scm_is_string (sval)) {
381                 new_input (ly_scm2string (sval), sources_);
382                 yy_pop_state ();
383         } else {
384                 LexerError (_ ("string expected after \\include").c_str ());
385                 if (sval != SCM_UNDEFINED) {
386                         SCM err = scm_current_error_port ();
387                         scm_puts ("This value was found instead: ", err);
388                         scm_display (sval, err);
389                 }
390         }
391 }
392
393 <incl,version,sourcefilename>\"[^""]*   { // backup rule
394         error (_ ("end quote missing"));
395         exit (1);
396 }
397 <chords,notes,figures>{RESTNAME}        {
398         char const *s = YYText ();
399         yylval.scm = scm_from_locale_string (s);
400         return RESTNAME;
401 }
402 <chords,notes,figures>R         {
403         return MULTI_MEASURE_REST;
404 }
405 <INITIAL,chords,figures,lyrics,markup,notes>#   { //embedded scm
406         int n = 0;
407         Input hi = here_input();
408         hi.step_forward ();
409         SCM sval = ly_parse_scm (hi.start (), &n, hi,
410                 be_safe_global && is_main_input_, parser_);
411
412         if (sval == SCM_UNDEFINED)
413                 error_level_ = 1;
414
415         for (int i = 0; i < n; i++)
416         {
417                 yyinput ();
418         }
419         char_count_stack_.back () += n;
420
421         yylval.scm = sval;
422         return SCM_TOKEN;
423 }
424
425 <INITIAL,chords,figures,lyrics,markup,notes>\$  { //immediate scm
426         int n = 0;
427         Input hi = here_input();
428         hi.step_forward ();
429         SCM sval = ly_parse_scm (hi.start (), &n, hi,
430                 be_safe_global && is_main_input_, parser_);
431
432         for (int i = 0; i < n; i++)
433         {
434                 yyinput ();
435         }
436         char_count_stack_.back () += n;
437
438         sval = eval_scm (sval);
439                 
440         int token = scan_scm_id (sval);
441         if (!scm_is_eq (yylval.scm, SCM_UNSPECIFIED))
442           return token;
443 }
444
445 <INITIAL,notes,lyrics>{ 
446         \<\<    {
447                 return DOUBLE_ANGLE_OPEN;
448         }
449         \>\>    {
450                 return DOUBLE_ANGLE_CLOSE;
451         }
452 }
453
454 <INITIAL,notes>{
455         \<      {
456                 return ANGLE_OPEN;
457         }
458         \>      {
459                 return ANGLE_CLOSE;
460         }
461 }
462
463 <figures>{
464         _       {
465                 return FIGURE_SPACE;
466         }
467         \>              {
468                 return FIGURE_CLOSE;
469         }
470         \<      {
471                 return FIGURE_OPEN;
472         }
473 }
474
475 <notes,figures>{
476         {ALPHAWORD}     {
477                 return scan_bare_word (YYText_utf8 ());
478         }
479
480         {NOTECOMMAND}   {
481                 return scan_escaped_word (YYText_utf8 () + 1); 
482         }
483         {FRACTION}      {
484                 yylval.scm =  scan_fraction (YYText ());
485                 return FRACTION;
486         }
487         {UNSIGNED}/\/   | // backup rule
488         {UNSIGNED}              {
489                 yylval.scm = scm_c_read_string (YYText ());
490                 return UNSIGNED;
491         }
492         {E_UNSIGNED}    {
493                 yylval.i = String_convert::dec2int (string (YYText () +1));
494                 return E_UNSIGNED;
495         }
496 }
497
498 <quote,lyric_quote>{
499         \\{ESCAPED}     {
500                 *yylval.string += to_string (escaped_char (YYText ()[1]));
501         }
502         [^\\""]+        {
503                 *yylval.string += YYText_utf8 ();
504         }
505         \"      {
506
507                 yy_pop_state ();
508
509                 /* yylval is union. Must remember STRING before setting SCM*/
510                 string *sp = yylval.string;
511                 yylval.scm = ly_string2scm (*sp);
512                 delete sp;
513                 return is_lyric_state () ? LYRICS_STRING : STRING;
514         }
515         \\      {
516                 *yylval.string += YYText ();
517         }
518 }
519
520 <lyrics>{
521         \" {
522                 start_lyric_quote ();
523         }
524         {FRACTION}      {
525                 yylval.scm =  scan_fraction (YYText ());
526                 return FRACTION;
527         }
528         {UNSIGNED}/\/[^0-9] { // backup rule
529                 yylval.scm = scm_c_read_string (YYText ());
530                 return UNSIGNED;
531         }
532         {UNSIGNED}/\/   | // backup rule
533         {UNSIGNED}              {
534                 yylval.scm = scm_c_read_string (YYText ());
535                 return UNSIGNED;
536         }
537         {NOTECOMMAND}   {
538                 return scan_escaped_word (YYText_utf8 () + 1);
539         }
540         {LYRICS} {
541                 /* ugr. This sux. */
542                 string s (YYText_utf8 ()); 
543                 if (s == "__")
544                         return yylval.i = EXTENDER;
545                 if (s == "--")
546                         return yylval.i = HYPHEN;
547                 s = lyric_fudge (s);
548
549                 char c = s[s.length () - 1];
550                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
551                         here_input ().warning (
552                                 _ ("Brace found at end of lyric.  Did you forget a space?"));
553                 yylval.scm = ly_string2scm (s);
554
555
556                 return LYRICS_STRING;
557         }
558         . {
559                 return YYText ()[0]; // LYRICS already catches all multibytes.
560         }
561 }
562 <chords>{
563         {ALPHAWORD}     {
564                 return scan_bare_word (YYText_utf8 ());
565         }
566         {NOTECOMMAND}   {
567                 return scan_escaped_word (YYText_utf8 () + 1);
568         }
569         {FRACTION}      {
570                 yylval.scm =  scan_fraction (YYText ());
571                 return FRACTION;
572         }
573         {UNSIGNED}/\/[^0-9] { // backup rule
574                 yylval.scm = scm_c_read_string (YYText ());
575                 return UNSIGNED;
576         }
577         {UNSIGNED}/\/   | // backup rule
578         {UNSIGNED}              {
579                 yylval.scm = scm_c_read_string (YYText ());
580                 return UNSIGNED;
581         }
582         -  {
583                 return CHORD_MINUS;
584         }
585         :  {
586                 return CHORD_COLON;
587         }
588         \/\+ {
589                 return CHORD_BASS;
590         }
591         \/  {
592                 return CHORD_SLASH;
593         }
594         \^  {
595                 return CHORD_CARET;
596         }
597         . {
598                 return YYText ()[0]; // ALPHAWORD catches all multibyte.
599         }
600 }
601
602
603 <markup>{
604         \\score {
605                 return SCORE;
606         }
607         {MARKUPCOMMAND} {
608                 string str (YYText_utf8 () + 1);
609
610                 int token_type = MARKUP_FUNCTION;
611                 SCM s = lookup_markup_command (str);
612
613                 // lookup-markup-command returns a pair with the car
614                 // being the function to call, and the cdr being the
615                 // call signature specified to define-markup-command,
616                 // a list of predicates.
617
618                 if (!scm_is_pair (s)) {
619                   // If lookup-markup-command was not successful, we
620                   // try lookup-markup-list-command instead.
621                   // If this fails as well, we just scan and return
622                   // the escaped word.
623                   s = lookup_markup_list_command (str);
624                   if (scm_is_pair (s))
625                     token_type = MARKUP_LIST_FUNCTION;
626                   else
627                     return scan_escaped_word (str);
628                 }
629
630                 // If the list of predicates is, say,
631                 // (number? number? markup?), then tokens
632                 // EXPECT_MARKUP EXPECT_SCM EXPECT_SCM EXPECT_NO_MORE_ARGS
633                 // will be generated.  Note that we have to push them
634                 // in reverse order, so the first token pushed in the
635                 // loop will be EXPECT_NO_MORE_ARGS.
636
637                 yylval.scm = scm_car(s);
638
639                 // yylval now contains the function to call as token
640                 // value (for token type MARKUP_FUNCTION or
641                 // MARKUP_LIST_FUNCTION).
642
643                 push_extra_token(EXPECT_NO_MORE_ARGS);
644                 s = scm_cdr(s);
645                 for (; scm_is_pair(s); s = scm_cdr(s)) {
646                   SCM predicate = scm_car(s);
647
648                   if (predicate == ly_lily_module_constant ("markup-list?"))
649                     push_extra_token(EXPECT_MARKUP_LIST);
650                   else if (predicate == ly_lily_module_constant ("markup?"))
651                     push_extra_token(EXPECT_MARKUP);
652                   else
653                     push_extra_token(EXPECT_SCM, predicate);
654                 }
655                 return token_type;
656         }
657         [{}]    {
658                 return YYText ()[0];
659         }
660         [^$#{}\"\\ \t\n\r\f]+ {
661                 string s (YYText_utf8 ()); 
662
663                 char c = s[s.length () - 1];
664                 /* brace open is for not confusing dumb tools.  */
665                 if (c == '{' ||  c == '}')
666                         here_input ().warning (
667                                 _ ("Brace found at end of markup.  Did you forget a space?"));
668                 yylval.scm = ly_string2scm (s);
669
670
671                 return STRING;
672         }
673         .  {
674                 return YYText()[0];  // Above is catchall for multibyte
675         }
676 }
677
678 <longcomment><<EOF>> {
679                 LexerError (_ ("EOF found inside a comment").c_str ());
680                 is_main_input_ = false; // should be safe , can't have \include in --safe.
681                 if (!close_input ())
682                   yyterminate (); // can't move this, since it actually rets a YY_NULL
683         }
684
685 <<EOF>> { if (is_main_input_)
686         {
687                 /* 2 = init.ly + current file.
688                    > because we're before closing, but is_main_input_ should
689                    reflect after.
690                 */ 
691                 is_main_input_ = include_stack_.size () > 2;
692                 if (!close_input ())
693                 /* Returns YY_NULL */
694                         yyterminate ();
695         }
696         else if (!close_input ())
697                 /* Returns YY_NULL */
698                 yyterminate ();
699 }
700
701 <INITIAL>{
702         {DASHED_WORD}   {
703                 return scan_bare_word (YYText_utf8 ());
704         }
705         {DASHED_KEY_WORD}       {
706                 return scan_escaped_word (YYText_utf8 () + 1);
707         }
708 }
709
710 -{UNSIGNED}     | // backup rule
711 {REAL}          {
712         yylval.scm = scm_c_read_string (YYText ());
713         return REAL;
714 }
715 -\.     { // backup rule
716         yylval.scm = scm_from_double (0.0);
717         return REAL;
718 }
719
720 {UNSIGNED}      {
721         yylval.scm = scm_c_read_string (YYText ());
722         return UNSIGNED;
723 }
724
725
726 [{}]    {
727
728         return YYText ()[0];
729 }
730 [*:=]           {
731         char c = YYText ()[0];
732
733         return c;
734 }
735
736 <INITIAL,notes,figures>.        {
737         return YYText ()[0];
738 }
739
740 <INITIAL,lyrics,notes,figures>\\. {
741     char c = YYText ()[1];
742
743     switch (c) {
744     case '>':
745         return E_ANGLE_CLOSE;
746     case '<':
747         return E_ANGLE_OPEN;
748     case '!':
749         return E_EXCLAMATION;
750     case '(':
751         return E_OPEN;
752     case ')':
753         return E_CLOSE;
754     case '[':
755         return E_BRACKET_OPEN;
756     case '+':
757         return E_PLUS;
758     case ']':
759         return E_BRACKET_CLOSE;
760     case '~':
761         return E_TILDE;
762     case '\\':
763         return E_BACKSLASH;
764
765     default:
766         return E_CHAR;
767     }
768 }
769
770 <*>.[\200-\277]*        {
771         string msg = _f ("invalid character: `%s'", YYText_utf8 ());
772         LexerError (msg.c_str ());
773         return '%';  // Better not return half a utf8 character.
774 }
775
776 %%
777
778 /* Make the lexer generate a token of the given type as the next token. 
779  TODO: make it possible to define a value for the token as well */
780 void
781 Lily_lexer::push_extra_token (int token_type, SCM scm)
782 {
783         if (scm_is_null (extra_tokens_))
784         {
785                 if (YY_START != extratoken)
786                         hidden_state_ = YY_START;
787                 yy_push_state (extratoken);
788         }
789         extra_tokens_ = scm_acons (scm_from_int (token_type), scm, extra_tokens_);
790 }
791
792 void
793 Lily_lexer::push_chord_state (SCM tab)
794 {
795         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
796         yy_push_state (chords);
797 }
798
799 void
800 Lily_lexer::push_figuredbass_state ()
801 {
802         yy_push_state (figures);
803 }
804
805 void
806 Lily_lexer::push_initial_state ()
807 {
808         yy_push_state (INITIAL);
809 }
810
811 void
812 Lily_lexer::push_lyric_state ()
813 {
814         yy_push_state (lyrics);
815 }
816
817 void
818 Lily_lexer::push_markup_state ()
819 {
820         yy_push_state (markup);
821 }
822
823 void
824 Lily_lexer::push_note_state (SCM tab)
825 {
826         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
827         yy_push_state (notes);
828 }
829
830 void
831 Lily_lexer::pop_state ()
832 {
833         if (YYSTATE == notes || YYSTATE == chords)
834                 pitchname_tab_stack_ = scm_cdr (pitchname_tab_stack_);
835
836         yy_pop_state ();
837 }
838
839 int
840 Lily_lexer::identifier_type (SCM sid)
841 {
842         int k = try_special_identifiers (&yylval.scm , sid);
843         return k >= 0  ? k : SCM_IDENTIFIER;
844 }
845
846
847 int
848 Lily_lexer::scan_escaped_word (string str)
849 {
850         // use more SCM for this.
851
852 //      SCM sym = ly_symbol2scm (str.c_str ());
853
854         int i = lookup_keyword (str);
855         if (i == MARKUP && is_lyric_state ())
856                 return LYRIC_MARKUP;
857         if (i != -1)
858                 return i;
859
860         SCM sid = lookup_identifier (str);
861         if (sid != SCM_UNDEFINED)
862                 return scan_scm_id (sid);
863
864         string msg (_f ("unknown escaped string: `\\%s'", str));        
865         LexerError (msg.c_str ());
866
867         yylval.scm = ly_string2scm (str);
868
869         return STRING;
870 }
871
872 int
873 Lily_lexer::scan_scm_id (SCM sid)
874 {
875         if (is_music_function (sid))
876         {
877                 int funtype = SCM_FUNCTION;
878
879                 yylval.scm = get_music_function_transform (sid);
880
881                 SCM s = scm_object_property (yylval.scm, ly_symbol2scm ("music-function-signature"));
882                 SCM cs = scm_car (s);
883
884                 if (scm_is_pair (cs))
885                 {
886                         cs = SCM_CAR (cs);
887                 }
888
889                 if (scm_is_eq (cs, ly_lily_module_constant ("ly:music?")))
890                         funtype = MUSIC_FUNCTION;
891                 else if (scm_is_eq (cs, ly_lily_module_constant ("ly:event?")))
892                         funtype = EVENT_FUNCTION;
893                 else if (ly_is_procedure (cs))
894                         funtype = SCM_FUNCTION;
895                 else programming_error ("Bad syntax function predicate");
896
897                 push_extra_token (EXPECT_NO_MORE_ARGS);
898                 for (s = scm_cdr (s); scm_is_pair (s); s = scm_cdr (s))
899                 {
900                         SCM optional = SCM_UNDEFINED;
901                         cs = scm_car (s);
902
903                         if (scm_is_pair (cs))
904                         {
905                                 optional = SCM_CDR (cs);
906                                 cs = SCM_CAR (cs);
907                         }
908                         
909                         if (cs == Pitch_type_p_proc)
910                                 push_extra_token (EXPECT_PITCH);
911                         else if (cs == Duration_type_p_proc)
912                                 push_extra_token (EXPECT_DURATION);
913                         else if (ly_is_procedure (cs))
914                                 push_extra_token (EXPECT_SCM, cs);
915                         else
916                         {
917                                 programming_error ("Function parameter without type-checking predicate");
918                                 continue;
919                         }
920                         if (!scm_is_eq (optional, SCM_UNDEFINED))
921                                 push_extra_token (EXPECT_OPTIONAL, optional);
922                 }
923                 return funtype;
924         }
925         yylval.scm = sid;
926         return identifier_type (sid);
927 }
928
929 int
930 Lily_lexer::scan_bare_word (string str)
931 {
932         SCM sym = ly_symbol2scm (str.c_str ());
933         if ((YYSTATE == notes) || (YYSTATE == chords)) {
934                 SCM handle = SCM_BOOL_F;
935                 if (scm_is_pair (pitchname_tab_stack_))
936                         handle = scm_hashq_get_handle (scm_car (pitchname_tab_stack_), sym);
937                 
938                 if (scm_is_pair (handle)) {
939                         yylval.scm = scm_cdr (handle);
940                         if (unsmob_pitch (yylval.scm)) 
941                             return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
942                         else if (scm_is_symbol (yylval.scm))
943                             return DRUM_PITCH;
944                 }
945                 else if ((YYSTATE == chords)
946                         && (handle = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
947                 {
948                     yylval.scm = scm_cdr (handle);
949                     return CHORD_MODIFIER;
950                 }
951                 if ((chord_repetition_.repetition_symbol_ != SCM_EOL)
952                     && to_boolean (scm_equal_p (chord_repetition_.repetition_symbol_, sym)))
953                         return CHORD_REPETITION;
954         }
955
956         yylval.scm = ly_string2scm (str);
957         return STRING;
958 }
959
960 int
961 Lily_lexer::get_state () const
962 {
963         if (YY_START == extratoken)
964                 return hidden_state_;
965         else
966                 return YY_START;
967 }
968
969 bool
970 Lily_lexer::is_note_state () const
971 {
972         return get_state () == notes;
973 }
974
975 bool
976 Lily_lexer::is_chord_state () const
977 {
978         return get_state () == chords;
979 }
980
981 bool
982 Lily_lexer::is_lyric_state () const
983 {
984         return get_state () == lyrics;
985 }
986
987 bool
988 Lily_lexer::is_figure_state () const
989 {
990         return get_state () == figures;
991 }
992
993 SCM
994 Lily_lexer::eval_scm (SCM readerdata)
995 {
996         SCM sval = SCM_UNDEFINED;
997
998         if (!SCM_UNBNDP (readerdata))
999         {
1000                 sval = ly_eval_scm (scm_car (readerdata),
1001                                     *unsmob_input (scm_cdr (readerdata)),
1002                                     be_safe_global && is_main_input_,
1003                                     parser_);
1004         }
1005
1006         if (SCM_UNBNDP (sval))
1007         {
1008                 error_level_ = 1;
1009                 return SCM_UNSPECIFIED;
1010         }
1011         return sval;
1012 }
1013
1014 /* Check for valid UTF-8 that has no overlong or surrogate codes and
1015    is in the range 0-0x10ffff */
1016
1017 const char *
1018 Lily_lexer::YYText_utf8 ()
1019 {
1020         const char * const p =  YYText ();
1021         for (int i=0; p[i];) {
1022                 if ((p[i] & 0xff) < 0x80) {
1023                         ++i;
1024                         continue;
1025                 }
1026                 int oldi = i; // start of character
1027                 int more = 0; // # of followup bytes, 0 if bad
1028                 switch (p[i++] & 0xff) {
1029                         // 0xc0 and 0xc1 are overlong prefixes for
1030                         // 0x00-0x3f and 0x40-0x7f respectively, bad.
1031                 case 0xc2:      // 0x80-0xbf
1032                 case 0xc3:      // 0xc0-0xff
1033                 case 0xc4:      // 0x100-0x13f
1034                 case 0xc5:      // 0x140-0x17f
1035                 case 0xc6:      // 0x180-0x1bf
1036                 case 0xc7:      // 0x1c0-0x1ff
1037                 case 0xc8:      // 0x200-0x23f
1038                 case 0xc9:      // 0x240-0x27f
1039                 case 0xca:      // 0x280-0x2bf
1040                 case 0xcb:      // 0x2c0-0x2ff
1041                 case 0xcc:      // 0x300-0x33f
1042                 case 0xcd:      // 0x340-0x37f
1043                 case 0xce:      // 0x380-0x3bf
1044                 case 0xcf:      // 0x3c0-0x3ff
1045                 case 0xd0:      // 0x400-0x43f
1046                 case 0xd1:      // 0x440-0x47f
1047                 case 0xd2:      // 0x480-0x4bf
1048                 case 0xd3:      // 0x4c0-0x4ff
1049                 case 0xd4:      // 0x500-0x53f
1050                 case 0xd5:      // 0x540-0x57f
1051                 case 0xd6:      // 0x580-0x5bf
1052                 case 0xd7:      // 0x5c0-0x5ff
1053                 case 0xd8:      // 0x600-0x63f
1054                 case 0xd9:      // 0x640-0x67f
1055                 case 0xda:      // 0x680-0x6bf
1056                 case 0xdb:      // 0x6c0-0x6ff
1057                 case 0xdc:      // 0x700-0x73f
1058                 case 0xdd:      // 0x740-0x77f
1059                 case 0xde:      // 0x780-0x7bf
1060                 case 0xdf:      // 0x7c0-0x7ff
1061                         more = 1; // 2-byte sequences, 0x80-0x7ff
1062                         break;
1063                 case 0xe0:
1064                         // don't allow overlong sequences for 0-0x7ff
1065                         if ((p[i] & 0xff) < 0xa0)
1066                                 break;
1067                 case 0xe1:      // 0x1000-0x1fff
1068                 case 0xe2:      // 0x2000-0x2fff
1069                 case 0xe3:      // 0x3000-0x3fff
1070                 case 0xe4:      // 0x4000-0x4fff
1071                 case 0xe5:      // 0x5000-0x5fff
1072                 case 0xe6:      // 0x6000-0x6fff
1073                 case 0xe7:      // 0x7000-0x7fff
1074                 case 0xe8:      // 0x8000-0x8fff
1075                 case 0xe9:      // 0x9000-0x9fff
1076                 case 0xea:      // 0xa000-0xafff
1077                 case 0xeb:      // 0xb000-0xbfff
1078                 case 0xec:      // 0xc000-0xcfff
1079                         more = 2; // 3-byte sequences, 0x7ff-0xcfff
1080                         break;
1081                 case 0xed:      // 0xd000-0xdfff
1082                         // Don't allow surrogate codes 0xd800-0xdfff
1083                         if ((p[i] & 0xff) >= 0xa0)
1084                                 break;
1085                 case 0xee:      // 0xe000-0xefff
1086                 case 0xef:      // 0xf000-0xffff
1087                         more = 2; // 3-byte sequences,
1088                                   // 0xd000-0xd7ff, 0xe000-0xffff
1089                         break;
1090                 case 0xf0:
1091                         // don't allow overlong sequences for 0-0xffff
1092                         if ((p[i] & 0xff) < 0x90)
1093                                 break;
1094                 case 0xf1:      // 0x40000-0x7ffff
1095                 case 0xf2:      // 0x80000-0xbffff
1096                 case 0xf3:      // 0xc0000-0xfffff
1097                         more = 3; // 4-byte sequences, 0x10000-0xfffff
1098                         break;
1099                 case 0xf4:
1100                         // don't allow more than 0x10ffff
1101                         if ((p[i] & 0xff) >= 0x90)
1102                                 break;
1103                         more = 3; // 4-byte sequence, 0x100000-0x10ffff
1104                         break;
1105                 }
1106                 if (more) {
1107                         // check that all continuation bytes are valid
1108                         do {
1109                                 if ((p[i++] & 0xc0) != 0x80)
1110                                         break;
1111                         } while (--more);
1112                         if (!more)
1113                                 continue;
1114                 }
1115                 Input h = here_input ();
1116                 h.set (h.get_source_file (), h.start () + oldi, h.start () + i);
1117                 h.warning (_ ("non-UTF-8 input").c_str ());
1118         }
1119         return p;
1120 }
1121
1122
1123 /*
1124  urg, belong to string (_convert)
1125  and should be generalised 
1126  */
1127 void
1128 strip_leading_white (string&s)
1129 {
1130         ssize i = 0;
1131         for (;  i < s.length (); i++)
1132                 if (!isspace (s[i]))
1133                         break;
1134
1135         s = s.substr (i);
1136 }
1137
1138 void
1139 strip_trailing_white (string&s)
1140 {
1141         ssize i = s.length ();  
1142         while (i--) 
1143                 if (!isspace (s[i]))
1144                         break;
1145
1146         s = s.substr (0, i + 1);
1147 }
1148
1149
1150
1151 Lilypond_version oldest_version ("2.7.38");
1152
1153
1154 bool
1155 is_valid_version (string s)
1156 {
1157   Lilypond_version current ( MAJOR_VERSION "." MINOR_VERSION "." PATCH_LEVEL );
1158   Lilypond_version ver (s);
1159   if (int (ver) < oldest_version)
1160         {       
1161                 non_fatal_error (_f ("file too old: %s (oldest supported: %s)", ver.to_string (), oldest_version.to_string ()));
1162                 non_fatal_error (_ ("consider updating the input with the convert-ly script"));
1163                 return false;
1164         }
1165
1166   if (ver > current)
1167         {
1168                 non_fatal_error (_f ("program too old: %s (file requires: %s)",  current.to_string (), ver.to_string ()));
1169                 return false;
1170         }
1171   return true;
1172 }
1173         
1174
1175 /*
1176   substitute _
1177 */
1178 string
1179 lyric_fudge (string s)
1180 {
1181         size_t i=0;
1182
1183         while ((i = s.find ('_', i)) != string::npos)
1184         {
1185                 s[i++] = ' ';
1186         }
1187         return s;
1188 }
1189
1190 /*
1191 Convert "NUM/DEN" into a '(NUM . DEN) cons.
1192 */
1193 SCM
1194 scan_fraction (string frac)
1195 {
1196         ssize i = frac.find ('/');
1197         string left = frac.substr (0, i);
1198         string right = frac.substr (i + 1, (frac.length () - i + 1));
1199
1200         int n = String_convert::dec2int (left);
1201         int d = String_convert::dec2int (right);
1202         return scm_cons (scm_from_int (n), scm_from_int (d));
1203 }
1204
1205 SCM
1206 lookup_markup_command (string s)
1207 {
1208         SCM proc = ly_lily_module_constant ("lookup-markup-command");
1209         return scm_call_1 (proc, ly_string2scm (s));
1210 }
1211
1212 SCM
1213 lookup_markup_list_command (string s)
1214 {
1215         SCM proc = ly_lily_module_constant ("lookup-markup-list-command");
1216         return scm_call_1 (proc, ly_string2scm (s));
1217 }
1218
1219 /* Shut up lexer warnings.  */
1220 #if YY_STACK_USED
1221
1222 static void
1223 yy_push_state (int)
1224 {
1225 }
1226
1227 static void
1228 yy_pop_state ()
1229 {
1230 }
1231
1232 static int
1233 yy_top_state ()
1234 {
1235   return 0;
1236 }
1237
1238 static void
1239 silence_lexer_warnings ()
1240 {
1241    (void) yy_start_stack_ptr;
1242    (void) yy_start_stack_depth;
1243    (void) yy_start_stack;
1244    (void) yy_push_state;
1245    (void) yy_pop_state;
1246    (void) yy_top_state;
1247    (void) silence_lexer_warnings;
1248 }
1249 #endif