]> git.donarmstrong.com Git - lilypond.git/blob - lily/lexer.ll
* lily/include/lily-guile.hh: is_x -> ly_c_X_p naming.
[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--2004 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 "interval.hh"
43 #include "lily-guile.hh"
44 #include "parser.hh"
45 #include "warn.hh"
46 #include "main.hh"
47 #include "version.hh"
48 #include "lilypond-input-version.hh"
49 #include "context-def.hh"
50 #include "identifier-smob.hh"
51
52 /*
53 RH 7 fix (?)
54 */
55 #define isatty HORRIBLEKLUDGE
56
57 void strip_trailing_white (String&);
58 void strip_leading_white (String&);
59 String lyric_fudge (String s);
60
61 SCM lookup_markup_command (String s);
62 bool is_valid_version (String s);
63
64
65 #define start_quote()   \
66         yy_push_state (quote);\
67         yylval.string = new String
68
69 #define yylval \
70         (*(YYSTYPE*)lexval)
71
72 #define YY_USER_ACTION  add_lexed_char (YYLeng ());
73 /*
74
75 LYRICS          ({AA}|{TEX})[^0-9 \t\n\f]*
76
77 */
78
79
80 SCM scan_fraction (String);
81 SCM (* scm_parse_error_handler) (void *);
82
83
84
85 %}
86
87 %option c++
88 %option noyywrap
89 %option nodefault
90 %option debug
91 %option yyclass="My_lily_lexer"
92 %option stack
93 %option never-interactive 
94 %option warn
95
96 %x encoding
97 %x renameinput
98 %x version
99 %x chords
100 %x incl
101 %x lyrics
102 %x notes
103 %x figures
104 %x quote
105 %x longcomment
106 %x markup 
107
108 A               [a-zA-Z]
109 AA              {A}|_
110 N               [0-9]
111 AN              {AA}|{N}
112 PUNCT           [?!:'`]
113 ACCENT          \\[`'"^]
114 NATIONAL        [\001-\006\021-\027\031\036\200-\377]
115 TEX             {AA}|-|{PUNCT}|{ACCENT}|{NATIONAL}
116 WORD            {A}{AN}*
117 ALPHAWORD       {A}+
118 DIGIT           {N}
119 UNSIGNED        {N}+
120 E_UNSIGNED      \\{N}+
121 FRACTION        {N}+\/{N}+
122 INT             -?{UNSIGNED}
123 REAL            ({INT}\.{N}*)|(-?\.{N}+)
124 KEYWORD         \\{WORD}
125 WHITE           [ \n\t\f\r]
126 HORIZONTALWHITE         [ \t]
127 BLACK           [^ \n\t\f\r]
128 RESTNAME        [rs]
129 NOTECOMMAND     \\{A}+
130 MARKUPCOMMAND   \\({A}|[-_])+
131 LYRICS          ({AA}|{TEX})[^0-9 \t\n\r\f]*
132 ESCAPED         [nt\\'"]
133 EXTENDER        __
134 HYPHEN          --
135 %%
136
137
138 <*>\r           {
139         // windows-suck-suck-suck
140 }
141
142 <INITIAL,chords,incl,markup,lyrics,notes,figures>{
143   "%{"  {
144         yy_push_state (longcomment);
145   }
146   %[^{\n\r].*[\n\r]     {
147   }
148   %[^{\n\r]     { // backup rule
149   }
150   %[\n\r]       {
151   }
152   %[^{\n\r].*   {
153   }
154   {WHITE}+      {
155
156   }
157 }
158
159 <INITIAL>\\encoding{WHITE}*     {
160         yy_push_state (encoding);
161 }
162 <INITIAL,chords,lyrics,notes,figures>\\version{WHITE}*  {
163         yy_push_state (version);
164 }
165 <INITIAL,chords,lyrics,notes,figures>\\renameinput{WHITE}*      {
166         yy_push_state (renameinput);
167 }
168 <encoding>\"[^"]*\"     {
169         String s (YYText () + 1);
170         s = s.left_string (s.index_last ('\"'));
171         set_encoding (s);
172         yy_pop_state ();
173 }
174 <version>\"[^"]*\"     { /* got the version number */
175         String s (YYText () + 1);
176         s = s.left_string (s.index_last ('\"'));
177
178         yy_pop_state ();
179         if (!is_valid_version (s))
180                 return INVALID;
181 }
182 <renameinput>\"[^"]*\"     {
183         String s (YYText ()+1);
184         s = s.left_string (s.index_last ('\"'));
185
186         yy_pop_state();
187         this->here_input().source_file_->name_ = s;
188         progress_indication ("\n");
189         progress_indication (_f ("input renamed to: `%s'", s.to_str0 ()));
190         progress_indication ("\n");
191         scm_module_define (ly_car (scopes_),
192                      ly_symbol2scm ("input-file-name"),
193                      scm_makfrom0str (s.to_str0()));
194
195 }
196 <encoding>.     {
197         LexerError (_ ("No quoted string found after \\encoding").to_str0 ());
198         yy_pop_state ();
199 }
200 <version>.      {
201         LexerError (_ ("No quoted string found after \\version").to_str0 ());
202         yy_pop_state ();
203 }
204 <renameinput>.  {
205         LexerError (_ ("No quoted string found after \\renameinput").to_str0 ());
206         yy_pop_state ();
207 }
208 <longcomment>{
209         [^\%]*          {
210         }
211         \%*[^}%]*               {
212
213         }
214         "%"+"}"         {
215                 yy_pop_state ();
216         }
217         <<EOF>>         {
218                 LexerError (_ ("EOF found inside a comment").to_str0 ());
219                 main_input_b_ = false;
220                 if (! close_input ()) 
221                   yyterminate (); // can't move this, since it actually rets a YY_NULL
222         }
223 }
224
225
226 <INITIAL,chords,lyrics,notes,figures>\\maininput           {
227         if (!main_input_b_)
228         {
229                 start_main_input ();
230                 main_input_b_ = true;
231         }
232         else
233                 error (_ ("\\maininput not allowed outside init files"));
234 }
235
236 <INITIAL,chords,lyrics,figures,notes>\\include           {
237         yy_push_state (incl);
238 }
239 <incl>\"[^"]*\";?   { /* got the include file name */
240         String s (YYText ()+1);
241         s = s.left_string (s.index_last ('"'));
242
243         new_input (s, sources_);
244         yy_pop_state ();
245 }
246 <incl>\\{BLACK}*;?{WHITE} { /* got the include identifier */
247         String s = YYText () + 1;
248         strip_trailing_white (s);
249         if (s.length () && (s[s.length () - 1] == ';'))
250           s = s.left_string (s.length () - 1);
251
252         SCM sid = lookup_identifier (s);
253         if (ly_c_string_p (sid)) {
254                 new_input (ly_scm2string (sid), sources_);
255                 yy_pop_state ();
256         } else { 
257             String msg (_f ("wrong or undefined identifier: `%s'", s ));
258
259             LexerError (msg.to_str0 ());
260             SCM err = scm_current_error_port ();
261             scm_puts ("This value was found in the table: ", err);
262             scm_display (sid, err);
263           }
264 }
265 <incl>\"[^"]*   { // backup rule
266         error (_ ("Missing end quote"));
267         exit (1);
268 }
269 <chords,notes,figures>{RESTNAME}        {
270         const char *s = YYText ();
271         yylval.scm = scm_makfrom0str (s);
272         return RESTNAME;
273 }
274 <chords,notes,figures>R         {
275         return MULTI_MEASURE_REST;
276 }
277 <INITIAL,markup,chords,lyrics,notes,figures>#   { //embedded scm
278         //char const* s = YYText () + 1;
279         char const* s = here_str0 ();
280         int n = 0;
281         SCM sval = ly_parse_scm (s, &n, here_input (),
282                 safe_global_b && main_input_b_);
283
284         if (sval == SCM_UNDEFINED)
285         {
286                 sval = SCM_UNSPECIFIED;
287                 errorlevel_ = 1;
288         }
289
290         for (int i=0; i < n; i++)
291         {
292                 yyinput ();
293         }
294         char_count_stack_.top () += n;
295
296         if (unpack_identifier (sval) != SCM_UNDEFINED)
297         {
298                 yylval.scm = unpack_identifier(sval);
299                 return identifier_type (yylval.scm);
300         }
301                 
302         yylval.scm = sval;
303         return SCM_T;
304 }
305 <INITIAL,notes,lyrics>{ 
306         \<\<   {
307                 return LESSLESS;
308         }
309         \>\>   {
310                 return MOREMORE;
311         }
312 }
313 <figures>{
314         _       {
315                 return FIGURE_SPACE;
316         }
317         \>              {
318                 return FIGURE_CLOSE;
319         }
320         \<      {
321                 return FIGURE_OPEN;
322         }
323 }
324
325 <notes,figures>{
326         {ALPHAWORD}     {
327                 return scan_bare_word (YYText ());
328         }
329
330         {NOTECOMMAND}   {
331                 return scan_escaped_word (YYText () + 1); 
332         }
333         {FRACTION}      {
334                 yylval.scm =  scan_fraction (YYText ());
335                 return FRACTION;
336         }
337
338         {DIGIT}         {
339                 yylval.i = String_convert::dec2int (String (YYText ()));
340                 return DIGIT;
341         }
342         {UNSIGNED}              {
343                 yylval.i = String_convert::dec2int (String (YYText ()));
344                 return UNSIGNED;
345         }
346         {E_UNSIGNED}    {
347                 yylval.i = String_convert::dec2int (String (YYText () +1));
348                 return E_UNSIGNED;
349         }
350
351         \" {
352                 start_quote ();
353         }
354 }
355
356 \"              {
357         start_quote ();
358 }
359 <quote>{
360         \\{ESCAPED}     {
361                 *yylval.string += to_string (escaped_char (YYText ()[1]));
362         }
363         [^\\"]+ {
364                 *yylval.string += YYText ();
365         }
366         \"      {
367
368                 yy_pop_state ();
369
370                 /* yylval is union. Must remember STRING before setting SCM*/
371                 String *sp = yylval.string;
372                 yylval.scm = scm_makfrom0str (sp->to_str0 ());
373                 delete sp;
374                 return STRING;
375         }
376         .       {
377                 *yylval.string += YYText ();
378         }
379 }
380
381 <lyrics>{
382         \" {
383                 start_quote ();
384         }
385         {FRACTION}      {
386                 yylval.scm =  scan_fraction (YYText ());
387                 return FRACTION;
388         }
389         {UNSIGNED}              {
390                 yylval.i = String_convert::dec2int (String (YYText ()));
391                 return UNSIGNED;
392         }
393         {NOTECOMMAND}   {
394                 return scan_escaped_word (YYText () + 1);
395         }
396         {LYRICS} {
397                 /* ugr. This sux. */
398                 String s (YYText ()); 
399                 if (s == "__")
400                         return yylval.i = EXTENDER;
401                 if (s == "--")
402                         return yylval.i = HYPHEN;
403                 s = lyric_fudge (s);
404
405                 char c = s[s.length () - 1];
406                 if (c == '{' ||  c == '}') // brace open is for not confusing dumb tools.
407                         here_input ().warning (
408                                 _ ("Brace found at end of lyric.  Did you forget a space?"));
409                 yylval.scm = scm_makfrom0str (s.to_str0 ());
410
411
412                 return STRING;
413         }
414         . {
415                 return YYText ()[0];
416         }
417 }
418 <chords>{
419         {ALPHAWORD}     {
420                 return scan_bare_word (YYText ());
421         }
422         {NOTECOMMAND}   {
423                 return scan_escaped_word (YYText () + 1);
424         }
425         {FRACTION}      {
426                 yylval.scm =  scan_fraction (YYText ());
427                 return FRACTION;
428         }
429         {UNSIGNED}              {
430                 yylval.i = String_convert::dec2int (String (YYText ()));
431                 return UNSIGNED;
432         }
433         \" {
434                 start_quote ();
435         }
436         -  {
437                 return CHORD_MINUS;
438         }
439         :  {
440                 return CHORD_COLON;
441         }
442         \/\+ {
443                 return CHORD_BASS;
444         }
445         \/  {
446                 return CHORD_SLASH;
447         }
448         \^  {
449                 return CHORD_CARET;
450         }
451         . {
452                 return YYText ()[0];
453         }
454 }
455
456
457 <markup>{
458         \" {
459                 start_quote ();
460         }
461         \< {
462                 return '<';
463         }
464         \> {
465                 return '>';
466         }
467         {MARKUPCOMMAND} {
468                 String str (YYText () + 1);
469                 SCM s = lookup_markup_command (str);
470
471                 if (ly_c_pair_p (s) && ly_c_symbol_p (ly_cdr (s)) ) {
472                         yylval.scm = ly_car(s);
473                         SCM tag = ly_cdr(s);
474                         if (tag == ly_symbol2scm("markup0"))
475                                 return MARKUP_HEAD_MARKUP0;
476                         if (tag == ly_symbol2scm("empty"))
477                                 return MARKUP_HEAD_EMPTY;
478                         else if (tag == ly_symbol2scm ("markup0-markup1"))
479                                 return MARKUP_HEAD_MARKUP0_MARKUP1;
480                         else if (tag == ly_symbol2scm ("markup-list0"))
481                                 return MARKUP_HEAD_LIST0;
482                         else if (tag == ly_symbol2scm ("scheme0"))
483                                 return MARKUP_HEAD_SCM0;
484                         else if (tag == ly_symbol2scm ("scheme0-scheme1"))
485                                 return MARKUP_HEAD_SCM0_SCM1;
486                         else if (tag == ly_symbol2scm ("scheme0-markup1"))
487                                 return MARKUP_HEAD_SCM0_MARKUP1;
488                         else if (tag == ly_symbol2scm ("scheme0-scheme1-markup2"))
489                                 return MARKUP_HEAD_SCM0_SCM1_MARKUP2;
490                         else if (tag == ly_symbol2scm ("scheme0-scheme1-scheme2"))
491                                 return MARKUP_HEAD_SCM0_SCM1_SCM2;
492                         else {
493                                 programming_error ("No parser tag defined for this signature. Abort"); 
494                                 ly_display_scm (s);
495                                 assert(false);
496                         }
497                 } else
498                         return scan_escaped_word (str);
499         }
500         [{}]    {
501                 return YYText ()[0];
502         }
503         [^#{}"\\ \t\n\r\f]+ {
504                 String s (YYText ()); 
505
506                 char c = s[s.length () - 1];
507                 /* brace open is for not confusing dumb tools.  */
508                 if (c == '{' ||  c == '}')
509                         here_input ().warning (
510                                 _ ("Brace found at end of markup.  Did you forget a space?"));
511                 yylval.scm = scm_makfrom0str (s.to_str0 ());
512
513
514                 return STRING;
515         }
516         .  {
517                 return YYText()[0];
518         }
519 }
520
521 <<EOF>> {
522         main_input_b_ = false;
523         if (! close_input ()) { 
524           yyterminate (); // can't move this, since it actually rets a YY_NULL
525         }
526 }
527
528
529 {WORD}  {
530         return scan_bare_word (YYText ());
531 }
532 {KEYWORD}       {
533         return scan_escaped_word (YYText () + 1);
534 }
535 {REAL}          {
536         Real r;
537         int cnv=sscanf (YYText (), "%lf", &r);
538         assert (cnv == 1);
539
540         yylval.scm = scm_make_real (r);
541         return REAL;
542 }
543
544 {UNSIGNED}      {
545         yylval.i = String_convert::dec2int (String (YYText ()));
546         return UNSIGNED;
547 }
548
549
550 [{}]    {
551
552         return YYText ()[0];
553 }
554 [*:=]           {
555         char c = YYText ()[0];
556
557         return c;
558 }
559
560 <INITIAL,notes,figures>.        {
561         return YYText ()[0];
562 }
563
564 <INITIAL,lyrics,notes,figures>\\. {
565     char c= YYText ()[1];
566
567     switch (c) {
568     case '>':
569         return E_BIGGER;
570     case '<':
571         return E_SMALLER;
572     case '!':
573         return E_EXCLAMATION;
574     case '(':
575         return E_OPEN;
576     case ')':
577         return E_CLOSE;
578     case '[':
579         return E_LEFTSQUARE;
580     case ']':
581         return E_RIGHTSQUARE;
582     case '~':
583         return E_TILDE;
584     case '\\':
585         return E_BACKSLASH;
586
587     default:
588         return E_CHAR;
589     }
590 }
591
592 <*>.            {
593         String msg = _f ("invalid character: `%c'", YYText ()[0]);
594         LexerError (msg.to_str0 ());
595         return YYText ()[0];
596 }
597
598 %%
599
600 void
601 My_lily_lexer::push_note_state (SCM tab)
602 {
603         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
604         yy_push_state (notes);
605 }
606
607 void
608 My_lily_lexer::push_figuredbass_state()
609 {
610         yy_push_state (figures);
611 }
612 void
613 My_lily_lexer::push_chord_state (SCM tab)
614 {
615         pitchname_tab_stack_ = scm_cons (tab, pitchname_tab_stack_);
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         if (YYSTATE == notes || YYSTATE == chords)
635                 pitchname_tab_stack_ = ly_cdr (pitchname_tab_stack_);
636         yy_pop_state ();
637 }
638
639 int
640 My_lily_lexer::identifier_type (SCM sid)
641 {
642         int k = try_special_identifiers (&yylval.scm , sid);
643         return k >= 0  ? k : SCM_IDENTIFIER;
644 }
645
646
647 int
648 My_lily_lexer::scan_escaped_word (String str)
649 {
650         // use more SCM for this.
651
652 //      SCM sym = ly_symbol2scm (str.to_str0 ());
653
654         int l = lookup_keyword (str);
655         if (l != -1) {
656                 return l;
657         }
658         SCM sid = lookup_identifier (str);
659         if (sid != SCM_UNDEFINED)
660         {
661                 yylval.scm = sid;
662                 return identifier_type (sid);
663         }
664
665         String msg (_f ("unknown escaped string: `\\%s'", str));        
666         LexerError (msg.to_str0 ());
667
668         yylval.scm = scm_makfrom0str (str.to_str0 ());
669
670         return STRING;
671 }
672
673 int
674 My_lily_lexer::scan_bare_word (String str)
675 {
676         SCM sym = ly_symbol2scm (str.to_str0 ());
677         if ((YYSTATE == notes) || (YYSTATE == chords)) {
678                 SCM handle = SCM_BOOL_F;
679                 if (ly_c_pair_p (pitchname_tab_stack_))
680                         handle = scm_hashq_get_handle (ly_car (pitchname_tab_stack_), sym);
681                 
682                 if (ly_c_pair_p (handle)) {
683                         yylval.scm = ly_cdr (handle);
684                         if (unsmob_pitch (yylval.scm)) 
685                             return (YYSTATE == notes) ? NOTENAME_PITCH : TONICNAME_PITCH;
686                         else if (ly_c_symbol_p (yylval.scm))
687                             return DRUM_PITCH;
688                 }
689                 else if ((handle = scm_hashq_get_handle (chordmodifier_tab_, sym))!= SCM_BOOL_F)
690                 {
691                     yylval.scm = ly_cdr (handle);
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::is_note_state () const
702 {
703         return YY_START == notes;
704 }
705
706 bool
707 My_lily_lexer::is_chord_state () const
708 {
709         return YY_START == chords;
710 }
711
712 bool
713 My_lily_lexer::is_lyric_state () const
714 {
715         return YY_START == lyrics;
716 }
717
718 bool
719 My_lily_lexer::is_figure_state () 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 /* 2.1.2x something -> \property -> \set. */ 
753 Lilypond_version oldest_version ("2.2.0");
754
755
756 bool
757 is_valid_version (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   substitute _ and \,
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 scm_cons (scm_int2num (n), scm_int2num (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         SCM proc = ly_scheme_function ("lookup-markup-command");
838         return scm_call_1 (proc, scm_makfrom0str (s.to_str0 ()));
839 }