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