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