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