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