]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
* lily/my-lily-lexer.cc (My_lily_lexer): don't crash
[lilypond.git] / lily / lexer.ll
1 %{ // -*-Fundamental-*-
2 /*
3   lexer.ll -- implement the Flex lexer
4
5   source file of the LilyPond music typesetter
6
7   (c) 1996--2003 Han-Wen Nienhuys <hanwen@cs.uu.nl>
8            Jan Nieuwenhuizen <janneke@gnu.org>
9 */
10
11
12 /*
13   backup rules
14
15   after making a change to the lexer rules, run 
16       flex -b <this lexer file>
17   and make sure that 
18       lex.backup
19   contains no backup states, but only the reminder
20       Compressed tables always back up.
21  (don-t forget to rm lex.yy.cc :-)
22  */
23
24
25 #include <stdio.h>
26 #include <ctype.h>
27 #include <errno.h>
28
29 /* Flex >= 2.5.29 fix; FlexLexer.h's multiple include bracing breaks
30    when building the actual lexer.  */
31 #define LEXER_CC
32
33 #include <iostream>
34 using namespace std;
35
36 #include "source-file.hh"
37 #include "parse-scm.hh"
38 #include "lily-guile.hh"
39 #include "string.hh"
40 #include "string-convert.hh"
41 #include "my-lily-lexer.hh"
42 #include "input-file-results.hh"
43 #include "interval.hh"
44 #include "lily-guile.hh"
45 #include "parser.hh"
46 #include "warn.hh"
47 #include "main.hh"
48 #include "version.hh"
49 #include "lilypond-input-version.hh"
50 #include "translator-def.hh"
51 #include "identifier-smob.hh"
52
53 /*
54 RH 7 fix (?)
55 */
56 #define isatty HORRIBLEKLUDGE
57
58 void strip_trailing_white (String&);
59 void strip_leading_white (String&);
60 String lyric_fudge (String s);
61
62 SCM
63 lookup_markup_command (String s);
64
65 bool
66 valid_version_b (String s);
67
68
69
70 #define start_quote()   \
71         yy_push_state (quote);\
72         yylval.string = new String
73
74 #define yylval \
75         (*(YYSTYPE*)lexval)
76
77 #define YY_USER_ACTION  add_lexed_char (YYLeng ());
78 /*
79
80 LYRICS          ({AA}|{TEX})[^0-9 \t\n\f]*
81
82 */
83
84
85 SCM scan_fraction (String);
86 SCM (* scm_parse_error_handler) (void *);
87
88
89
90 %}
91
92 %option c++
93 %option noyywrap
94 %option nodefault
95 %option debug
96 %option yyclass="My_lily_lexer"
97 %option stack
98 %option never-interactive 
99 %option warn
100
101 %x renameinput
102 %x version
103 %x chords
104 %x incl
105 %x lyrics
106 %x notes
107 %x figures
108 %x quote
109 %x longcomment
110 %x markup 
111
112 A               [a-zA-Z]
113 AA              {A}|_
114 N               [0-9]
115 AN              {AA}|{N}
116 PUNCT           [?!:'`]
117 ACCENT          \\[`'"^]
118 NATIONAL        [\001-\006\021-\027\031\036\200-\377]
119 TEX             {AA}|-|{PUNCT}|{ACCENT}|{NATIONAL}
120 WORD            {A}{AN}*
121 ALPHAWORD       {A}+
122 DIGIT           {N}
123 UNSIGNED        {N}+
124 E_UNSIGNED      \\{N}+
125 FRACTION        {N}+\/{N}+
126 INT             -?{UNSIGNED}
127 REAL            ({INT}\.{N}*)|(-?\.{N}+)
128 KEYWORD         \\{WORD}
129 WHITE           [ \n\t\f\r]
130 HORIZONTALWHITE         [ \t]
131 BLACK           [^ \n\t\f\r]
132 RESTNAME        [rs]
133 NOTECOMMAND     \\{A}+
134 MARKUPCOMMAND   \\({A}|[-_])+
135 LYRICS          ({AA}|{TEX})[^0-9 \t\n\f]*
136 ESCAPED         [nt\\'"]
137 EXTENDER        __
138 HYPHEN          --
139 %%
140
141
142 <*>\r           {
143         // windows-suck-suck-suck
144 }
145
146 <INITIAL,chords,incl,markup,lyrics,notes,figures>{
147   "%{"  {
148         yy_push_state (longcomment);
149   }
150   %[^{\n].*\n   {
151   }
152   %[^{\n]       { // backup rule
153   }
154   %\n   {
155   }
156   %[^{\n].*     {
157   }
158   {WHITE}+      {
159
160   }
161 }
162
163 <INITIAL,chords,lyrics,notes,figures>\\version{WHITE}*  {
164         yy_push_state (version);
165 }
166 <INITIAL,chords,lyrics,notes,figures>\\renameinput{WHITE}*      {
167         yy_push_state (renameinput);
168 }
169 <version>\"[^"]*\"     { /* got the version number */
170         String s (YYText ()+1);
171         s = s.left_string (s.index_last ('\"'));
172
173         yy_pop_state();
174          if (!valid_version_b (s))
175                 return INVALID;
176 }
177 <renameinput>\"[^"]*\"     { /* got the version number */
178         String s (YYText ()+1);
179         s = s.left_string (s.index_last ('\"'));
180
181         yy_pop_state();
182         this->here_input().source_file_->name_ = s;
183         scm_module_define (gh_car (scopes_),
184                      ly_symbol2scm ("input-file-name"),
185                      scm_makfrom0str (s.to_str0()));
186
187 }
188
189 <version>.      {
190         LexerError ("No quoted string found after \\version");
191         yy_pop_state ();
192 }
193 <renameinput>.  {
194         LexerError ("No quoted string found after \\renameinput");
195         yy_pop_state ();
196 }
197 <longcomment>{
198         [^\%]*          {
199         }
200         \%*[^}%]*               {
201
202         }
203         "%"+"}"         {
204                 yy_pop_state ();
205         }
206         <<EOF>>         {
207                 LexerError (_ ("EOF found inside a comment").to_str0 ());
208                 if (! close_input ()) 
209                   yyterminate (); // can't move this, since it actually rets a YY_NULL
210         }
211 }
212
213
214 <INITIAL,chords,lyrics,notes,figures>\\maininput           {
215         if (!main_input_b_)
216         {
217                 start_main_input ();
218                 main_input_b_ = true;
219         }
220         else
221                 error (_ ("\\maininput disallowed outside init files"));
222 }
223
224 <INITIAL,chords,lyrics,figures,notes>\\include           {
225         yy_push_state (incl);
226 }
227 <incl>\"[^"]*\";?   { /* got the include file name */
228         String s (YYText ()+1);
229         s = s.left_string (s.index_last ('"'));
230
231         new_input (s, &global_input_file->sources_ );
232         yy_pop_state ();
233 }
234 <incl>\\{BLACK}*;?{WHITE} { /* got the include identifier */
235         String s = YYText () + 1;
236         strip_trailing_white (s);
237         if (s.length () && (s[s.length () - 1] == ';'))
238           s = s.left_string (s.length () - 1);
239
240         SCM sid = lookup_identifier (s);
241         if (gh_string_p (sid)) {
242                 new_input (ly_scm2string (sid), &global_input_file->sources_);
243                 yy_pop_state ();
244         } else { 
245             String msg (_f ("wrong or undefined identifier: `%s'", s ));
246
247             LexerError (msg.to_str0 ());
248             SCM err = scm_current_error_port ();
249             scm_puts ("This value was found in the table: ", err);
250             scm_display (sid, err);
251           }
252 }
253 <incl>\"[^"]*   { // backup rule
254         error (_ ("Missing end quote"));
255         exit (1);
256 }
257 <chords,notes,figures>{RESTNAME}        {
258         const char *s = YYText ();
259         yylval.scm = scm_makfrom0str (s);
260         return RESTNAME;
261 }
262 <chords,notes,figures>R         {
263         return MULTI_MEASURE_REST;
264 }
265 <INITIAL,chords,lyrics,notes,figures>\\\${BLACK}*{WHITE}        {
266         String s=YYText () + 2;
267         s=s.left_string (s.length () - 1);
268         return scan_escaped_word (s); 
269 }
270 <INITIAL,chords,lyrics,notes,figures>\${BLACK}*{WHITE}          {
271         String s=YYText () + 1;
272         s=s.left_string (s.length () - 1);
273         return scan_bare_word (s);
274 }
275 <INITIAL,chords,lyrics,notes,figures>\\\${BLACK}*               { // backup rule
276         error (_("white expected"));
277         exit (1);
278 }
279 <INITIAL,chords,lyrics,notes,figures>\${BLACK}*         { // backup rule
280         error (_("white expected"));
281         exit (1);
282 }
283
284 <INITIAL,markup,chords,lyrics,notes,figures>#   { //embedded scm
285         //char const* s = YYText () + 1;
286         char const* s = here_str0 ();
287         int n = 0;
288         if (main_input_b_ && safe_global_b) {
289                 error (_ ("Can't evaluate Scheme in safe mode"));
290                 yylval.scm =  SCM_EOL;
291                 return SCM_T;
292         }
293         SCM sval = ly_parse_scm (s, &n, here_input());
294         if (sval == SCM_UNDEFINED)
295                 {
296                 sval = SCM_UNSPECIFIED;
297                 errorlevel_ = 1;
298                 }
299
300         for (int i=0; i < n; i++)
301         {
302                 yyinput ();
303         }
304         char_count_stack_.top () += n;
305
306         if (unpack_identifier (sval) != SCM_UNDEFINED)
307         {
308                 yylval.scm = unpack_identifier(sval);
309                 return identifier_type (yylval.scm);
310         }
311                 
312         yylval.scm = sval;
313         return SCM_T;
314 }
315 <INITIAL,notes,markup>{ 
316         \<\<   {
317                 return CHORD_OPEN;
318         }
319         \>\>   {
320                 return CHORD_CLOSE;
321         }
322 }
323 <figures>{
324         _       {
325                 return FIGURE_SPACE;
326         }
327         \>              {
328                 return FIGURE_CLOSE;
329         }
330         \<      {
331                 return FIGURE_OPEN;
332         }
333 }
334
335 <notes,figures>{
336         {ALPHAWORD}     {
337                 return scan_bare_word (YYText ());
338         }
339
340         {NOTECOMMAND}   {
341                 return scan_escaped_word (YYText () + 1); 
342         }
343         {FRACTION}      {
344                 yylval.scm =  scan_fraction (YYText ());
345                 return FRACTION;
346         }
347
348         {DIGIT}         {
349                 yylval.i = String_convert::dec2int (String (YYText ()));
350                 return DIGIT;
351         }
352         {UNSIGNED}              {
353                 yylval.i = String_convert::dec2int (String (YYText ()));
354                 return UNSIGNED;
355         }
356         {E_UNSIGNED}    {
357                 yylval.i = String_convert::dec2int (String (YYText () +1));
358                 return E_UNSIGNED;
359         }
360
361         \" {
362                 start_quote ();
363         }
364 }
365
366 \"              {
367         start_quote ();
368 }
369 <quote>{
370         \\{ESCAPED}     {
371                 *yylval.string += to_string (escaped_char (YYText ()[1]));
372         }
373         [^\\"]+ {
374                 *yylval.string += YYText ();
375         }
376         \"      {
377
378                 yy_pop_state ();
379
380                 /* yylval is union. Must remember STRING before setting SCM*/
381                 String *sp = yylval.string;
382                 yylval.scm = scm_makfrom0str (sp->to_str0 ());
383                 delete sp;
384                 return STRING;
385         }
386         .       {
387                 *yylval.string += YYText ();
388         }
389 }
390
391 <lyrics>{
392         \" {
393                 start_quote ();
394         }
395         {FRACTION}      {
396                 yylval.scm =  scan_fraction (YYText ());
397                 return FRACTION;
398         }
399         {UNSIGNED}              {
400                 yylval.i = String_convert::dec2int (String (YYText ()));
401                 return UNSIGNED;
402         }
403         {NOTECOMMAND}   {
404                 return scan_escaped_word (YYText () + 1);
405         }
406         {LYRICS} {
407                 /* ugr. This sux. */
408                 String s (YYText ()); 
409                 if (s == "__")
410                         return yylval.i = EXTENDER;
411                 if (s == "--")
412                         return yylval.i = HYPHEN;
413                 s = lyric_fudge (s);
414
415                 char c = s[s.length () - 1];
416                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
417                         here_input ().warning (
418                                 _ ("Brace found at end of lyric.  Did you forget a space?"));
419                 yylval.scm = scm_makfrom0str (s.to_str0 ());
420
421
422                 return STRING;
423         }
424         . {
425                 return YYText ()[0];
426         }
427 }
428 <chords>{
429         {ALPHAWORD}     {
430                 return scan_bare_word (YYText ());
431         }
432         {NOTECOMMAND}   {
433                 return scan_escaped_word (YYText () + 1);
434         }
435         {FRACTION}      {
436                 yylval.scm =  scan_fraction (YYText ());
437                 return FRACTION;
438         }
439         {UNSIGNED}              {
440                 yylval.i = String_convert::dec2int (String (YYText ()));
441                 return UNSIGNED;
442         }
443         \" {
444                 start_quote ();
445         }
446         -  {
447                 return CHORD_MINUS;
448         }
449         :  {
450                 return CHORD_COLON;
451         }
452         \/\+ {
453                 return CHORD_BASS;
454         }
455         \/  {
456                 return CHORD_SLASH;
457         }
458         \^  {
459                 return CHORD_CARET;
460         }
461         . {
462                 return YYText ()[0];
463         }
464 }
465
466
467 <markup>{
468         \" {
469                 start_quote ();
470         }
471         {MARKUPCOMMAND} {
472                 String str (YYText() + 1);
473                 SCM s = lookup_markup_command (str);
474
475                 if (gh_pair_p (s) && gh_symbol_p (gh_cdr (s)) ) {
476                         yylval.scm = gh_car(s);
477                         SCM tag = gh_cdr(s);
478                         if (tag == ly_symbol2scm("markup0"))
479                                 return MARKUP_HEAD_MARKUP0;
480                         else if (tag == ly_symbol2scm ("markup0-markup1"))
481                                 return MARKUP_HEAD_MARKUP0_MARKUP1;
482                         else if (tag == ly_symbol2scm ("markup-list0"))
483                                 return MARKUP_HEAD_LIST0;
484                         else if (tag == ly_symbol2scm ("scheme0"))
485                                 return MARKUP_HEAD_SCM0;
486                         else if (tag == ly_symbol2scm ("scheme0-scheme1"))
487                                 return MARKUP_HEAD_SCM0_SCM1;
488                         else if (tag == ly_symbol2scm ("scheme0-markup1"))
489                                 return MARKUP_HEAD_SCM0_MARKUP1;
490                         else if (tag == ly_symbol2scm ("scheme0-scheme1-markup2"))
491                                 return MARKUP_HEAD_SCM0_SCM1_MARKUP2;
492                         else if (tag == ly_symbol2scm ("scheme0-scheme1-scheme2"))
493                                 return MARKUP_HEAD_SCM0_SCM1_SCM2;
494                         else {
495                                 programming_error ("No parser tag defined for this signature. Abort"); 
496                                 ly_display_scm (s);
497                                 assert(false);
498                         }
499                 } else
500                         return scan_escaped_word (str);
501         }
502         [{}]    {
503                 return YYText()[0];
504         }
505         [^#{}"\\ \t\n\f]+ {
506                 String s (YYText ()); 
507
508                 char c = s[s.length () - 1];
509                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
510                         here_input ().warning (
511                                 _ ("Brace found at end of markup.  Did you forget a space?"));
512                 yylval.scm = scm_makfrom0str (s.to_str0 ());
513
514
515                 return STRING;
516         }
517         .  {
518                 return YYText()[0];
519         }
520 }
521
522 <<EOF>> {
523
524
525         if (! close_input ()) { 
526           yyterminate (); // can't move this, since it actually rets a YY_NULL
527         }
528 }
529
530
531 {WORD}  {
532         return scan_bare_word (YYText ());
533 }
534 {KEYWORD}       {
535         return scan_escaped_word (YYText () + 1);
536 }
537 {REAL}          {
538         Real r;
539         int cnv=sscanf (YYText (), "%lf", &r);
540         assert (cnv == 1);
541
542         yylval.scm = gh_double2scm (r);
543         return REAL;
544 }
545
546 {UNSIGNED}      {
547         yylval.i = String_convert::dec2int (String (YYText ()));
548         return UNSIGNED;
549 }
550
551
552 [{}]    {
553
554         return YYText ()[0];
555 }
556 [*:=]           {
557         char c = YYText ()[0];
558
559         return c;
560 }
561
562 <INITIAL,notes,figures>.        {
563         return YYText ()[0];
564 }
565
566 <INITIAL,lyrics,notes,figures>\\. {
567     char c= YYText ()[1];
568
569     switch (c) {
570     case '>':
571         return E_BIGGER;
572     case '<':
573         return E_SMALLER;
574     case '!':
575         return E_EXCLAMATION;
576     case '(':
577         return E_OPEN;
578     case ')':
579         return E_CLOSE;
580     case '[':
581         return E_LEFTSQUARE;
582     case ']':
583         return E_RIGHTSQUARE;
584     case '~':
585         return E_TILDE;
586     case '\\':
587         return E_BACKSLASH;
588
589     default:
590         return E_CHAR;
591     }
592 }
593
594 <*>.            {
595         String msg = _f ("invalid character: `%c'", YYText ()[0]);
596         LexerError (msg.to_str0 ());
597         return YYText ()[0];
598 }
599
600 %%
601
602 void
603 My_lily_lexer::push_note_state ()
604 {
605         yy_push_state (notes);
606 }
607
608 void
609 My_lily_lexer::push_figuredbass_state()
610 {
611         yy_push_state (figures);
612 }
613 void
614 My_lily_lexer::push_chord_state ()
615 {
616         yy_push_state (chords);
617 }
618
619 void
620 My_lily_lexer::push_lyric_state ()
621 {
622         yy_push_state (lyrics);
623 }
624
625 void
626 My_lily_lexer::push_markup_state ()
627 {
628         yy_push_state (markup);
629 }
630
631 void
632 My_lily_lexer::pop_state ()
633 {
634         yy_pop_state ();
635 }
636
637 int
638 My_lily_lexer::identifier_type(SCM sid)
639 {
640         int k = try_special_identifiers(&yylval.scm , sid);
641         return k >= 0  ? k : SCM_IDENTIFIER;
642 }
643
644
645 int
646 My_lily_lexer::scan_escaped_word (String str)
647 {
648         // use more SCM for this.
649
650         SCM sym = ly_symbol2scm (str.to_str0 ());
651
652         int l = lookup_keyword (str);
653         if (l != -1) {
654                 return l;
655         }
656         SCM sid = lookup_identifier (str);
657         if (sid != SCM_UNDEFINED)
658         {
659                 yylval.scm = sid;
660                 return identifier_type (sid);
661         }
662
663         if ((YYSTATE != notes) && (YYSTATE != chords)) {
664                 SCM pitch = scm_hashq_get_handle (pitchname_tab_, sym);
665                 
666                 if (gh_pair_p (pitch))
667                 {
668                         yylval.scm = ly_cdr (pitch);
669                         return NOTENAME_PITCH;
670                 }
671         }
672         String msg (_f ("unknown escaped string: `\\%s'", str));        
673         LexerError (msg.to_str0 ());
674
675         yylval.scm = scm_makfrom0str (str.to_str0 ());
676
677         return STRING;
678 }
679
680 int
681 My_lily_lexer::scan_bare_word (String str)
682 {
683         SCM sym = ly_symbol2scm (str.to_str0 ());
684         if ((YYSTATE == notes) || (YYSTATE == chords)) {
685                 SCM pitch = scm_hashq_get_handle (pitchname_tab_, sym);
686                 if (gh_pair_p (pitch)) {
687                     yylval.scm = ly_cdr (pitch);
688                     return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
689                 } else if ((pitch = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
690                 {
691                     yylval.scm = ly_cdr (pitch);
692                     return CHORD_MODIFIER;
693                 }
694         }
695
696         yylval.scm = scm_makfrom0str (str.to_str0 ());
697         return STRING;
698 }
699
700 bool
701 My_lily_lexer::note_state_b () const
702 {
703         return YY_START == notes;
704 }
705
706 bool
707 My_lily_lexer::chord_state_b () const
708 {
709         return YY_START == chords;
710 }
711
712 bool
713 My_lily_lexer::lyric_state_b () const
714 {
715         return YY_START == lyrics;
716 }
717
718 bool
719 My_lily_lexer::figure_state_b () const
720 {
721         return YY_START == figures;
722 }
723
724 /*
725  urg, belong to String (_convert)
726  and should be generalised 
727  */
728 void
729 strip_leading_white (String&s)
730 {
731         int i=0;
732         for (;  i < s.length (); i++) 
733                 if (!isspace (s[i]))
734                         break;
735
736         s = s.nomid_string (0, i);
737 }
738
739 void
740 strip_trailing_white (String&s)
741 {
742         int i=s.length ();      
743         while (i--) 
744                 if (!isspace (s[i]))
745                         break;
746
747         s = s.left_string (i+1);
748 }
749
750
751
752 /* 1.9.0 == postfix articulations */ 
753 Lilypond_version oldest_version ("1.9.0");
754
755
756 bool
757 valid_version_b (String s)
758 {
759   Lilypond_version current ( MAJOR_VERSION "." MINOR_VERSION "." PATCH_LEVEL );
760   Lilypond_version ver (s);
761   if (! ((ver >= oldest_version) && (ver <= current)))
762         {       
763                 non_fatal_error (_f ("Incorrect lilypond version: %s (%s, %s)", ver.to_string (), oldest_version.to_string (), current.to_string ()));
764                 non_fatal_error (_ ("Consider updating the input with the convert-ly script")); 
765                 return false;
766     }
767   return true;
768 }
769         
770
771 /*
772   substittute _ adn \,
773 */
774 String
775 lyric_fudge (String s)
776 {
777   char  * chars  =s.get_copy_str0 ();
778
779   for (char * p = chars; *p ; p++)
780     {
781       if (*p == '_' && (p == chars || *(p-1) != '\\'))
782         *p = ' ';
783     }
784   
785   s = String (chars);
786   delete[] chars;
787
788   int i =0;     
789   if ((i=s.index ("\\,")) != -1)   // change "\," to TeX's "\c "
790     {
791       * (s.get_str0 () + i + 1) = 'c';
792       s = s.left_string (i+2) + " " + s.right_string (s.length ()-i-2);
793     }
794
795   return s;
796 }
797
798 /*
799 Convert "NUM/DEN" into a '(NUM . DEN) cons.
800 */
801 SCM
802 scan_fraction (String frac)
803 {
804         int i = frac.index ('/');
805         int l = frac.length ();
806         String left = frac.left_string (i);
807         String right = frac.right_string (l - i - 1);
808
809         int n = String_convert::dec2int (left);
810         int d = String_convert::dec2int (right);
811         return gh_cons (gh_int2scm (n), gh_int2scm (d));
812 }
813
814 // Breaks for flex 2.5.31
815 #if 0
816 /* avoid silly flex induced gcc warnings */
817 static void yy_push_state (int) {;}
818 static void yy_pop_state () {;}
819 static int yy_top_state () { return 0; }
820
821 static void
822 avoid_silly_flex_induced_gcc_warnings ()
823 {
824         (void)yy_start_stack_ptr;
825         (void)yy_start_stack_depth;
826         (void)yy_start_stack;
827         yy_push_state (0);
828         yy_pop_state ();
829         yy_top_state ();
830         avoid_silly_flex_induced_gcc_warnings ();
831 }
832 #endif
833
834 SCM
835 lookup_markup_command (String s)
836 {
837         static SCM proc ;
838         if (!proc)
839                 proc = scm_c_eval_string ("lookup-markup-command");
840
841         return scm_call_1 (proc, scm_makfrom0str (s.to_str0 ()));
842 }