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