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