]> git.donarmstrong.com Git - lilypond.git/blob - lily/lily-guile.cc
lily-guile updates and CG: "Scheme->C interface" section.
[lilypond.git] / lily / lily-guile.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1998--2011 Jan Nieuwenhuizen <janneke@gnu.org>
5   Han-Wen Nienhuys <hanwen@xs4all.nl>
6
7   LilyPond is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   LilyPond is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "lily-guile.hh"
22
23 #include <cstdio>
24 #include <cstdlib>
25 #include <cstring> /* strdup, strchr */
26 #include <cctype>
27
28 using namespace std;
29
30 #include "dimensions.hh"
31 #include "direction.hh"
32 #include "file-path.hh"
33 #include "international.hh"
34 #include "libc-extension.hh"
35 #include "main.hh"
36 #include "misc.hh"
37 #include "offset.hh"
38 #include "pitch.hh"
39 #include "string-convert.hh"
40 #include "source-file.hh"
41 #include "version.hh"
42 #include "warn.hh"
43
44 /*
45   symbols/strings.
46  */
47 string
48 ly_scm_write_string (SCM s)
49 {
50   SCM port = scm_mkstrport (SCM_INUM0,
51                             scm_make_string (SCM_INUM0, SCM_UNDEFINED),
52                             SCM_OPN | SCM_WRTNG,
53                             "ly_write2string");
54   //  SCM write = scm_eval_3 (ly_symbol2scm ("write"), s, SCM_EOL);
55   SCM write = scm_primitive_eval (ly_symbol2scm ("write"));
56
57   // scm_apply (write, port, SCM_EOL);
58   scm_call_2 (write, s, port);
59   return ly_scm2string (scm_strport_to_string (port));
60 }
61
62 SCM
63 ly_quote_scm (SCM s)
64 {
65   return scm_list_n (ly_symbol2scm ("quote"), s, SCM_UNDEFINED);
66 }
67
68 string
69 ly_symbol2string (SCM s)
70 {
71   /*
72     Ugh. this is not very efficient.
73   */
74   SCM str = scm_symbol_to_string (s);
75   return ly_scm2string (str);
76 }
77
78 string
79 gulp_file_to_string (string fn, bool must_exist, int size)
80 {
81   string s = global_path.find (fn);
82   if (s == "")
83     {
84       if (must_exist)
85         {
86           string e = _f ("cannot find file: `%s'", fn);
87           e += " ";
88           e += _f ("(load path: `%s')", global_path.to_string ());
89           error (e);
90           /* unreachable */
91         }
92       return s;
93     }
94
95   debug_output ("[" + s, true);
96
97   vector<char> chars = gulp_file (s, size);
98   string result (&chars[0], chars.size ());
99
100   debug_output ("]\n", false);
101
102   return result;
103 }
104
105 extern "C" {
106   // maybe gdb 5.0 becomes quicker if it doesn't do fancy C++ typing?
107   void
108   ly_display_scm (SCM s)
109   {
110     scm_display (s, scm_current_output_port ());
111     scm_newline (scm_current_output_port ());
112   }
113 };
114
115 /*
116   STRINGS
117  */
118 string
119 ly_scm2string (SCM str)
120 {
121   assert (scm_is_string (str));
122   string result;
123   size_t len = scm_c_string_length (str);
124   if (len)
125     {
126       result.resize (len);
127       scm_to_locale_stringbuf (str, &result.at (0), len);
128     }
129   return result;
130 }
131
132 SCM
133 ly_string2scm (string const &str)
134 {
135   return scm_from_locale_stringn (str.c_str (),
136                                   str.length ());
137 }
138
139 char *
140 ly_scm2str0 (SCM str)
141 {
142   return scm_to_locale_string (str);
143 }
144
145 /*
146   PAIRS
147 */
148 SCM
149 index_get_cell (SCM s, Direction d)
150 {
151   assert (d);
152   return (d == LEFT) ? scm_car (s) : scm_cdr (s);
153 }
154
155 SCM
156 index_set_cell (SCM s, Direction d, SCM v)
157 {
158   if (d == LEFT)
159     scm_set_car_x (s, v);
160   else if (d == RIGHT)
161     scm_set_cdr_x (s, v);
162   return s;
163 }
164
165 bool
166 is_number_pair (SCM p)
167 {
168   return scm_is_pair (p)
169          && scm_is_number (scm_car (p)) && scm_is_number (scm_cdr (p));
170 }
171
172 unsigned int
173 ly_scm_hash (SCM s)
174 {
175   return scm_ihashv (s, ~1u);
176 }
177
178 bool
179 is_axis (SCM s)
180 {
181   if (scm_is_integer (s))
182     {
183       int i = scm_to_int (s);
184       return i == 0 || i == 1;
185     }
186   return false;
187 }
188
189 bool
190 to_boolean (SCM s)
191 {
192   return scm_is_bool (s) && ly_scm2bool (s);
193 }
194
195 /*
196   DIRECTIONS
197  */
198 Direction
199 to_dir (SCM s)
200 {
201   return scm_is_integer (s) ? (Direction) scm_to_int (s) : CENTER;
202 }
203
204 Direction
205 robust_scm2dir (SCM d, Direction def)
206 {
207   if (is_direction (d))
208     def = to_dir (d);
209   return def;
210 }
211
212 bool
213 is_direction (SCM s)
214 {
215   if (scm_is_integer (s))
216     {
217       int i = scm_to_int (s);
218       return i >= -1 && i <= 1;
219     }
220   return false;
221 }
222
223 /*
224   INTERVALS
225  */
226 Interval
227 ly_scm2interval (SCM p)
228 {
229   return is_number_pair (p) ?
230            Interval (scm_to_double (scm_car (p)),
231                      scm_to_double (scm_cdr (p))) :
232            Interval (0, 0);
233 }
234
235 Drul_array<Real>
236 ly_scm2realdrul (SCM p)
237 {
238   return Drul_array<Real> (scm_to_double (scm_car (p)),
239                            scm_to_double (scm_cdr (p)));
240 }
241
242 SCM
243 ly_interval2scm (Drul_array<Real> i)
244 {
245   return scm_cons (scm_from_double (i[LEFT]), scm_from_double (i[RIGHT]));
246 }
247
248 Interval
249 robust_scm2interval (SCM k, Drul_array<Real> v)
250 {
251   Interval i;
252   i[LEFT] = v[LEFT];
253   i[RIGHT] = v[RIGHT];
254   if (is_number_pair (k))
255     i = ly_scm2interval (k);
256   return i;
257 }
258
259 Drul_array<Real>
260 robust_scm2drul (SCM k, Drul_array<Real> v)
261 {
262   if (is_number_pair (k))
263     v = ly_scm2interval (k);
264   return v;
265 }
266
267 Drul_array<bool>
268 robust_scm2booldrul (SCM k, Drul_array<bool> def)
269 {
270   if (scm_is_pair (k))
271     {
272       def[LEFT] = to_boolean (scm_car (k));
273       def[RIGHT] = to_boolean (scm_cdr (k));
274     }
275   return def;
276 }
277
278 /*
279   OFFSET
280 */
281 SCM
282 ly_offset2scm (Offset o)
283 {
284   return scm_cons (scm_from_double (o[X_AXIS]), scm_from_double (o[Y_AXIS]));
285 }
286
287 Offset
288 ly_scm2offset (SCM s)
289 {
290   return is_number_pair (s) ?
291            Offset (scm_to_double (scm_car (s)),
292                    scm_to_double (scm_cdr (s))) :
293            Offset (0, 0);
294 }
295
296 Offset
297 robust_scm2offset (SCM k, Offset o)
298 {
299   if (is_number_pair (k))
300     o = ly_scm2offset (k);
301   return o;
302 }
303 SCM
304 ly_offsets2scm (vector<Offset> os)
305 {
306   SCM l = SCM_EOL;
307   SCM *tail = &l;
308   for (vsize i = 0; i < os.size (); i++)
309     {
310       *tail = scm_cons (ly_offset2scm (os[i]), SCM_EOL);
311       tail = SCM_CDRLOC (*tail);
312     }
313   return l;
314 }
315
316 vector<Offset>
317 ly_scm2offsets (SCM s)
318 {
319   vector<Offset> os;
320   for (; scm_is_pair (s); s = scm_cdr (s))
321     os.push_back (ly_scm2offset (scm_car (s)));
322   return os;
323 }
324
325 /*
326   ALIST
327 */
328 // This one is used nowhere.
329 bool
330 ly_is_alist_equal (SCM a, SCM b)
331 {
332   if (!scm_is_pair (a) || !scm_is_pair (b))
333     return false;
334   for (SCM s = a; scm_is_pair (s); s = scm_cdr (s))
335     {
336       SCM key = scm_caar (s);
337       SCM val = scm_cdar (s);
338       SCM l = scm_assoc (key, b);
339
340       if (scm_is_false (l) || !ly_is_equal (scm_cdr (l), val))
341         return false;
342     }
343   return true;
344 }
345
346 SCM
347 ly_alist_vals (SCM alist)
348 {
349   SCM x = SCM_EOL;
350   for (SCM p = alist; scm_is_pair (p); p = scm_cdr (p))
351     x = scm_cons (scm_cdar (p), x);
352   return x;
353 }
354
355 /*
356   LISTS
357  */
358
359 /* Return I-th element, or last elt L. If I < 0, then we take the first
360    element.
361
362    PRE: length (L) > 0  */
363 SCM
364 robust_list_ref (int i, SCM l)
365 {
366   while (i-- > 0 && scm_is_pair (scm_cdr (l)))
367     l = scm_cdr (l);
368   return scm_car (l);
369 }
370
371 SCM
372 ly_deep_copy (SCM src)
373 {
374   if (scm_is_pair (src))
375     return scm_cons (ly_deep_copy (scm_car (src)), ly_deep_copy (scm_cdr (src)));
376   else if (scm_is_vector (src))
377     {
378       int len = scm_c_vector_length (src);
379       SCM nv = scm_c_make_vector (len, SCM_UNDEFINED);
380       for (int i = 0; i < len; i++)
381         {
382           SCM si = scm_from_int (i);
383           scm_vector_set_x (nv, si, ly_deep_copy (scm_vector_ref (src, si)));
384         }
385     }
386   return src;
387 }
388
389 string
390 print_scm_val (SCM val)
391 {
392   string realval = ly_scm_write_string (val);
393   if (realval.length () > 200)
394     realval = realval.substr (0, 100)
395               + "\n :\n :\n"
396               + realval.substr (realval.length () - 100);
397   return realval;
398 }
399
400 bool
401 type_check_assignment (SCM sym, SCM val, SCM type_symbol)
402 {
403   bool ok = true;
404
405   /*
406     Always succeeds.
407
408
409     TODO: should remove #f from allowed vals?
410   */
411   if (val == SCM_EOL || val == SCM_BOOL_F)
412     return ok;
413
414   if (!scm_is_symbol (sym))
415 #if 0
416     return false;
417 #else
418     /*
419       This is used for autoBeamSettings.
420
421       TODO: deprecate the use of \override and \revert for
422       autoBeamSettings?
423
424       or use a symbol autoBeamSettingS?
425     */
426     return true;
427 #endif
428
429   SCM type = scm_object_property (sym, type_symbol);
430
431   if (type != SCM_EOL && !ly_is_procedure (type))
432     {
433       warning (_f ("cannot find property type-check for `%s' (%s).",
434                    ly_symbol2string (sym).c_str (),
435                    ly_symbol2string (type_symbol).c_str ())
436                + "  " + _ ("perhaps a typing error?"));
437
438       /* Be strict when being anal :) */
439       if (do_internal_type_checking_global)
440         scm_throw (ly_symbol2scm ("ly-file-failed"), scm_list_3 (ly_symbol2scm ("typecheck"),
441                                                                  sym, val));
442
443       warning (_ ("doing assignment anyway"));
444     }
445   else
446     {
447       if (val != SCM_EOL
448           && ly_is_procedure (type)
449           && scm_call_1 (type, val) == SCM_BOOL_F)
450         {
451           ok = false;
452           SCM typefunc = ly_lily_module_constant ("type-name");
453           SCM type_name = scm_call_1 (typefunc, type);
454
455           warning (_f ("type check for `%s' failed; value `%s' must be of type `%s'",
456                        ly_symbol2string (sym).c_str (),
457                        print_scm_val (val),
458                        ly_scm2string (type_name).c_str ()));
459           progress_indication ("\n");
460         }
461     }
462   return ok;
463 }
464
465 /* some SCM abbrevs
466
467 zijn deze nou handig?
468 zijn ze er al in scheme, maar heten ze anders? */
469
470 /* Remove doubles from (sorted) list */
471 SCM
472 ly_unique (SCM list)
473 {
474   SCM unique = SCM_EOL;
475   for (SCM i = list; scm_is_pair (i); i = scm_cdr (i))
476     {
477       if (!scm_is_pair (scm_cdr (i))
478           || !ly_is_equal (scm_car (i), scm_cadr (i)))
479         unique = scm_cons (scm_car (i), unique);
480     }
481   return scm_reverse_x (unique, SCM_EOL);
482 }
483
484 /* Split list at member s, removing s.
485    Return (BEFORE . AFTER)  */
486 SCM
487 ly_split_list (SCM s, SCM list)
488 {
489   SCM before = SCM_EOL;
490   SCM after = list;
491   for (; scm_is_pair (after);)
492     {
493       SCM i = scm_car (after);
494       after = scm_cdr (after);
495       if (ly_is_equal (i, s))
496         break;
497       before = scm_cons (i, before);
498     }
499   return scm_cons (scm_reverse_x (before, SCM_EOL), after);
500 }
501
502 void
503 taint (SCM *)
504 {
505   /*
506     nop.
507   */
508 }
509
510 /*
511   display stuff without using stack
512 */
513 SCM
514 display_list (SCM s)
515 {
516   SCM p = scm_current_output_port ();
517
518   scm_puts ("(", p);
519   for (; scm_is_pair (s); s = scm_cdr (s))
520     {
521       scm_display (scm_car (s), p);
522       scm_puts (" ", p);
523     }
524   scm_puts (")", p);
525   return SCM_UNSPECIFIED;
526 }
527
528 Slice
529 int_list_to_slice (SCM l)
530 {
531   Slice s;
532   s.set_empty ();
533   for (; scm_is_pair (l); l = scm_cdr (l))
534     if (scm_is_number (scm_car (l)))
535       s.add_point (scm_to_int (scm_car (l)));
536   return s;
537 }
538
539 Real
540 robust_scm2double (SCM k, double x)
541 {
542   if (scm_is_number (k))
543     x = scm_to_double (k);
544   return x;
545 }
546
547 string
548 robust_scm2string (SCM k, string s)
549 {
550   if (scm_is_string (k))
551     s = ly_scm2string (k);
552   return s;
553 }
554
555 int
556 robust_scm2int (SCM k, int o)
557 {
558   if (scm_integer_p (k) == SCM_BOOL_T)
559     o = scm_to_int (k);
560   return o;
561 }
562
563 SCM
564 ly_rational2scm (Rational r)
565 {
566   return scm_divide (scm_from_int64 (r.numerator ()),
567                      scm_from_int64 (r.denominator ()));
568 }
569
570 Rational
571 ly_scm2rational (SCM r)
572 {
573   return Rational (scm_to_int64 (scm_numerator (r)),
574                    scm_to_int64 (scm_denominator (r)));
575 }
576
577 Rational
578 robust_scm2rational (SCM n, Rational rat)
579 {
580   if (ly_is_fraction (n))
581     return ly_scm2rational (n);
582   else
583     return rat;
584 }
585
586 SCM
587 alist_to_hashq (SCM alist)
588 {
589   int i = scm_ilength (alist);
590   if (i < 0)
591     return scm_c_make_hash_table (0);
592
593   SCM tab = scm_c_make_hash_table (i);
594   for (SCM s = alist; scm_is_pair (s); s = scm_cdr (s))
595     {
596       SCM pt = scm_cdar (s);
597       scm_hashq_set_x (tab, scm_caar (s), pt);
598     }
599   return tab;
600 }
601
602 SCM
603 ly_hash2alist (SCM tab)
604 {
605   SCM func = ly_lily_module_constant ("hash-table->alist");
606   return scm_call_1 (func, tab);
607 }
608
609 /*
610   C++ interfacing.
611  */
612
613 string
614 mangle_cxx_identifier (string cxx_id)
615 {
616   if (cxx_id.substr (0, 3) == "ly_")
617     cxx_id = cxx_id.replace (0, 3, "ly:");
618   else
619     {
620       cxx_id = String_convert::to_lower (cxx_id);
621       cxx_id = "ly:" + cxx_id;
622     }
623   if (cxx_id.substr (cxx_id.length () - 2) == "_p")
624     cxx_id = cxx_id.replace (cxx_id.length () - 2, 2, "?");
625   else if (cxx_id.substr (cxx_id.length () - 2) == "_x")
626     cxx_id = cxx_id.replace (cxx_id.length () - 2, 2, "!");
627
628   replace_all (&cxx_id, "_less?", "<?");
629   replace_all (&cxx_id, "_2_", "->");
630   replace_all (&cxx_id, "__", "::");
631   replace_all (&cxx_id, '_', '-');
632
633   return cxx_id;
634 }
635
636 SCM
637 ly_string_array_to_scm (vector<string> a)
638 {
639   SCM s = SCM_EOL;
640   for (vsize i = a.size (); i; i--)
641     s = scm_cons (ly_symbol2scm (a[i - 1].c_str ()), s);
642   return s;
643 }
644
645 /* SYMBOLS is a whitespace separated list.  */
646 SCM
647 parse_symbol_list (char const *symbols)
648 {
649   while (isspace (*symbols))
650     symbols++;
651   string s = symbols;
652   replace_all (&s, '\n', ' ');
653   replace_all (&s, '\t', ' ');
654   replace_all (&s, "  ", " ");
655   return ly_string_array_to_scm (string_split (s, ' '));
656 }
657
658 /* GDB debugging. */
659 struct ly_t_double_cell
660 {
661   SCM a;
662   SCM b;
663   SCM c;
664   SCM d;
665 };
666
667 /* inserts at front, removing duplicates */
668 SCM ly_assoc_prepend_x (SCM alist, SCM key, SCM val)
669 {
670   return scm_acons (key, val, scm_assoc_remove_x (alist, key));
671 }
672