]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
lexer.ll: Let pop_state preserve extratoken state
[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 -{UNSIGNED}     | // backup rule
715 {REAL}          {
716         yylval.scm = scm_c_read_string (YYText ());
717         return REAL;
718 }
719 -\.     { // backup rule
720         yylval.scm = scm_from_double (0.0);
721         return REAL;
722 }
723
724 {UNSIGNED}      {
725         yylval.scm = scm_c_read_string (YYText ());
726         return UNSIGNED;
727 }
728
729
730 [{}]    {
731
732         return YYText ()[0];
733 }
734 [*:=]           {
735         char c = YYText ()[0];
736
737         return c;
738 }
739
740 <INITIAL,notes,figures>.        {
741         return YYText ()[0];
742 }
743
744 <INITIAL,lyrics,notes,figures>\\. {
745     char c = YYText ()[1];
746
747     switch (c) {
748     case '>':
749         return E_ANGLE_CLOSE;
750     case '<':
751         return E_ANGLE_OPEN;
752     case '!':
753         return E_EXCLAMATION;
754     case '(':
755         return E_OPEN;
756     case ')':
757         return E_CLOSE;
758     case '[':
759         return E_BRACKET_OPEN;
760     case '+':
761         return E_PLUS;
762     case ']':
763         return E_BRACKET_CLOSE;
764     case '~':
765         return E_TILDE;
766     case '\\':
767         return E_BACKSLASH;
768
769     default:
770         return E_CHAR;
771     }
772 }
773
774 <*>.[\200-\277]*        {
775         string msg = _f ("invalid character: `%s'", YYText_utf8 ());
776         LexerError (msg.c_str ());
777         return '%';  // Better not return half a utf8 character.
778 }
779
780 %%
781
782 /* Make the lexer generate a token of the given type as the next token. 
783  TODO: make it possible to define a value for the token as well */
784 void
785 Lily_lexer::push_extra_token (int token_type, SCM scm)
786 {
787         if (scm_is_null (extra_tokens_))
788         {
789                 if (YY_START != extratoken)
790                         hidden_state_ = YY_START;
791                 yy_push_state (extratoken);
792         }
793         extra_tokens_ = scm_acons (scm_from_int (token_type), scm, extra_tokens_);
794 }
795
796 void
797 Lily_lexer::push_chord_state (SCM tab)
798 {
799         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
800         yy_push_state (chords);
801 }
802
803 void
804 Lily_lexer::push_figuredbass_state ()
805 {
806         yy_push_state (figures);
807 }
808
809 void
810 Lily_lexer::push_initial_state ()
811 {
812         yy_push_state (INITIAL);
813 }
814
815 void
816 Lily_lexer::push_lyric_state ()
817 {
818         yy_push_state (lyrics);
819 }
820
821 void
822 Lily_lexer::push_markup_state ()
823 {
824         yy_push_state (markup);
825 }
826
827 void
828 Lily_lexer::push_note_state (SCM tab)
829 {
830         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
831         yy_push_state (notes);
832 }
833
834 void
835 Lily_lexer::pop_state ()
836 {
837         bool extra = (YYSTATE == extratoken);
838
839         if (extra)
840                 yy_pop_state ();
841
842         if (YYSTATE == notes || YYSTATE == chords)
843                 pitchname_tab_stack_ = scm_cdr (pitchname_tab_stack_);
844
845         yy_pop_state ();
846
847         if (extra) {
848                 hidden_state_ = YYSTATE;
849                 yy_push_state (extratoken);
850         }
851 }
852
853 int
854 Lily_lexer::identifier_type (SCM sid)
855 {
856         int k = try_special_identifiers (&yylval.scm , sid);
857         return k >= 0  ? k : SCM_IDENTIFIER;
858 }
859
860
861 int
862 Lily_lexer::scan_escaped_word (string str)
863 {
864         // use more SCM for this.
865
866 //      SCM sym = ly_symbol2scm (str.c_str ());
867
868         int i = lookup_keyword (str);
869         if (i == MARKUP && is_lyric_state ())
870                 return LYRIC_MARKUP;
871         if (i != -1)
872                 return i;
873
874         SCM sid = lookup_identifier (str);
875         if (sid != SCM_UNDEFINED)
876                 return scan_scm_id (sid);
877
878         string msg (_f ("unknown escaped string: `\\%s'", str));        
879         LexerError (msg.c_str ());
880
881         yylval.scm = ly_string2scm (str);
882
883         return STRING;
884 }
885
886 int
887 Lily_lexer::scan_scm_id (SCM sid)
888 {
889         if (is_music_function (sid))
890         {
891                 int funtype = SCM_FUNCTION;
892
893                 yylval.scm = get_music_function_transform (sid);
894
895                 SCM s = scm_object_property (yylval.scm, ly_symbol2scm ("music-function-signature"));
896                 SCM cs = scm_car (s);
897
898                 if (scm_is_pair (cs))
899                 {
900                         cs = SCM_CAR (cs);
901                 }
902
903                 if (scm_is_eq (cs, ly_lily_module_constant ("ly:music?")))
904                         funtype = MUSIC_FUNCTION;
905                 else if (scm_is_eq (cs, ly_lily_module_constant ("ly:event?")))
906                         funtype = EVENT_FUNCTION;
907                 else if (ly_is_procedure (cs))
908                         funtype = SCM_FUNCTION;
909                 else programming_error ("Bad syntax function predicate");
910
911                 push_extra_token (EXPECT_NO_MORE_ARGS);
912                 for (s = scm_cdr (s); scm_is_pair (s); s = scm_cdr (s))
913                 {
914                         SCM optional = SCM_UNDEFINED;
915                         cs = scm_car (s);
916
917                         if (scm_is_pair (cs))
918                         {
919                                 optional = SCM_CDR (cs);
920                                 cs = SCM_CAR (cs);
921                         }
922                         
923                         if (cs == Pitch_type_p_proc)
924                                 push_extra_token (EXPECT_PITCH);
925                         else if (cs == Duration_type_p_proc)
926                                 push_extra_token (EXPECT_DURATION);
927                         else if (ly_is_procedure (cs))
928                                 push_extra_token (EXPECT_SCM, cs);
929                         else
930                         {
931                                 programming_error ("Function parameter without type-checking predicate");
932                                 continue;
933                         }
934                         if (!scm_is_eq (optional, SCM_UNDEFINED))
935                                 push_extra_token (EXPECT_OPTIONAL, optional);
936                 }
937                 return funtype;
938         }
939         yylval.scm = sid;
940         return identifier_type (sid);
941 }
942
943 int
944 Lily_lexer::scan_bare_word (string str)
945 {
946         SCM sym = ly_symbol2scm (str.c_str ());
947         if ((YYSTATE == notes) || (YYSTATE == chords)) {
948                 SCM handle = SCM_BOOL_F;
949                 if (scm_is_pair (pitchname_tab_stack_))
950                         handle = scm_hashq_get_handle (scm_car (pitchname_tab_stack_), sym);
951                 
952                 if (scm_is_pair (handle)) {
953                         yylval.scm = scm_cdr (handle);
954                         if (unsmob_pitch (yylval.scm)) 
955                             return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
956                         else if (scm_is_symbol (yylval.scm))
957                             return DRUM_PITCH;
958                 }
959                 else if ((YYSTATE == chords)
960                         && (handle = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
961                 {
962                     yylval.scm = scm_cdr (handle);
963                     return CHORD_MODIFIER;
964                 }
965         }
966         yylval.scm = ly_string2scm (str);
967         return STRING;
968 }
969
970 int
971 Lily_lexer::get_state () const
972 {
973         if (YY_START == extratoken)
974                 return hidden_state_;
975         else
976                 return YY_START;
977 }
978
979 bool
980 Lily_lexer::is_note_state () const
981 {
982         return get_state () == notes;
983 }
984
985 bool
986 Lily_lexer::is_chord_state () const
987 {
988         return get_state () == chords;
989 }
990
991 bool
992 Lily_lexer::is_lyric_state () const
993 {
994         return get_state () == lyrics;
995 }
996
997 bool
998 Lily_lexer::is_figure_state () const
999 {
1000         return get_state () == figures;
1001 }
1002
1003 SCM
1004 Lily_lexer::eval_scm (SCM readerdata)
1005 {
1006         SCM sval = SCM_UNDEFINED;
1007
1008         if (!SCM_UNBNDP (readerdata))
1009         {
1010                 sval = ly_eval_scm (scm_car (readerdata),
1011                                     *unsmob_input (scm_cdr (readerdata)),
1012                                     be_safe_global && is_main_input_,
1013                                     parser_);
1014         }
1015
1016         if (SCM_UNBNDP (sval))
1017         {
1018                 error_level_ = 1;
1019                 return SCM_UNSPECIFIED;
1020         }
1021         return sval;
1022 }
1023
1024 /* Check for valid UTF-8 that has no overlong or surrogate codes and
1025    is in the range 0-0x10ffff */
1026
1027 const char *
1028 Lily_lexer::YYText_utf8 ()
1029 {
1030         const char * const p =  YYText ();
1031         for (int i=0; p[i];) {
1032                 if ((p[i] & 0xff) < 0x80) {
1033                         ++i;
1034                         continue;
1035                 }
1036                 int oldi = i; // start of character
1037                 int more = 0; // # of followup bytes, 0 if bad
1038                 switch (p[i++] & 0xff) {
1039                         // 0xc0 and 0xc1 are overlong prefixes for
1040                         // 0x00-0x3f and 0x40-0x7f respectively, bad.
1041                 case 0xc2:      // 0x80-0xbf
1042                 case 0xc3:      // 0xc0-0xff
1043                 case 0xc4:      // 0x100-0x13f
1044                 case 0xc5:      // 0x140-0x17f
1045                 case 0xc6:      // 0x180-0x1bf
1046                 case 0xc7:      // 0x1c0-0x1ff
1047                 case 0xc8:      // 0x200-0x23f
1048                 case 0xc9:      // 0x240-0x27f
1049                 case 0xca:      // 0x280-0x2bf
1050                 case 0xcb:      // 0x2c0-0x2ff
1051                 case 0xcc:      // 0x300-0x33f
1052                 case 0xcd:      // 0x340-0x37f
1053                 case 0xce:      // 0x380-0x3bf
1054                 case 0xcf:      // 0x3c0-0x3ff
1055                 case 0xd0:      // 0x400-0x43f
1056                 case 0xd1:      // 0x440-0x47f
1057                 case 0xd2:      // 0x480-0x4bf
1058                 case 0xd3:      // 0x4c0-0x4ff
1059                 case 0xd4:      // 0x500-0x53f
1060                 case 0xd5:      // 0x540-0x57f
1061                 case 0xd6:      // 0x580-0x5bf
1062                 case 0xd7:      // 0x5c0-0x5ff
1063                 case 0xd8:      // 0x600-0x63f
1064                 case 0xd9:      // 0x640-0x67f
1065                 case 0xda:      // 0x680-0x6bf
1066                 case 0xdb:      // 0x6c0-0x6ff
1067                 case 0xdc:      // 0x700-0x73f
1068                 case 0xdd:      // 0x740-0x77f
1069                 case 0xde:      // 0x780-0x7bf
1070                 case 0xdf:      // 0x7c0-0x7ff
1071                         more = 1; // 2-byte sequences, 0x80-0x7ff
1072                         break;
1073                 case 0xe0:
1074                         // don't allow overlong sequences for 0-0x7ff
1075                         if ((p[i] & 0xff) < 0xa0)
1076                                 break;
1077                 case 0xe1:      // 0x1000-0x1fff
1078                 case 0xe2:      // 0x2000-0x2fff
1079                 case 0xe3:      // 0x3000-0x3fff
1080                 case 0xe4:      // 0x4000-0x4fff
1081                 case 0xe5:      // 0x5000-0x5fff
1082                 case 0xe6:      // 0x6000-0x6fff
1083                 case 0xe7:      // 0x7000-0x7fff
1084                 case 0xe8:      // 0x8000-0x8fff
1085                 case 0xe9:      // 0x9000-0x9fff
1086                 case 0xea:      // 0xa000-0xafff
1087                 case 0xeb:      // 0xb000-0xbfff
1088                 case 0xec:      // 0xc000-0xcfff
1089                         more = 2; // 3-byte sequences, 0x7ff-0xcfff
1090                         break;
1091                 case 0xed:      // 0xd000-0xdfff
1092                         // Don't allow surrogate codes 0xd800-0xdfff
1093                         if ((p[i] & 0xff) >= 0xa0)
1094                                 break;
1095                 case 0xee:      // 0xe000-0xefff
1096                 case 0xef:      // 0xf000-0xffff
1097                         more = 2; // 3-byte sequences,
1098                                   // 0xd000-0xd7ff, 0xe000-0xffff
1099                         break;
1100                 case 0xf0:
1101                         // don't allow overlong sequences for 0-0xffff
1102                         if ((p[i] & 0xff) < 0x90)
1103                                 break;
1104                 case 0xf1:      // 0x40000-0x7ffff
1105                 case 0xf2:      // 0x80000-0xbffff
1106                 case 0xf3:      // 0xc0000-0xfffff
1107                         more = 3; // 4-byte sequences, 0x10000-0xfffff
1108                         break;
1109                 case 0xf4:
1110                         // don't allow more than 0x10ffff
1111                         if ((p[i] & 0xff) >= 0x90)
1112                                 break;
1113                         more = 3; // 4-byte sequence, 0x100000-0x10ffff
1114                         break;
1115                 }
1116                 if (more) {
1117                         // check that all continuation bytes are valid
1118                         do {
1119                                 if ((p[i++] & 0xc0) != 0x80)
1120                                         break;
1121                         } while (--more);
1122                         if (!more)
1123                                 continue;
1124                 }
1125                 Input h = here_input ();
1126                 h.set (h.get_source_file (), h.start () + oldi, h.start () + i);
1127                 h.warning (_ ("non-UTF-8 input").c_str ());
1128         }
1129         return p;
1130 }
1131
1132
1133 /*
1134  urg, belong to string (_convert)
1135  and should be generalised 
1136  */
1137 void
1138 strip_leading_white (string&s)
1139 {
1140         ssize i = 0;
1141         for (;  i < s.length (); i++)
1142                 if (!isspace (s[i]))
1143                         break;
1144
1145         s = s.substr (i);
1146 }
1147
1148 void
1149 strip_trailing_white (string&s)
1150 {
1151         ssize i = s.length ();  
1152         while (i--) 
1153                 if (!isspace (s[i]))
1154                         break;
1155
1156         s = s.substr (0, i + 1);
1157 }
1158
1159
1160
1161 Lilypond_version oldest_version ("2.7.38");
1162
1163
1164 bool
1165 is_valid_version (string s)
1166 {
1167   Lilypond_version current ( MAJOR_VERSION "." MINOR_VERSION "." PATCH_LEVEL );
1168   Lilypond_version ver (s);
1169   if (int (ver) < oldest_version)
1170         {       
1171                 non_fatal_error (_f ("file too old: %s (oldest supported: %s)", ver.to_string (), oldest_version.to_string ()));
1172                 non_fatal_error (_ ("consider updating the input with the convert-ly script"));
1173                 return false;
1174         }
1175
1176   if (ver > current)
1177         {
1178                 non_fatal_error (_f ("program too old: %s (file requires: %s)",  current.to_string (), ver.to_string ()));
1179                 return false;
1180         }
1181   return true;
1182 }
1183         
1184
1185 /*
1186   substitute _
1187 */
1188 string
1189 lyric_fudge (string s)
1190 {
1191         size_t i=0;
1192
1193         while ((i = s.find ('_', i)) != string::npos)
1194         {
1195                 s[i++] = ' ';
1196         }
1197         return s;
1198 }
1199
1200 /*
1201 Convert "NUM/DEN" into a '(NUM . DEN) cons.
1202 */
1203 SCM
1204 scan_fraction (string frac)
1205 {
1206         ssize i = frac.find ('/');
1207         string left = frac.substr (0, i);
1208         string right = frac.substr (i + 1, (frac.length () - i + 1));
1209
1210         int n = String_convert::dec2int (left);
1211         int d = String_convert::dec2int (right);
1212         return scm_cons (scm_from_int (n), scm_from_int (d));
1213 }
1214
1215 SCM
1216 lookup_markup_command (string s)
1217 {
1218         SCM proc = ly_lily_module_constant ("lookup-markup-command");
1219         return scm_call_1 (proc, ly_string2scm (s));
1220 }
1221
1222 SCM
1223 lookup_markup_list_command (string s)
1224 {
1225         SCM proc = ly_lily_module_constant ("lookup-markup-list-command");
1226         return scm_call_1 (proc, ly_string2scm (s));
1227 }
1228
1229 /* Shut up lexer warnings.  */
1230 #if YY_STACK_USED
1231
1232 static void
1233 yy_push_state (int)
1234 {
1235 }
1236
1237 static void
1238 yy_pop_state ()
1239 {
1240 }
1241
1242 static int
1243 yy_top_state ()
1244 {
1245   return 0;
1246 }
1247
1248 static void
1249 silence_lexer_warnings ()
1250 {
1251    (void) yy_start_stack_ptr;
1252    (void) yy_start_stack_depth;
1253    (void) yy_start_stack;
1254    (void) yy_push_state;
1255    (void) yy_pop_state;
1256    (void) yy_top_state;
1257    (void) silence_lexer_warnings;
1258 }
1259 #endif