]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
Issue 2530: Use fractions rather than Scheme pairs for \scaleDuration, timeSignatureF...
[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--2012 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>q {
403         return CHORD_REPETITION;
404 }
405
406 <chords,notes,figures>R         {
407         return MULTI_MEASURE_REST;
408 }
409 <INITIAL,chords,figures,lyrics,markup,notes>#   { //embedded scm
410         int n = 0;
411         Input hi = here_input();
412         hi.step_forward ();
413         SCM sval = ly_parse_scm (hi.start (), &n, hi,
414                 be_safe_global && is_main_input_, parser_);
415
416         if (sval == SCM_UNDEFINED)
417                 error_level_ = 1;
418
419         for (int i = 0; i < n; i++)
420         {
421                 yyinput ();
422         }
423         char_count_stack_.back () += n;
424
425         yylval.scm = sval;
426         return SCM_TOKEN;
427 }
428
429 <INITIAL,chords,figures,lyrics,markup,notes>\$  { //immediate scm
430         int n = 0;
431         Input hi = here_input();
432         hi.step_forward ();
433         SCM sval = ly_parse_scm (hi.start (), &n, hi,
434                 be_safe_global && is_main_input_, parser_);
435
436         for (int i = 0; i < n; i++)
437         {
438                 yyinput ();
439         }
440         char_count_stack_.back () += n;
441
442         sval = eval_scm (sval);
443                 
444         int token = scan_scm_id (sval);
445         if (!scm_is_eq (yylval.scm, SCM_UNSPECIFIED))
446           return token;
447 }
448
449 <INITIAL,notes,lyrics>{ 
450         \<\<    {
451                 return DOUBLE_ANGLE_OPEN;
452         }
453         \>\>    {
454                 return DOUBLE_ANGLE_CLOSE;
455         }
456 }
457
458 <INITIAL,notes>{
459         \<      {
460                 return ANGLE_OPEN;
461         }
462         \>      {
463                 return ANGLE_CLOSE;
464         }
465 }
466
467 <figures>{
468         _       {
469                 return FIGURE_SPACE;
470         }
471         \>              {
472                 return FIGURE_CLOSE;
473         }
474         \<      {
475                 return FIGURE_OPEN;
476         }
477 }
478
479 <notes,figures>{
480         {ALPHAWORD}     {
481                 return scan_bare_word (YYText_utf8 ());
482         }
483
484         {NOTECOMMAND}   {
485                 return scan_escaped_word (YYText_utf8 () + 1); 
486         }
487         {FRACTION}      {
488                 yylval.scm =  scan_fraction (YYText ());
489                 return FRACTION;
490         }
491         {UNSIGNED}/\/   | // backup rule
492         {UNSIGNED}              {
493                 yylval.scm = scm_c_read_string (YYText ());
494                 return UNSIGNED;
495         }
496         {E_UNSIGNED}    {
497                 yylval.i = String_convert::dec2int (string (YYText () +1));
498                 return E_UNSIGNED;
499         }
500 }
501
502 <quote,lyric_quote>{
503         \\{ESCAPED}     {
504                 *yylval.string += to_string (escaped_char (YYText ()[1]));
505         }
506         [^\\""]+        {
507                 *yylval.string += YYText_utf8 ();
508         }
509         \"      {
510
511                 yy_pop_state ();
512
513                 /* yylval is union. Must remember STRING before setting SCM*/
514                 string *sp = yylval.string;
515                 yylval.scm = ly_string2scm (*sp);
516                 delete sp;
517                 return is_lyric_state () ? LYRICS_STRING : STRING;
518         }
519         \\      {
520                 *yylval.string += YYText ();
521         }
522 }
523
524 <lyrics>{
525         \" {
526                 start_lyric_quote ();
527         }
528         {FRACTION}      {
529                 yylval.scm =  scan_fraction (YYText ());
530                 return FRACTION;
531         }
532         {UNSIGNED}/\/[^0-9] { // backup rule
533                 yylval.scm = scm_c_read_string (YYText ());
534                 return UNSIGNED;
535         }
536         {UNSIGNED}/\/   | // backup rule
537         {UNSIGNED}              {
538                 yylval.scm = scm_c_read_string (YYText ());
539                 return UNSIGNED;
540         }
541         {NOTECOMMAND}   {
542                 return scan_escaped_word (YYText_utf8 () + 1);
543         }
544         {LYRICS} {
545                 /* ugr. This sux. */
546                 string s (YYText_utf8 ()); 
547                 if (s == "__")
548                         return yylval.i = EXTENDER;
549                 if (s == "--")
550                         return yylval.i = HYPHEN;
551                 s = lyric_fudge (s);
552
553                 char c = s[s.length () - 1];
554                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
555                         here_input ().warning (
556                                 _ ("Brace found at end of lyric.  Did you forget a space?"));
557                 yylval.scm = ly_string2scm (s);
558
559
560                 return LYRICS_STRING;
561         }
562         . {
563                 return YYText ()[0]; // LYRICS already catches all multibytes.
564         }
565 }
566 <chords>{
567         {ALPHAWORD}     {
568                 return scan_bare_word (YYText_utf8 ());
569         }
570         {NOTECOMMAND}   {
571                 return scan_escaped_word (YYText_utf8 () + 1);
572         }
573         {FRACTION}      {
574                 yylval.scm =  scan_fraction (YYText ());
575                 return FRACTION;
576         }
577         {UNSIGNED}/\/[^0-9] { // backup rule
578                 yylval.scm = scm_c_read_string (YYText ());
579                 return UNSIGNED;
580         }
581         {UNSIGNED}/\/   | // backup rule
582         {UNSIGNED}              {
583                 yylval.scm = scm_c_read_string (YYText ());
584                 return UNSIGNED;
585         }
586         -  {
587                 return CHORD_MINUS;
588         }
589         :  {
590                 return CHORD_COLON;
591         }
592         \/\+ {
593                 return CHORD_BASS;
594         }
595         \/  {
596                 return CHORD_SLASH;
597         }
598         \^  {
599                 return CHORD_CARET;
600         }
601         . {
602                 return YYText ()[0]; // ALPHAWORD catches all multibyte.
603         }
604 }
605
606
607 <markup>{
608         \\score {
609                 return SCORE;
610         }
611         {MARKUPCOMMAND} {
612                 string str (YYText_utf8 () + 1);
613
614                 int token_type = MARKUP_FUNCTION;
615                 SCM s = lookup_markup_command (str);
616
617                 // lookup-markup-command returns a pair with the car
618                 // being the function to call, and the cdr being the
619                 // call signature specified to define-markup-command,
620                 // a list of predicates.
621
622                 if (!scm_is_pair (s)) {
623                   // If lookup-markup-command was not successful, we
624                   // try lookup-markup-list-command instead.
625                   // If this fails as well, we just scan and return
626                   // the escaped word.
627                   s = lookup_markup_list_command (str);
628                   if (scm_is_pair (s))
629                     token_type = MARKUP_LIST_FUNCTION;
630                   else
631                     return scan_escaped_word (str);
632                 }
633
634                 // If the list of predicates is, say,
635                 // (number? number? markup?), then tokens
636                 // EXPECT_MARKUP EXPECT_SCM EXPECT_SCM EXPECT_NO_MORE_ARGS
637                 // will be generated.  Note that we have to push them
638                 // in reverse order, so the first token pushed in the
639                 // loop will be EXPECT_NO_MORE_ARGS.
640
641                 yylval.scm = scm_car(s);
642
643                 // yylval now contains the function to call as token
644                 // value (for token type MARKUP_FUNCTION or
645                 // MARKUP_LIST_FUNCTION).
646
647                 push_extra_token(EXPECT_NO_MORE_ARGS);
648                 s = scm_cdr(s);
649                 for (; scm_is_pair(s); s = scm_cdr(s)) {
650                   SCM predicate = scm_car(s);
651
652                   if (predicate == ly_lily_module_constant ("markup-list?"))
653                     push_extra_token(EXPECT_MARKUP_LIST);
654                   else if (predicate == ly_lily_module_constant ("markup?"))
655                     push_extra_token(EXPECT_MARKUP);
656                   else
657                     push_extra_token(EXPECT_SCM, predicate);
658                 }
659                 return token_type;
660         }
661         [{}]    {
662                 return YYText ()[0];
663         }
664         [^$#{}\"\\ \t\n\r\f]+ {
665                 string s (YYText_utf8 ()); 
666
667                 char c = s[s.length () - 1];
668                 /* brace open is for not confusing dumb tools.  */
669                 if (c == '{' ||  c == '}')
670                         here_input ().warning (
671                                 _ ("Brace found at end of markup.  Did you forget a space?"));
672                 yylval.scm = ly_string2scm (s);
673
674
675                 return STRING;
676         }
677         .  {
678                 return YYText()[0];  // Above is catchall for multibyte
679         }
680 }
681
682 <longcomment><<EOF>> {
683                 LexerError (_ ("EOF found inside a comment").c_str ());
684                 is_main_input_ = false; // should be safe , can't have \include in --safe.
685                 if (!close_input ())
686                   yyterminate (); // can't move this, since it actually rets a YY_NULL
687         }
688
689 <<EOF>> { if (is_main_input_)
690         {
691                 /* 2 = init.ly + current file.
692                    > because we're before closing, but is_main_input_ should
693                    reflect after.
694                 */ 
695                 is_main_input_ = include_stack_.size () > 2;
696                 if (!close_input ())
697                 /* Returns YY_NULL */
698                         yyterminate ();
699         }
700         else if (!close_input ())
701                 /* Returns YY_NULL */
702                 yyterminate ();
703 }
704
705 <INITIAL>{
706         {DASHED_WORD}   {
707                 return scan_bare_word (YYText_utf8 ());
708         }
709         {DASHED_KEY_WORD}       {
710                 return scan_escaped_word (YYText_utf8 () + 1);
711         }
712 }
713
714 {FRACTION}      {
715         yylval.scm =  scan_fraction (YYText ());
716         return FRACTION;
717 }
718
719 -{UNSIGNED}     | // backup rule
720 {REAL}          {
721         yylval.scm = scm_c_read_string (YYText ());
722         return REAL;
723 }
724 -\.     { // backup rule
725         yylval.scm = scm_from_double (0.0);
726         return REAL;
727 }
728
729 {UNSIGNED}/\/   | // backup rule
730 {UNSIGNED}      {
731         yylval.scm = scm_c_read_string (YYText ());
732         return UNSIGNED;
733 }
734
735
736 [{}]    {
737
738         return YYText ()[0];
739 }
740 [*:=]           {
741         char c = YYText ()[0];
742
743         return c;
744 }
745
746 <INITIAL,notes,figures>.        {
747         return YYText ()[0];
748 }
749
750 <INITIAL,lyrics,notes,figures>\\. {
751     char c = YYText ()[1];
752
753     switch (c) {
754     case '>':
755         return E_ANGLE_CLOSE;
756     case '<':
757         return E_ANGLE_OPEN;
758     case '!':
759         return E_EXCLAMATION;
760     case '(':
761         return E_OPEN;
762     case ')':
763         return E_CLOSE;
764     case '[':
765         return E_BRACKET_OPEN;
766     case '+':
767         return E_PLUS;
768     case ']':
769         return E_BRACKET_CLOSE;
770     case '~':
771         return E_TILDE;
772     case '\\':
773         return E_BACKSLASH;
774
775     default:
776         return E_CHAR;
777     }
778 }
779
780 <*>.[\200-\277]*        {
781         string msg = _f ("invalid character: `%s'", YYText_utf8 ());
782         LexerError (msg.c_str ());
783         return '%';  // Better not return half a utf8 character.
784 }
785
786 %%
787
788 /* Make the lexer generate a token of the given type as the next token. 
789  TODO: make it possible to define a value for the token as well */
790 void
791 Lily_lexer::push_extra_token (int token_type, SCM scm)
792 {
793         if (scm_is_null (extra_tokens_))
794         {
795                 if (YY_START != extratoken)
796                         hidden_state_ = YY_START;
797                 yy_push_state (extratoken);
798         }
799         extra_tokens_ = scm_acons (scm_from_int (token_type), scm, extra_tokens_);
800 }
801
802 void
803 Lily_lexer::push_chord_state (SCM tab)
804 {
805         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
806         yy_push_state (chords);
807 }
808
809 void
810 Lily_lexer::push_figuredbass_state ()
811 {
812         yy_push_state (figures);
813 }
814
815 void
816 Lily_lexer::push_initial_state ()
817 {
818         yy_push_state (INITIAL);
819 }
820
821 void
822 Lily_lexer::push_lyric_state ()
823 {
824         yy_push_state (lyrics);
825 }
826
827 void
828 Lily_lexer::push_markup_state ()
829 {
830         yy_push_state (markup);
831 }
832
833 void
834 Lily_lexer::push_note_state (SCM tab)
835 {
836         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
837         yy_push_state (notes);
838 }
839
840 void
841 Lily_lexer::pop_state ()
842 {
843         bool extra = (YYSTATE == extratoken);
844
845         if (extra)
846                 yy_pop_state ();
847
848         if (YYSTATE == notes || YYSTATE == chords)
849                 pitchname_tab_stack_ = scm_cdr (pitchname_tab_stack_);
850
851         yy_pop_state ();
852
853         if (extra) {
854                 hidden_state_ = YYSTATE;
855                 yy_push_state (extratoken);
856         }
857 }
858
859 int
860 Lily_lexer::identifier_type (SCM sid)
861 {
862         int k = try_special_identifiers (&yylval.scm , sid);
863         return k >= 0  ? k : SCM_IDENTIFIER;
864 }
865
866
867 int
868 Lily_lexer::scan_escaped_word (string str)
869 {
870         // use more SCM for this.
871
872 //      SCM sym = ly_symbol2scm (str.c_str ());
873
874         int i = lookup_keyword (str);
875         if (i == MARKUP && is_lyric_state ())
876                 return LYRIC_MARKUP;
877         if (i != -1)
878                 return i;
879
880         SCM sid = lookup_identifier (str);
881         if (sid != SCM_UNDEFINED)
882                 return scan_scm_id (sid);
883
884         string msg (_f ("unknown escaped string: `\\%s'", str));        
885         LexerError (msg.c_str ());
886
887         yylval.scm = ly_string2scm (str);
888
889         return STRING;
890 }
891
892 int
893 Lily_lexer::scan_scm_id (SCM sid)
894 {
895         if (is_music_function (sid))
896         {
897                 int funtype = SCM_FUNCTION;
898
899                 yylval.scm = sid;
900
901                 SCM s = get_music_function_signature (sid);
902                 SCM cs = scm_car (s);
903
904                 if (scm_is_pair (cs))
905                 {
906                         cs = SCM_CAR (cs);
907                 }
908
909                 if (scm_is_eq (cs, ly_lily_module_constant ("ly:music?")))
910                         funtype = MUSIC_FUNCTION;
911                 else if (scm_is_eq (cs, ly_lily_module_constant ("ly:event?")))
912                         funtype = EVENT_FUNCTION;
913                 else if (ly_is_procedure (cs))
914                         funtype = SCM_FUNCTION;
915                 else programming_error ("Bad syntax function predicate");
916
917                 push_extra_token (EXPECT_NO_MORE_ARGS);
918                 for (s = scm_cdr (s); scm_is_pair (s); s = scm_cdr (s))
919                 {
920                         SCM optional = SCM_UNDEFINED;
921                         cs = scm_car (s);
922
923                         if (scm_is_pair (cs))
924                         {
925                                 optional = SCM_CDR (cs);
926                                 cs = SCM_CAR (cs);
927                         }
928                         
929                         if (cs == Pitch_type_p_proc)
930                                 push_extra_token (EXPECT_PITCH);
931                         else if (cs == Duration_type_p_proc)
932                                 push_extra_token (EXPECT_DURATION);
933                         else if (ly_is_procedure (cs))
934                                 push_extra_token (EXPECT_SCM, cs);
935                         else
936                         {
937                                 programming_error ("Function parameter without type-checking predicate");
938                                 continue;
939                         }
940                         if (!scm_is_eq (optional, SCM_UNDEFINED))
941                                 push_extra_token (EXPECT_OPTIONAL, optional);
942                 }
943                 return funtype;
944         }
945         yylval.scm = sid;
946         return identifier_type (sid);
947 }
948
949 int
950 Lily_lexer::scan_bare_word (string str)
951 {
952         SCM sym = ly_symbol2scm (str.c_str ());
953         if ((YYSTATE == notes) || (YYSTATE == chords)) {
954                 SCM handle = SCM_BOOL_F;
955                 if (scm_is_pair (pitchname_tab_stack_))
956                         handle = scm_hashq_get_handle (scm_car (pitchname_tab_stack_), sym);
957                 
958                 if (scm_is_pair (handle)) {
959                         yylval.scm = scm_cdr (handle);
960                         if (unsmob_pitch (yylval.scm)) 
961                             return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
962                         else if (scm_is_symbol (yylval.scm))
963                             return DRUM_PITCH;
964                 }
965                 else if ((YYSTATE == chords)
966                         && (handle = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
967                 {
968                     yylval.scm = scm_cdr (handle);
969                     return CHORD_MODIFIER;
970                 }
971         }
972         yylval.scm = ly_string2scm (str);
973         return STRING;
974 }
975
976 int
977 Lily_lexer::get_state () const
978 {
979         if (YY_START == extratoken)
980                 return hidden_state_;
981         else
982                 return YY_START;
983 }
984
985 bool
986 Lily_lexer::is_note_state () const
987 {
988         return get_state () == notes;
989 }
990
991 bool
992 Lily_lexer::is_chord_state () const
993 {
994         return get_state () == chords;
995 }
996
997 bool
998 Lily_lexer::is_lyric_state () const
999 {
1000         return get_state () == lyrics;
1001 }
1002
1003 bool
1004 Lily_lexer::is_figure_state () const
1005 {
1006         return get_state () == figures;
1007 }
1008
1009 SCM
1010 Lily_lexer::eval_scm (SCM readerdata)
1011 {
1012         SCM sval = SCM_UNDEFINED;
1013
1014         if (!SCM_UNBNDP (readerdata))
1015         {
1016                 sval = ly_eval_scm (scm_car (readerdata),
1017                                     *unsmob_input (scm_cdr (readerdata)),
1018                                     be_safe_global && is_main_input_,
1019                                     parser_);
1020         }
1021
1022         if (SCM_UNBNDP (sval))
1023         {
1024                 error_level_ = 1;
1025                 return SCM_UNSPECIFIED;
1026         }
1027         return sval;
1028 }
1029
1030 /* Check for valid UTF-8 that has no overlong or surrogate codes and
1031    is in the range 0-0x10ffff */
1032
1033 const char *
1034 Lily_lexer::YYText_utf8 ()
1035 {
1036         const char * const p =  YYText ();
1037         for (int i=0; p[i];) {
1038                 if ((p[i] & 0xff) < 0x80) {
1039                         ++i;
1040                         continue;
1041                 }
1042                 int oldi = i; // start of character
1043                 int more = 0; // # of followup bytes, 0 if bad
1044                 switch (p[i++] & 0xff) {
1045                         // 0xc0 and 0xc1 are overlong prefixes for
1046                         // 0x00-0x3f and 0x40-0x7f respectively, bad.
1047                 case 0xc2:      // 0x80-0xbf
1048                 case 0xc3:      // 0xc0-0xff
1049                 case 0xc4:      // 0x100-0x13f
1050                 case 0xc5:      // 0x140-0x17f
1051                 case 0xc6:      // 0x180-0x1bf
1052                 case 0xc7:      // 0x1c0-0x1ff
1053                 case 0xc8:      // 0x200-0x23f
1054                 case 0xc9:      // 0x240-0x27f
1055                 case 0xca:      // 0x280-0x2bf
1056                 case 0xcb:      // 0x2c0-0x2ff
1057                 case 0xcc:      // 0x300-0x33f
1058                 case 0xcd:      // 0x340-0x37f
1059                 case 0xce:      // 0x380-0x3bf
1060                 case 0xcf:      // 0x3c0-0x3ff
1061                 case 0xd0:      // 0x400-0x43f
1062                 case 0xd1:      // 0x440-0x47f
1063                 case 0xd2:      // 0x480-0x4bf
1064                 case 0xd3:      // 0x4c0-0x4ff
1065                 case 0xd4:      // 0x500-0x53f
1066                 case 0xd5:      // 0x540-0x57f
1067                 case 0xd6:      // 0x580-0x5bf
1068                 case 0xd7:      // 0x5c0-0x5ff
1069                 case 0xd8:      // 0x600-0x63f
1070                 case 0xd9:      // 0x640-0x67f
1071                 case 0xda:      // 0x680-0x6bf
1072                 case 0xdb:      // 0x6c0-0x6ff
1073                 case 0xdc:      // 0x700-0x73f
1074                 case 0xdd:      // 0x740-0x77f
1075                 case 0xde:      // 0x780-0x7bf
1076                 case 0xdf:      // 0x7c0-0x7ff
1077                         more = 1; // 2-byte sequences, 0x80-0x7ff
1078                         break;
1079                 case 0xe0:
1080                         // don't allow overlong sequences for 0-0x7ff
1081                         if ((p[i] & 0xff) < 0xa0)
1082                                 break;
1083                 case 0xe1:      // 0x1000-0x1fff
1084                 case 0xe2:      // 0x2000-0x2fff
1085                 case 0xe3:      // 0x3000-0x3fff
1086                 case 0xe4:      // 0x4000-0x4fff
1087                 case 0xe5:      // 0x5000-0x5fff
1088                 case 0xe6:      // 0x6000-0x6fff
1089                 case 0xe7:      // 0x7000-0x7fff
1090                 case 0xe8:      // 0x8000-0x8fff
1091                 case 0xe9:      // 0x9000-0x9fff
1092                 case 0xea:      // 0xa000-0xafff
1093                 case 0xeb:      // 0xb000-0xbfff
1094                 case 0xec:      // 0xc000-0xcfff
1095                         more = 2; // 3-byte sequences, 0x7ff-0xcfff
1096                         break;
1097                 case 0xed:      // 0xd000-0xdfff
1098                         // Don't allow surrogate codes 0xd800-0xdfff
1099                         if ((p[i] & 0xff) >= 0xa0)
1100                                 break;
1101                 case 0xee:      // 0xe000-0xefff
1102                 case 0xef:      // 0xf000-0xffff
1103                         more = 2; // 3-byte sequences,
1104                                   // 0xd000-0xd7ff, 0xe000-0xffff
1105                         break;
1106                 case 0xf0:
1107                         // don't allow overlong sequences for 0-0xffff
1108                         if ((p[i] & 0xff) < 0x90)
1109                                 break;
1110                 case 0xf1:      // 0x40000-0x7ffff
1111                 case 0xf2:      // 0x80000-0xbffff
1112                 case 0xf3:      // 0xc0000-0xfffff
1113                         more = 3; // 4-byte sequences, 0x10000-0xfffff
1114                         break;
1115                 case 0xf4:
1116                         // don't allow more than 0x10ffff
1117                         if ((p[i] & 0xff) >= 0x90)
1118                                 break;
1119                         more = 3; // 4-byte sequence, 0x100000-0x10ffff
1120                         break;
1121                 }
1122                 if (more) {
1123                         // check that all continuation bytes are valid
1124                         do {
1125                                 if ((p[i++] & 0xc0) != 0x80)
1126                                         break;
1127                         } while (--more);
1128                         if (!more)
1129                                 continue;
1130                 }
1131                 Input h = here_input ();
1132                 h.set (h.get_source_file (), h.start () + oldi, h.start () + i);
1133                 h.warning (_ ("non-UTF-8 input").c_str ());
1134         }
1135         return p;
1136 }
1137
1138
1139 /*
1140  urg, belong to string (_convert)
1141  and should be generalised 
1142  */
1143 void
1144 strip_leading_white (string&s)
1145 {
1146         ssize i = 0;
1147         for (;  i < s.length (); i++)
1148                 if (!isspace (s[i]))
1149                         break;
1150
1151         s = s.substr (i);
1152 }
1153
1154 void
1155 strip_trailing_white (string&s)
1156 {
1157         ssize i = s.length ();  
1158         while (i--) 
1159                 if (!isspace (s[i]))
1160                         break;
1161
1162         s = s.substr (0, i + 1);
1163 }
1164
1165
1166
1167 Lilypond_version oldest_version ("2.7.38");
1168
1169
1170 bool
1171 is_valid_version (string s)
1172 {
1173   Lilypond_version current ( MAJOR_VERSION "." MINOR_VERSION "." PATCH_LEVEL );
1174   Lilypond_version ver (s);
1175   if (int (ver) < oldest_version)
1176         {       
1177                 non_fatal_error (_f ("file too old: %s (oldest supported: %s)", ver.to_string (), oldest_version.to_string ()));
1178                 non_fatal_error (_ ("consider updating the input with the convert-ly script"));
1179                 return false;
1180         }
1181
1182   if (ver > current)
1183         {
1184                 non_fatal_error (_f ("program too old: %s (file requires: %s)",  current.to_string (), ver.to_string ()));
1185                 return false;
1186         }
1187   return true;
1188 }
1189         
1190
1191 /*
1192   substitute _
1193 */
1194 string
1195 lyric_fudge (string s)
1196 {
1197         size_t i=0;
1198
1199         while ((i = s.find ('_', i)) != string::npos)
1200         {
1201                 s[i++] = ' ';
1202         }
1203         return s;
1204 }
1205
1206 /*
1207 Convert "NUM/DEN" into a '(NUM . DEN) cons.
1208 */
1209 SCM
1210 scan_fraction (string frac)
1211 {
1212         ssize i = frac.find ('/');
1213         string left = frac.substr (0, i);
1214         string right = frac.substr (i + 1, (frac.length () - i + 1));
1215
1216         int n = String_convert::dec2int (left);
1217         int d = String_convert::dec2int (right);
1218         return scm_cons (scm_from_int (n), scm_from_int (d));
1219 }
1220
1221 SCM
1222 lookup_markup_command (string s)
1223 {
1224         SCM proc = ly_lily_module_constant ("lookup-markup-command");
1225         return scm_call_1 (proc, ly_string2scm (s));
1226 }
1227
1228 SCM
1229 lookup_markup_list_command (string s)
1230 {
1231         SCM proc = ly_lily_module_constant ("lookup-markup-list-command");
1232         return scm_call_1 (proc, ly_string2scm (s));
1233 }
1234
1235 /* Shut up lexer warnings.  */
1236 #if YY_STACK_USED
1237
1238 static void
1239 yy_push_state (int)
1240 {
1241 }
1242
1243 static void
1244 yy_pop_state ()
1245 {
1246 }
1247
1248 static int
1249 yy_top_state ()
1250 {
1251   return 0;
1252 }
1253
1254 static void
1255 silence_lexer_warnings ()
1256 {
1257    (void) yy_start_stack_ptr;
1258    (void) yy_start_stack_depth;
1259    (void) yy_start_stack;
1260    (void) yy_push_state;
1261    (void) yy_pop_state;
1262    (void) yy_top_state;
1263    (void) silence_lexer_warnings;
1264 }
1265 #endif