]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
(ly_parse_scm): add line/col/file
[lilypond.git] / lily / lily-guile.cc
1 /*
2   lily-guile.cc -- implement assorted guile functions
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1998--2002 Jan Nieuwenhuizen <janneke@gnu.org>
7
8   Han-Wen Nienhuys <hanwen@cs.uu.nl>
9 */
10
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <math.h>   /* isinf */
15 #include <string.h> /* strdup, strchr */
16 #include "libc-extension.hh"
17 #include "lily-guile.hh"
18 #include "main.hh"
19 #include "simple-file-storage.hh"
20 #include "file-path.hh"
21 #include "warn.hh"
22 #include "direction.hh"
23 #include "offset.hh"
24 #include "interval.hh"
25 #include "pitch.hh"
26 #include "dimensions.hh"
27
28
29 // #define TEST_GC
30
31 #ifdef PARANOID
32 #include <libguile/gc.h>
33 #undef gh_pair_p
34 bool
35 ly_pair_p (SCM x)
36 {
37 #if 0
38   assert (!SCM_CONSP (x) || (*(scm_t_bits*) SCM2PTR (SCM_CAR (x))) != scm_tc_free_cell);
39   assert (!SCM_CONSP (x) || (*(scm_t_bits*) SCM2PTR (SCM_CDR (x))) != scm_tc_free_cell);
40 #elif GUILE_MINOR_VERSION < 5
41   assert (!SCM_CONSP (x) || !SCM_FREEP (SCM_CAR (x)));
42   assert (!SCM_CONSP (x) || !SCM_FREEP (SCM_CDR (x)));
43 #else
44   assert (!SCM_CONSP (x) || !SCM_FREE_CELL_P (SCM_CAR (x)));
45   assert (!SCM_CONSP (x) || !SCM_FREE_CELL_P (SCM_CDR (x)));
46 #endif  
47   //return SCM_NFALSEP (scm_pair_p (x));
48   return gh_pair_p (x); 
49 }
50 #define gh_pair_p ly_pair_p
51 #endif
52
53 SCM
54 ly_last (SCM list)
55 {
56   return ly_car (scm_last_pair (list));
57 }
58
59 SCM
60 ly_str02scm (char const*c)
61 {
62   // this all really sucks, guile should take char const* arguments!
63   return gh_str02scm ((char*)c);
64 }
65
66
67 SCM
68 ly_write2scm (SCM s)
69 {
70   SCM port = scm_mkstrport (SCM_INUM0, 
71                             scm_make_string (SCM_INUM0, SCM_UNDEFINED),
72                             SCM_OPN | SCM_WRTNG,
73                             "ly_write2string");
74   //  SCM write = scm_eval_3 (ly_symbol2scm ("write"), s, SCM_EOL);
75   SCM write = scm_primitive_eval (ly_symbol2scm ("write"));
76   
77   // scm_apply (write, port, SCM_EOL);
78   gh_call2 (write, s, port);
79   return scm_strport_to_string (port);
80 }
81
82
83 /*
84   Pass string to scm parser, evaluate one expression.
85   Return result value and #chars read.
86
87   Thanks to Gary Houston <ghouston@freewire.co.uk>
88
89   Need guile-1.3.4 (>1.3 anyway) for ftell on str ports -- jcn
90 */
91 /*
92   should move this func elsewhere (?)
93  */
94 SCM
95 ly_parse_scm (char const* s, int* n, Input ip)
96 {
97   SCM str = ly_str02scm (s);
98   SCM port = scm_mkstrport (SCM_INUM0, str, SCM_OPN | SCM_RDNG,
99                             "ly_eval_scm_0str");
100
101   scm_set_port_filename_x (port, scm_makfrom0str (ip.file_string ().str0()));
102   scm_set_port_line_x (port,  gh_int2scm (ip.line_number ()));
103   scm_set_port_column_x (port,  gh_int2scm (ip.column_number()));
104   
105   SCM from = scm_ftell (port);
106
107   SCM form;
108   SCM answer = SCM_UNSPECIFIED;
109
110   /* Read expression from port */
111   if (!SCM_EOF_OBJECT_P (form = scm_read (port)))
112     answer = scm_primitive_eval (form);
113  
114   /*
115    After parsing
116
117  (begin (foo 1 2))
118
119    all seems fine, but after parsing
120
121  (foo 1 2)
122
123    read_buf has been advanced to read_pos - 1,
124    so that scm_ftell returns 1, instead of #parsed chars
125    */
126   
127   /*
128     urg: reset read_buf for scm_ftell
129     shouldn't scm_read () do this for us?
130   */
131   scm_fill_input (port);
132   SCM to = scm_ftell (port);
133   *n = gh_scm2int (to) - gh_scm2int (from);
134
135   /* Don't close the port here; if we re-enter this function via a
136      continuation, then the next time we enter it, we'll get an error.
137      It's a string port anyway, so there's no advantage to closing it
138      early.
139
140      scm_close_port (port);
141   */
142
143   return answer;
144 }
145
146 SCM
147 ly_quote_scm (SCM s)
148 {
149   return scm_list_n (ly_symbol2scm ("quote"), s, SCM_UNDEFINED);
150 }
151
152
153
154 String
155 ly_symbol2string (SCM s)
156 {
157   assert (gh_symbol_p (s));
158   return String ((Byte*)SCM_STRING_CHARS (s), (int) SCM_STRING_LENGTH (s));
159 }
160
161
162 String
163 gulp_file_to_string (String fn)
164 {
165   String s = global_path.find (fn);
166   if (s == "")
167     {
168       String e = _f ("can't find file: `%s'", fn);
169       e += " ";
170       e += _f ("(load path: `%s')", global_path.string ());
171       error (e);
172     }
173   else if (verbose_global_b)
174     progress_indication ("[" + s);
175
176
177   Simple_file_storage f (s);
178   String result (f.to_str0 ());
179   if (verbose_global_b)
180     progress_indication ("]");
181   return result;
182 }
183
184 LY_DEFINE(ly_gulp_file, "ly-gulp-file", 1,0, 0,
185           (SCM name),
186           "Read the file named @var{name}, and return its contents in a string. The
187 file is looked up using the lilypond search path.
188
189 ")
190 {
191   return ly_str02scm (gulp_file_to_string (ly_scm2string (name)).to_str0 ());
192 }
193
194
195 /**
196    Read a file, and shove it down GUILE.  GUILE also has file read
197    functions, but you can't fiddle with the path of those.
198
199
200    TODO: JUNKME.
201 */
202 void
203 read_lily_scm_file (String fn)
204 {
205   gh_eval_str ((char *) gulp_file_to_string (fn).to_str0 ());
206 }
207
208 extern "C" {
209   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
210 void
211 ly_display_scm (SCM s)
212 {
213   gh_display (s);
214   gh_newline ();
215 }
216 };
217
218 String
219 ly_scm2string (SCM s)
220 {
221   assert (gh_string_p (s));
222
223   char *p = SCM_STRING_CHARS(s);
224   String r (p);
225   return r;
226 }
227
228 SCM
229 index_get_cell (SCM s, Direction d)
230 {
231   assert (d);
232   return (d == LEFT) ? ly_car (s) : ly_cdr (s);
233 }
234
235 SCM
236 index_set_cell (SCM s, Direction d, SCM v)
237 {
238   if (d == LEFT)
239     gh_set_car_x (s, v);
240   else if (d == RIGHT)
241     gh_set_cdr_x (s, v);
242   return s;
243 }
244   
245 LY_DEFINE(ly_warning,"ly-warn", 1, 0, 0,
246   (SCM str),"Scheme callable function to issue the warning @code{msg}.
247 ")
248 {
249   assert (gh_string_p (str));
250   warning ("lily-guile: " + ly_scm2string (str));
251   return SCM_BOOL_T;
252 }
253
254 LY_DEFINE(ly_isdir,  "dir?", 1,0, 0,  (SCM s),
255           "type predicate. A direction is a -1, 0 or 1, where -1 represents left or
256 down and 1 represents right or up.
257 ")
258 {
259   if (gh_number_p (s))
260     {
261       int i = gh_scm2int (s);
262       return (i>= -1 && i <= 1)  ? SCM_BOOL_T : SCM_BOOL_F; 
263     }
264   return SCM_BOOL_F;
265 }
266
267 bool
268 ly_number_pair_p (SCM p)
269 {
270   return gh_pair_p (p) && gh_number_p (ly_car (p)) && gh_number_p (ly_cdr (p));
271 }
272
273 typedef void (*Void_fptr) ();
274 Array<Void_fptr> *scm_init_funcs_;
275
276 void add_scm_init_func (void (*f) ())
277 {
278   if (!scm_init_funcs_)
279     scm_init_funcs_ = new Array<Void_fptr>;
280
281   scm_init_funcs_->push (f);
282 }
283
284 extern void init_cxx_function_smobs ();
285
286
287 void
288 ly_init_guile ()
289 {
290   SCM last_mod = scm_current_module ();
291   scm_set_current_module (scm_c_resolve_module ("guile"));
292   
293   init_cxx_function_smobs ();
294   for (int i=scm_init_funcs_->size () ; i--;)
295     (scm_init_funcs_->elem (i)) ();
296
297   if (verbose_global_b)
298     progress_indication ("\n");
299   read_lily_scm_file ("lily.scm");
300
301   scm_set_current_module (last_mod);
302 }
303
304 unsigned int ly_scm_hash (SCM s)
305 {
306   return scm_ihashv (s, ~1u);
307 }
308
309
310
311 bool
312 ly_dir_p (SCM s)
313 {
314   if (gh_number_p (s))
315     {
316       int i = gh_scm2int (s);
317       return i>= -1 && i <= 1; 
318     }
319   return false;
320 }
321
322
323 bool
324 ly_axis_p (SCM s)
325 {
326   if (gh_number_p (s))
327     {
328       int i = gh_scm2int (s);
329       return i== 0 || i == 1;
330     }
331   return false;
332 }
333
334
335 Direction
336 to_dir (SCM s)
337 {
338   return (Direction) gh_scm2int (s);
339 }
340
341 Interval
342 ly_scm2interval (SCM p)
343 {
344   return  Interval (gh_scm2double (ly_car (p)),
345                     gh_scm2double (ly_cdr (p)));
346 }
347
348 SCM
349 ly_interval2scm (Drul_array<Real> i)
350 {
351   return gh_cons (gh_double2scm (i[LEFT]),
352                   gh_double2scm (i[RIGHT]));
353 }
354
355
356
357
358 bool
359 to_boolean (SCM s)
360 {
361   return gh_boolean_p (s) && gh_scm2bool (s);
362 }
363
364 /*
365   Appendable list L: the cdr contains the list, the car the last cons
366   in the list.
367  */
368 SCM
369 appendable_list ()
370 {
371   SCM s = gh_cons (SCM_EOL, SCM_EOL);
372   gh_set_car_x (s, s);
373   
374   return s;
375 }
376
377 void
378 appendable_list_append (SCM l, SCM elt)
379 {
380   SCM newcons = gh_cons (elt, SCM_EOL);
381   
382   gh_set_cdr_x (ly_car (l), newcons);      
383   gh_set_car_x (l, newcons);
384 }
385
386
387 SCM
388 ly_offset2scm (Offset o)
389 {
390   return gh_cons (gh_double2scm (o[X_AXIS]), gh_double2scm (o[Y_AXIS]));
391 }
392
393 Offset
394 ly_scm2offset (SCM s)
395 {
396   return Offset (gh_scm2double (ly_car (s)),
397                  gh_scm2double (ly_cdr (s)));
398 }
399
400 SCM
401 ly_type (SCM exp)
402 {
403   char const  * cp = "unknown";
404   if (gh_number_p (exp))
405     {
406       cp = "number";
407     }
408   else if (gh_string_p (exp))
409     {
410       cp = "string";
411     }
412   else if (gh_procedure_p (exp))
413     {
414       cp = "procedure";
415     }
416   else if (gh_boolean_p (exp))
417     {
418       cp = "boolean";
419     }
420   else if (gh_pair_p (exp))
421     {
422       cp = "list";
423     }
424
425   return ly_str02scm (cp);
426 }
427
428 /*
429   convert without too many decimals, and leave  a space at the end.
430  */
431    
432    
433 LY_DEFINE(ly_number2string,  "ly-number->string", 1, 0,0,
434           (SCM s),
435           " converts @var{num} to a string without generating many decimals. It
436 leaves a space at the end.
437 ")
438 {
439   assert (gh_number_p (s));
440
441   char str[400];                        // ugh.
442
443   if (scm_exact_p (s) == SCM_BOOL_F)
444     {
445       Real r (gh_scm2double (s));
446
447       if (isinf (r) || isnan (r))
448         {
449           programming_error ("Infinity or NaN encountered while converting Real number; setting to zero.");
450           r = 0.0;
451         }
452
453       sprintf (str, "%8.4f ", r);
454     }
455   else
456     {
457       sprintf (str, "%d ", gh_scm2int (s));
458     }
459
460   return ly_str02scm (str);
461 }
462
463 /*
464   Undef this to see if GUILE GC is causing too many swaps.
465  */
466
467 // #define TEST_GC
468
469 #ifdef TEST_GC
470 #include <libguile/gc.h>
471
472 static void *
473 greet_sweep (void *dummy1, void *dummy2, void *dummy3)
474 {
475    fprintf (stderr, "entering sweep\n");
476 }
477
478 static void *
479 wave_sweep_goodbye (void *dummy1, void *dummy2, void *dummy3)
480 {
481    fprintf (stderr, "leaving sweep\n");
482 }
483 #endif
484
485
486 #include "version.hh"
487 LY_DEFINE(ly_version,  "ly-version", 0, 0, 0, (),
488           "Return the current lilypond version as a list, e.g.
489 @code{(1 3 127 uu1)}. 
490 ")
491 {
492   char const* vs =  "\' (" MAJOR_VERSION " " MINOR_VERSION " "  PATCH_LEVEL " " MY_PATCH_LEVEL ")" ;
493   
494   return gh_eval_str ((char*)vs);
495 }
496
497 LY_DEFINE(ly_unit,  "ly-unit", 0, 0, 0, (),
498           "Return the unit used for lengths as a string.")
499 {
500   return ly_str02scm (INTERNAL_UNIT);
501 }
502
503 LY_DEFINE(ly_verbose,  "ly-verbose", 0, 0, 0, (),
504   "Return whether lilypond is being run in verbose mode.")
505 {
506   return gh_bool2scm (verbose_global_b);
507 }
508
509 static void
510 init_functions ()
511 {
512 #ifdef TEST_GC 
513   scm_c_hook_add (&scm_before_mark_c_hook, greet_sweep, 0, 0);
514   scm_c_hook_add (&scm_before_sweep_c_hook, wave_sweep_goodbye, 0, 0);
515 #endif
516 }
517
518 ADD_SCM_INIT_FUNC (funcs, init_functions);
519
520 SCM
521 ly_deep_copy (SCM src)
522 {
523   if (gh_pair_p (src))
524     {
525       return gh_cons (ly_deep_copy (ly_car (src)), ly_deep_copy (ly_cdr (src)));
526     }
527   else if (gh_vector_p (src))
528     {
529       int  l = SCM_VECTOR_LENGTH (src);
530       SCM nv = scm_c_make_vector (l, SCM_UNDEFINED);
531       for (int i  =0 ; i< l ; i++)
532         {
533           SCM si = gh_int2scm (i);
534           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si))); 
535         }
536     }
537   else
538     return src;
539
540   return src;
541 }
542
543
544
545
546 SCM
547 ly_assoc_chain (SCM key, SCM achain)
548 {
549   if (gh_pair_p (achain))
550     {
551       SCM handle = scm_assoc (key, ly_car (achain));
552       if (gh_pair_p (handle))
553         return handle;
554       else
555         return ly_assoc_chain (key, ly_cdr (achain));
556     }
557   else
558     return SCM_BOOL_F;
559 }
560
561 /* looks the key up in the cdrs of the alist-keys
562    - ignoring the car and ignoring non-pair keys.
563    Returns first match found, i.e.
564
565    alist = ((1 . 10)
566                    ((1 . 2) . 11)
567                    ((2 . 1) . 12)
568                    ((3 . 0) . 13)
569                    ((4 . 1) . 14) )
570
571 I would like (ly_assoc_cdr 1) to return 12 - because it's the first
572 element with the cdr of the key = 1.  In other words (alloc_cdr key)
573 corresponds to call
574
575 (alloc (anything . key))
576
577
578
579 */
580 SCM
581 ly_assoc_cdr (SCM key, SCM alist)
582 {
583   if (gh_pair_p (alist)) {
584     SCM trykey = ly_caar(alist);
585     if(gh_pair_p(trykey) && to_boolean(scm_equal_p(key,ly_cdr(trykey))))
586       return ly_car(alist);
587     else
588       return ly_assoc_cdr (key, ly_cdr (alist));
589   }
590   else
591     return SCM_BOOL_F;
592 }
593
594 /*
595   LIST has the form "sym1 sym2 sym3\nsym4\nsym5"
596
597   i.e. \n and ' ' can be used interchangeably as separators.
598  */
599 SCM
600 parse_symbol_list (const char * list)
601 {
602   char * s = strdup (list);
603   char *orig = s;
604   SCM create_list = SCM_EOL;
605
606   for (char * p = s; *p; p++)
607     {
608       if (*p == '\n')
609         *p = ' ' ;
610     }
611   
612   if (!s[0] )
613     s = 0;
614
615
616   
617   while (s)
618     {
619       char *next = strchr (s, ' ');
620       if (next)
621         *next++ = 0;
622
623       create_list = gh_cons (ly_symbol2scm (s), create_list);
624       s = next;
625     }
626
627   free (orig);
628   return create_list;
629 }
630
631
632 SCM
633 ly_truncate_list (int k, SCM l )
634 {
635   if (k == 0)
636     {
637       l = SCM_EOL;
638     }
639   else
640     {
641       SCM s = l;
642       k--;
643       for (; gh_pair_p (s) && k--; s = ly_cdr (s))
644         ;
645
646       if (gh_pair_p (s))
647         {
648           gh_set_cdr_x (s, SCM_EOL);
649         }
650     }
651   return l;
652 }
653
654 SCM my_gh_symbol2scm (const char* x)
655 {
656   return gh_symbol2scm ((char*)x);
657 }
658
659 String
660 print_scm_val (SCM val)
661 {
662   String realval = ly_scm2string (ly_write2scm (val));
663   if (realval.length () > 200)
664     realval = realval.left_string (100) + "\n :\n :\n" + realval.right_string (100);
665   
666   return realval;        
667 }
668
669 bool
670 type_check_assignment (SCM sym, SCM val,  SCM type_symbol) 
671 {
672   bool ok = true;
673
674   /*
675     Always succeeds.
676
677
678     TODO: should remove #f from allowed vals?
679    */
680   if (val == SCM_EOL || val == SCM_BOOL_F)
681     return ok;
682
683   
684   SCM type = SCM_EOL;
685
686   if (gh_symbol_p (sym))
687     type = scm_object_property (sym, type_symbol);
688
689   if (type != SCM_EOL && !gh_procedure_p (type))
690       {
691         warning (_f ("Can't find property type-check for `%s' (%s).  Perhaps you made a typing error? Doing assignment anyway.",
692                      ly_symbol2string (sym).to_str0 (),
693                      ly_symbol2string (type_symbol).to_str0 ()
694
695                      ));
696       }
697   else
698     {
699       if (val != SCM_EOL
700           && gh_procedure_p (type)
701           && gh_call1 (type, val) == SCM_BOOL_F)
702         {
703           SCM errport = scm_current_error_port ();
704           ok = false;
705           SCM typefunc = scm_primitive_eval (ly_symbol2scm ("type-name"));
706           SCM type_name = gh_call1 (typefunc, type);
707
708          
709           scm_puts (_f ("Type check for `%s' failed; value `%s' must be of type `%s'",
710                         ly_symbol2string (sym).to_str0 (),
711                         print_scm_val (val),
712                         ly_scm2string (type_name).to_str0 ()).to_str0 (),
713                     errport);
714           scm_puts ("\n", errport);                   
715         }
716     }
717   return ok;
718 }
719
720
721 /* some SCM abbrevs
722
723    zijn deze nou handig?
724    zijn ze er al in scheme, maar heten ze anders? */
725
726
727 /* Remove doubles from (sorted) list */
728 SCM
729 ly_unique (SCM list)
730 {
731   SCM unique = SCM_EOL;
732   for (SCM i = list; gh_pair_p (i); i = ly_cdr (i))
733     {
734       if (!gh_pair_p (ly_cdr (i))
735           || !gh_equal_p (ly_car (i), ly_cadr (i)))
736         unique = gh_cons (ly_car (i), unique);
737     }
738   return scm_reverse_x (unique, SCM_EOL);
739 }
740
741 /* tail add */
742 SCM
743 ly_snoc (SCM s, SCM list)
744 {
745   return gh_append2 (list, scm_list_n (s, SCM_UNDEFINED));
746 }
747
748
749 /* Split list at member s, removing s.
750    Return (BEFORE . AFTER) */
751 SCM
752 ly_split_list (SCM s, SCM list)
753 {
754   SCM before = SCM_EOL;
755   SCM after = list;
756   for (; gh_pair_p (after);)
757     {
758       SCM i = ly_car (after);
759       after = ly_cdr (after);
760       if (gh_equal_p (i, s))
761         break;
762       before = gh_cons (i, before);
763     }
764   return gh_cons ( scm_reverse_x (before, SCM_EOL),  after);
765   
766 }
767
768
769 void
770 taint (SCM *)
771 {
772   /*
773     nop.
774    */
775 }
776
777 /*
778   display stuff without using stack
779  */
780 SCM
781 display_list (SCM s)
782 {
783   SCM p = scm_current_output_port();
784
785   scm_puts ("(", p);
786   for (; gh_pair_p(s); s =gh_cdr(s))
787     {
788       scm_display (gh_car(s), p);
789       scm_puts (" ", p);      
790     }
791   scm_puts (")", p);
792   return SCM_UNSPECIFIED;
793 }
794
795 Slice
796 int_list_to_slice (SCM l)
797 {
798   Slice s;
799   s.set_empty ();
800   for (; gh_pair_p (l); l = gh_cdr (l))
801     {
802       if (gh_number_p (gh_car (l)))
803         s.add_point (gh_scm2int (gh_car (l))); 
804     }
805
806   return s;
807 }
808
809
810
811
812 /*
813   Return I-th element, or last elt L. If I < 0, then we take the first
814   element.
815
816   PRE: length (L) > 0
817  */
818 SCM
819 robust_list_ref(int i, SCM l)
820 {
821   while (i-- > 0 && gh_pair_p (gh_cdr(l)))
822     l = gh_cdr (l);
823
824   return gh_car(l);
825 }