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