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