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