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