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