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