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