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