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