c++-gtk-utils
extension.h
Go to the documentation of this file.
1 /* Copyright (C) 2014 and 2016 Chris Vine
2 
3 The library comprised in this file or of which this file is part is
4 distributed by Chris Vine under the GNU Lesser General Public
5 License as follows:
6 
7  This library is free software; you can redistribute it and/or
8  modify it under the terms of the GNU Lesser General Public License
9  as published by the Free Software Foundation; either version 2.1 of
10  the License, or (at your option) any later version.
11 
12  This library is distributed in the hope that it will be useful, but
13  WITHOUT ANY WARRANTY; without even the implied warranty of
14  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  Lesser General Public License, version 2.1, for more details.
16 
17  You should have received a copy of the GNU Lesser General Public
18  License, version 2.1, along with this library (see the file LGPL.TXT
19  which came with this source code package in the c++-gtk-utils
20  sub-directory); if not, write to the Free Software Foundation, Inc.,
21  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 
23 However, it is not intended that the object code of a program whose
24 source code instantiates a template from this file or uses macros or
25 inline functions (of any length) should by reason only of that
26 instantiation or use be subject to the restrictions of use in the GNU
27 Lesser General Public License. With that in mind, the words "and
28 macros, inline functions and instantiations of templates (of any
29 length)" shall be treated as substituted for the words "and small
30 macros and small inline functions (ten lines or less in length)" in
31 the fourth paragraph of section 5 of that licence. This does not
32 affect any other reason why object code may be subject to the
33 restrictions in that licence (nor for the avoidance of doubt does it
34 affect the application of section 2 of that licence to modifications
35 of the source code in this file).
36 
37 NOTE: If you incorporate this header file in your code, you will have
38 to link with libguile. libguile is released under the LGPL version 3
39 or later. By linking with libguile your code will therefore be
40 governed by the LPGL version 3 or later, not the LGPL version 2.1 or
41 later.
42 
43 */
44 
45 #ifndef CGU_EXTENSION_H
46 #define CGU_EXTENSION_H
47 
48 /**
49  * @namespace Cgu::Extension
50  * @brief This namespace provides functions to execute scheme code on the guile VM.
51  *
52  * \#include <c++-gtk-utils/extension.h>
53  *
54  * The Extension::exec() and Extension::exec_shared() functions
55  * provided by this library allow any C++ program to execute files
56  * written in the scheme language on the guile VM as part of the C++
57  * runtime. There are a number of reasons why this might be useful:
58  *
59  * @par
60  * - to enable the dynamic behaviour of the program to be altered
61  * without recompilation
62  *
63  * @par
64  * - to provide a plugin system
65  *
66  * @par
67  * - because some things are easier or quicker to do when done in
68  * a dynamically typed language such as scheme
69  *
70  * @par
71  * - because scheme is a nice language to use and highly
72  * extensible
73  *
74  * @par
75  * - with Extension::exec() and Extension::exec_shared(), it is
76  * trivial to do (see the example below)
77  *
78  * To call Extension::exec() or Extension::exec_shared(), guile-2.0 is
79  * required.
80  *
81  * Usage
82  * -----
83  *
84  * Extension::exec() and Extension::exec_shared() take three
85  * arguments. The first is a preamble string, which sets out any top
86  * level definitions which the script file needs to see. This is
87  * mainly intended for argument passing to the script file, but can
88  * comprise any scheme code. It can also be an empty string. The
89  * second is the name of the scheme script file to be executed, with
90  * path. This file can contain scheme code of arbitrary complexity
91  * and length, and can incorporate guile modules and other scheme
92  * files.
93  *
94  * The third argument is a translator. This is a function or callable
95  * object which takes the value to which the scheme file evaluates (in
96  * C++ terms, its return value) as an opaque SCM guile type (it is
97  * actually a pointer to a struct in the guile VM), and converts it to
98  * a suitable C++ representation using functions provided by libguile.
99  * The return value of the translator function comprises the return
100  * value of Extension::exec() and Extension::exec_shared().
101  *
102  * Translators
103  * -----------
104  *
105  * Preformed translators are provided by this library to translate
106  * from scheme's integers, real numbers and strings to C++ longs,
107  * doubles and strings respectively (namely
108  * Extension::integer_to_long(), Extension::real_to_double() and
109  * Extension::string_to_string()), and from any uniform lists of these
110  * to C++ vectors of the corresponding type
111  * (Extension::list_to_vector_long(),
112  * Extension::list_to_vector_double() and
113  * Extension::list_to_vector_string(). There is also a translator for
114  * void return types (Extension::any_to_void()), where the scheme
115  * script is executed for its side effects, perhaps I/O, where the
116  * return value is ignored and any communication necessary is done by
117  * guile exceptions.
118  *
119  * Any guile exception thrown by the code in the scheme file is
120  * trapped by the preformed translators and will be rethrown as an
121  * Extension::GuileException C++ exception. The preformed translators
122  * should suffice for most purposes, but custom translators can be
123  * provided by the user - see further below.
124  *
125  * Example
126  * -------
127  *
128  * Assume the following code is in a file called 'myip.scm'.
129  *
130  * @code
131  * ;; myip.scm
132  *
133  * ;; the following code assumes a top level definition of 'web-ip' is
134  * ;; passed, giving the URL of an IP address reflector
135  *
136  * (use-modules (ice-9 regex)(web uri)(web client))
137  * (let ([uri (build-uri 'http
138  * #:host web-ip
139  * #:port 80
140  * #:path "/")])
141  * (call-with-values
142  * (lambda () (http-get uri))
143  * (lambda (request body)
144  * (match:substring
145  * (string-match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"
146  * body)))))
147  * @endcode
148  *
149  * This code requires guile >= 2.0.3, and makes a http request to the
150  * reflector, reads the body of the reply and then does a regex search
151  * on it to obtain the address. Courtesy of the good folks at DynDNS
152  * we can obtain our address with this:
153  *
154  * @code
155  * using namespace Cgu;
156  * std::cout << "IP address is: "
157  * << Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
158  * "./myip.scm",
159  * &Extension::string_to_string)
160  * << std::endl;
161  * @endcode
162  *
163  * This is easier than doing the same in C++ using, say, libsoup and
164  * std::regex. However it is unsatisfying where we do not want the
165  * code to block waiting for the reply. There are a number of
166  * possible approaches to this, but one is to provide the result to a
167  * glib main loop asynchronously via a Thread::TaskManager object.
168  * There are two possibilities for this. First, the
169  * Thread::TaskManager::make_task_when_full() method could be used, to
170  * which a fail callback could be passed to execute if guile throws an
171  * exception (say because the url does not resolve). Alternatively,
172  * the scheme code in myip.scm could wrap itself in a guile catch
173  * expression, and hand back a list of two strings, the first string
174  * of which indicates an error condition with description (or an empty
175  * string if there is no error), and the second the result on success,
176  * in which case Thread::TaskManager::make_task_when() or
177  * Thread::TaskManager::make_task_compose() could be called. This
178  * does the second:
179  *
180  * @code
181  * ;; myip.scm
182  *
183  * ;; the following code assumes a top level definition of 'web-ip' is
184  * ;; passed, giving the URL of an IP address reflector
185  *
186  * (use-modules (ice-9 regex)(web uri)(web client))
187  * (let ([uri (build-uri 'http
188  * #:host web-ip
189  * #:port 80
190  * #:path "/")])
191  * (catch
192  * #t
193  * (lambda () ;; the 'try' block
194  * (call-with-values
195  * (lambda () (http-get uri))
196  * (lambda (request body)
197  * (list "" ;; empty string for first element of list - no error
198  * (match:substring
199  * (string-match "[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+"
200  * body)))))) ;; ip address as a string
201  * (lambda (key . details) ;; the 'catch' block
202  * (list (string-append "Exception in myip.scm: "
203  * (object->string (cons key details))) ;; exception details
204  * "")))) ;; empty string for second element of list - error
205  * @endcode
206  *
207  * @code
208  * using namespace Cgu;
209  * Thread::TaskManager tm{1};
210  * typedef std::vector<std::string> ResType;
211  * auto when = Callback::to_unique(
212  * Callback::lambda<const ResType&>([] (const ResType& res) {
213  * if (!res[0].empty()) {
214  * // display GtkMessageDialog object indicating failure
215  * }
216  * else {
217  * // publish result in res[1] in some GTK widget
218  * }
219  * }
220  * );
221  * tm.make_task_when (
222  * std::move(when),
223  * 0, // supply result to default glib main loop
224  * [] () {
225  * return Extension::exec_shared("(define web-ip \"checkip.dyndns.com\")",
226  * "./myip.scm",
227  * &Extension::list_to_vector_string);
228  * }
229  * );
230  * @endcode
231  *
232  * Extension::exec() and Extension::exec_shared()
233  * ----------------------------------------------
234  *
235  * Extension::exec() isolates the top level definitions of a task,
236  * including definitions in the preamble of a task or imported by
237  * guile's 'use-modules' or 'load' procedures, from the top level
238  * definitions of other tasks started by calls to Extension::exec(),
239  * by calling guile's 'make-fresh-user-module' procedure.
240  * Extension::exec_shared() does not do so: with
241  * Extension::exec_shared(), all scheme tasks executed by calls to
242  * that function will share the same top level. In addition,
243  * Extension::exec() loads the file passed to the function using the
244  * guile 'load' procedure, so that the first time the file is executed
245  * it is compiled into bytecode, whereas Extension::exec_shared()
246  * calls the 'primitive-load' procedure instead, which runs the file
247  * through the guile interpreter without converting it to bytecode.
248  *
249  * The reason for this different behaviour of Extension::exec_shared()
250  * is that, as currently implemented in guile both the
251  * 'make-fresh-user-module' and 'load' procedures leak small amounts
252  * of memory. If a particular program is likely to call
253  * Extension::exec() more than about 5,000 or 10,000 times, it would
254  * be better to use Extension::exec_shared() instead.
255  *
256  * From guile-2.0.2, Extension::exec() and Extension::exec_shared() do
257  * not need to be called only in the main program thread - and in the
258  * above example using a Thread::TaskManager object
259  * Extension::exec_shared() was not. However, one of the consequences
260  * of the behaviour mentioned above is that if
261  * Extension::exec_shared() is to be used instead of
262  * Extension::exec(), either concurrent calls to the function from
263  * different threads should be avoided, or (i) the preambles in calls
264  * to Extension::exec_shared() should be empty and (ii) tasks should
265  * not make clashing top level definitions in some other way,
266  * including by importing clashing definitions using 'use-modules' or
267  * 'load'. The need for Extension::exec_shared() to be called only in
268  * one thread in the example above was the reason why the TaskManager
269  * object in that example was set to have a maximum thread count of 1.
270  * In effect the TaskManager object was a dedicated serial dispatcher
271  * for all scheme tasks.
272  *
273  * The calling by Extension::exec_shared() of 'primitive-load' instead
274  * of 'load' may have some small effect on efficiency. It it best for
275  * the file passed to that function to hand off any complex code to
276  * modules prepared using guile's modules interface (which will be
277  * compiled into bytecode), and which are then loaded using
278  * 'use-modules' the first time Extension::exec_shared() is called, or
279  * by having the first call to Extension::exec_shared() (and only the
280  * first call) import any needed files into the top level using
281  * 'load'.
282  *
283  * Note that some guile global state may be shared between tasks
284  * whether Extension::exec() or Extension::exec_shared() is used. For
285  * example, if the guile 'add-to-load-path' procedure is called to add
286  * a local directory to the search path used by 'use-modules' or
287  * 'load', that will have effect for all other tasks.
288  *
289  * Other thread safety points
290  * --------------------------
291  *
292  * Leaving aside what has been said above, there are a few other
293  * issues to keep in mind if executing scheme code in more than one
294  * thread.
295  *
296  * First, the initialization of guile < 2.0.10 is not thread safe.
297  * One thread needs to have called Extension::exec() or
298  * Extension::exec_shared() once and returned before any other threads
299  * call the function. This can be achieved by the simple expedient of
300  * executing the statement:
301  *
302  * @code
303  * Extension::exec_shared("", "", &Extension::any_to_void);
304  * @endcode
305  *
306  * and waiting for it to return before any tasks are added to a
307  * TaskManager object running more than one thread. This issue is
308  * fixed in guile-2.0.10. However there is a further snag. Certain
309  * aspects of guile module loading are not thread safe. One way
310  * around this is to load all the modules that tasks may use in
311  * advance, by loading the modules in the preamble of the above
312  * statement (or to have that statement execute a file which loads the
313  * modules). If that is done, it should be fine afterwards to run
314  * Extension::exec() (or Extension::exec_shared() if clashing top
315  * level definitions are avoided as mentioned above) on a TaskManager
316  * object running any number of threads, or on a Thread::Future object
317  * or std::async() task. (However, note that if using
318  * Extension::exec() the modules would need to be reloaded in each
319  * task in order to make them visible to the task, but that would be
320  * done safely if they have previously been loaded in another task.)
321  *
322  * This issue is likely to be fixed in a future version of guile.
323  *
324  * If a C++ program is to run guile tasks on a TaskManager object
325  * having a maximum thread count greater than one (or in more than one
326  * thread in some other way), one other point should be noted. When a
327  * scheme file is executed for the first time by a user by being
328  * passed as the second argument of Extension::exec() (or by having
329  * 'load' applied to it in some other way), it will be compiled into
330  * byte code, the byte code will then be cached on the file system for
331  * that and subsequent calls, and the byte code then executed. Bad
332  * things might happen if concurrent calls to Extension::exec(), or to
333  * the 'load' or 'use-modules' procedures, are made in respect of the
334  * same scheme file for the "first" time, if there might be a race as
335  * to which of them is the "first" call in respect of the file: that
336  * is, if it causes two or more threads to try to compile the same
337  * file into byte code concurrently. This is only an issue the first
338  * time a particular user executes a scheme file, and can be avoided
339  * (amongst other ways) by having the C++ program concerned
340  * pre-compile the relevant scheme file before Extension::exec() or
341  * Extension::exec_shared() is first called, by means of the 'guild
342  * compile [filename]' command. The following gives more information
343  * about compilation: <A
344  * HREF="http://www.gnu.org/software/guile/manual/html_node/Compilation.html#Compilation">
345  * Compiling Scheme Code</A>
346  *
347  * Licence
348  * -------
349  *
350  * The c++-gtk-utils library (and this c++-gtk-utils/extension.h
351  * header file) follows glib and GTK+ by being released under the LGPL
352  * version 2.1 or later. libguile is released under the LGPL version
353  * 3 or later. The c++-gtk-utils library object code does not link to
354  * libguile, nor does it incorporate anything in the
355  * c++-gtk-utils/extension.h header. Instead
356  * c++-gtk-utils/extension.h contains all its code as a separate
357  * unlinked header for any program which wants to include it (this is
358  * partly because some of it comprises template functions).
359  *
360  * There are two consequences. If you want to use Extension::exec()
361  * or Extension::exec_shared(), the program which calls it will need
362  * to link itself explicitly with libguile as well as c++-gtk-utils,
363  * and to do that will need to use pkg-config to obtain libguile's
364  * cflags and libs particulars (its pkg-config file is guile-2.0.pc).
365  * This library does NOT do that for you. Secondly, by linking with
366  * libguile you will be governed by the LGPL version 3 or later,
367  * instead of the LGPL version 2.1 or later, with respect to that
368  * linking. That's fine (there is nothing wrong with the LGPL version
369  * 3 and this library permits that) but you should be aware of it.
370  * The scheme code in guile's scheme level modules is also in the main
371  * released under the LGPL version 3 or later ("in the main" because
372  * readline.scm, comprised in the readline module, is released under
373  * the GPL version 3 or later).
374  *
375  * Custom translators
376  * ------------------
377  *
378  * Any function or callable object which translates from an opaque SCM
379  * value to a suitable C++ representation can be passed as the third
380  * argument of Extension::exec() or Extension::exec_shared(). C++
381  * type deduction on template resolution will take care of everything
382  * else. The translator can execute any functions offered by
383  * libguile, because when the translator is run the program is still
384  * in guile mode. The fulsome guile documentation sets out the
385  * libguile functions which are callable in C/C++ code.
386  *
387  * The first call in a custom translator should normally be to the
388  * Extension::rethrow_guile_exception() function. This function tests
389  * whether a guile exception arose in executing the scheme file, and
390  * throws a C++ exception if it did. The preformed translators in
391  * extension.h provide worked examples of how a custom translator
392  * might be written.
393  *
394  * If something done in a custom translator were to raise a guile
395  * exception, the library implementation would handle it and a C++
396  * exception would be generated in its place in Extension::exec() or
397  * Extension::exec_shared(). However, a custom translator should not
398  * allow a guile exception arising from calls to libguile made by it
399  * to exit a C++ scope in which the translator has constructed a local
400  * C++ object which is not trivially destructible: that would give
401  * rise to undefined behaviour, with the likely result that the C++
402  * object's destructor would not be called. One approach to this
403  * (adopted in the preformed translators) is to allocate on free store
404  * all local C++ objects to be constructed in the translator which are
405  * not trivially destructible, and to manage their lifetimes manually
406  * using local C++ try/catch blocks rather than RAII, with dynwind
407  * unwind handlers to release memory were there to be a guile
408  * exception (but note that no C++ exception should transit out of a
409  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
410  * idea to test for any condition which might cause a guile exception
411  * to be raised in the translator in the first place, and throw a C++
412  * exception beforehand. Then the only condition which might cause a
413  * guile exception to occur in the translator is an out-of-memory
414  * condition, which is highly improbable in a translator as the
415  * translator is run after the guile task has completed. Heap
416  * exhaustion in such a case probably spells doom for the program
417  * concerned anyway, if it has other work to do.
418  *
419  * Note also that code in a custom translator should not store guile
420  * SCM objects (which are pointers to guile scheme objects) in memory
421  * blocks allocated by malloc() or the new expression, or they will
422  * not be seen by the garbage collector used by libguile (which is the
423  * gc library) and therefore may be prematurely deallocated. To keep
424  * such items alive in custom allocators, SCM variables should be kept
425  * as local variables or parameter names in functions (and so stored
426  * on the stack or in registers, where they will be seen by the
427  * garbage collector), or in memory allocated with scm_gc_malloc(),
428  * where they will also be seen by the garbage collector.
429  *
430  * Scheme
431  * ------
432  * If you want to learn more about scheme, these are useful sources:
433  * <P>
434  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
435  * (the rest of the manual is also good reading).</P>
436  * <P>
437  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
438  */
439 
440 #include <string>
441 #include <vector>
442 #include <exception>
443 #include <memory> // for std::unique_ptr
444 #include <type_traits> // for std::remove_reference, std::remove_const and std::result_of
445 #include <limits> // for std::numeric_limits
446 #include <functional> // for std::bind
447 #include <utility> // for std::move
448 #include <new> // for std::bad_alloc
449 
450 #include <stddef.h> // for size_t
451 #include <stdlib.h> // for free()
452 #include <string.h> // for strlen() and strncmp()
453 
454 #include <glib.h>
455 
457 #include <c++-gtk-utils/callback.h>
458 #include <c++-gtk-utils/thread.h>
459 #include <c++-gtk-utils/mutex.h>
461 
462 #include <libguile.h>
463 
464 
465 #ifndef DOXYGEN_PARSING
466 namespace Cgu {
467 
468 namespace Extension {
469 
470 struct FormatArgs {
471  SCM text;
472  SCM rest;
473 };
474 
475 enum VectorDeleteType {Long, Double, String};
476 
477 struct VectorDeleteArgs {
478  VectorDeleteType type;
479  void* vec;
480 };
481 
482 // defined in extension_helper.cpp
483 extern Cgu::Thread::Mutex* get_user_module_mutex();
484 extern bool init_mutex();
485 
486 } // namespace Extension
487 
488 } // namespace Cgu
489 
490 namespace {
491 extern "C" {
492  inline SCM cgu_format_try_handler(void* data) {
493  using Cgu::Extension::FormatArgs;
494  FormatArgs* format_args = static_cast<FormatArgs*>(data);
495  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
496  }
497  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
498  return SCM_BOOL_F;
499  }
500  inline void* cgu_guile_wrapper(void* data) {
501  try {
502  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
503  }
504  // an elipsis catch block is fine as thread cancellation is
505  // blocked. We can only enter this block if assigning to one of
506  // the exception strings in the callback has thrown
507  // std::bad_alloc. For that case we return a non-NULL pointer to
508  // indicate error (the 'data' argument is convenient and
509  // guaranteed to be standard-conforming for this).
510  catch (...) {
511  return data;
512  }
513  return 0;
514  }
515  inline void cgu_delete_vector(void* data) {
516  using Cgu::Extension::VectorDeleteArgs;
517  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
518  switch (args->type) {
519  case Cgu::Extension::Long:
520  delete static_cast<std::vector<long>*>(args->vec);
521  break;
522  case Cgu::Extension::Double:
523  delete static_cast<std::vector<double>*>(args->vec);
524  break;
525  case Cgu::Extension::String:
526  delete static_cast<std::vector<std::string>*>(args->vec);
527  break;
528  default:
529  g_critical("Incorrect argument passed to cgu_delete_vector");
530  }
531  delete args;
532  }
533  inline void cgu_unlock_module_mutex(void*) {
534  // this cannot give rise to an allocation or mutex error -
535  // we must have been called init_mutex() first
536  Cgu::Extension::get_user_module_mutex()->unlock();
537  }
538 } // extern "C"
539 } // unnamed namespace
540 #endif // DOXYGEN_PARSING
541 
542 namespace Cgu {
543 
544 namespace Extension {
545 
546 class GuileException: public std::exception {
547  Cgu::GcharSharedHandle message;
548  Cgu::GcharSharedHandle guile_message;
549 public:
550  virtual const char* what() const throw() {return (const char*)message.get();}
551  const char* guile_text() const throw() {return (const char*)guile_message.get();}
552  GuileException(const char* msg):
553  message(g_strdup_printf("Cgu::Extension::GuileException: %s", msg)),
554  guile_message(g_strdup(msg)) {}
555  ~GuileException() throw() {}
556 };
557 
558 class ReturnValueError: public std::exception {
559  Cgu::GcharSharedHandle message;
560  Cgu::GcharSharedHandle err_message;
561 public:
562  virtual const char* what() const throw() {return (const char*)message.get();}
563  const char* err_text() const throw() {return (const char*)err_message.get();}
564  ReturnValueError(const char* msg):
565  message(g_strdup_printf("Cgu::Extension::ReturnValueError: %s", msg)),
566  err_message(g_strdup(msg)) {}
567  ~ReturnValueError() throw() {}
568 };
569 
570 class WrapperError: public std::exception {
571  Cgu::GcharSharedHandle message;
572 public:
573  virtual const char* what() const throw() {return (const char*)message.get();}
574  WrapperError(const char* msg):
575  message(g_strdup_printf("Cgu::Extension::WrapperError: %s", msg)) {}
576  ~WrapperError() throw() {}
577 };
578 
579 #ifndef DOXYGEN_PARSING
580 
581 // this function has been renamed guile_wrapper_cb2 in version 2.0.28
582 // in order to prevent ODR issues and ensure exec_impl() in 2.0.28
583 // calls the correct version of this function
584 template <class Ret, class TransType>
585 void guile_wrapper_cb2(TransType* translator,
586  std::string* loader,
587  Ret* retval,
588  bool* result,
589  std::string* guile_except,
590  std::string* guile_ret_val_err,
591  std::string* gen_err,
592  bool shared) {
593  SCM scm;
594  if (shared) {
595  scm = scm_eval_string_in_module(scm_from_utf8_string(loader->c_str()),
596  scm_c_resolve_module("guile-user"));
597  }
598  else {
599  if (!init_mutex())
600  throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
601 
602  scm_dynwind_begin(scm_t_dynwind_flags(0));
603  scm_dynwind_unwind_handler(&cgu_unlock_module_mutex, 0, SCM_F_WIND_EXPLICITLY);
604  get_user_module_mutex()->lock(); // won't throw
605  SCM new_mod = scm_call_0(scm_c_public_ref("guile", "make-fresh-user-module"));
606  scm_dynwind_end();
607 
608  scm = scm_eval_string_in_module(scm_from_utf8_string(loader->c_str()),
609  new_mod);
610  }
611 
612  // have a dynwind context and async block while translator is
613  // executing. This is to cater for the pathological case of the
614  // scheme script having set up a signal handler which might throw a
615  // guile exception, or having chained a series of system asyncs
616  // which are still queued for action, which might otherwise cause
617  // the translator to trigger a guile exception while a non-trivially
618  // destructible object is in the local scope of translator. (Highly
619  // unlikely, but easy to deal with.) This is entirely safe as no
620  // C++ exception arising from the translator can transit across the
621  // dynamic context in this function - see below. So we have (i) no
622  // C++ exception can transit across a guile dynamic context, and
623  // (ii) no guile exception can escape out of a local C++ scope by
624  // virtue of an async executing (it might still escape with a
625  // non-trivially destructible object in existence if a custom
626  // translator has not been written correctly, but there is nothing
627  // we can do about that). Note that some guile installations do not
628  // link scm_dynwind_block_asyncs() correctly - this is tested at
629  // configuration time.
630 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
631  scm_dynwind_begin(scm_t_dynwind_flags(0));
632  scm_dynwind_block_asyncs();
633 #endif
634  // we cannot use std::exception_ptr here to store a C++ exception
635  // object, because std::exception_ptr is not trivially destructible
636  // and a guile exception in 'translator' could jump out of this
637  // scope to its continuation in scm_with_guile()
638  bool badalloc = false;
639  try {
640  *retval = (*translator)(scm);
641  *result = true; // this will detect any guile exception in the
642  // preamble or 'translator' which causes
643  // scm_with_guile() to return prematurely. We
644  // have could have done it instead by reversing
645  // the return values of cgu_guile_wrapper
646  // (non-NULL for success and NULL for failure)
647  // because scm_with_guile() returns NULL if it
648  // exits on an uncaught guile exception, but this
649  // approach enables us to discriminate between a
650  // C++ memory exception in the wrapper and a guile
651  // exception in the preamble or 'translator', at a
652  // minimal cost of one assignment to a bool.
653  }
654  catch (Cgu::Extension::GuileException& e) {
655  try {
656  *guile_except = e.guile_text();
657  }
658  catch (...) {
659  badalloc = true;
660  }
661  }
663  try {
664  *guile_ret_val_err = e.err_text();
665  }
666  catch (...) {
667  badalloc = true;
668  }
669  }
670  catch (std::exception& e) {
671  try {
672  *gen_err = e.what();
673  }
674  catch (...) {
675  badalloc = true;
676  }
677  }
678  catch (...) {
679  try {
680  *gen_err = "C++ exception thrown in guile_wrapper_cb()";
681  }
682  catch (...) {
683  badalloc = true;
684  }
685  }
686 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
687  scm_dynwind_end();
688 #endif
689  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
690 }
691 
692 template <class Ret, class Translator>
693 Ret exec_impl(const std::string& preamble,
694  const std::string& file,
695  Translator translator,
696  bool shared) {
697 
699 
700  std::string loader;
701  loader += preamble;
702  if (!file.empty()) {
703  if (shared)
704  loader += "((lambda ()";
705  loader += "(catch "
706  "#t"
707  "(lambda ()"
708  "(";
709  if (shared)
710  loader += "primitive-load \"";
711  else
712  loader += "load \"";
713  loader += file;
714  loader += "\"))"
715  "(lambda (key . details)"
716  "(cons \"***cgu-guile-exception***\" (cons key details))))";
717  if (shared)
718  loader += "))";
719  }
720 
721  Ret retval;
722  bool result = false;
723  std::string guile_except;
724  std::string guile_ret_val_err;
725  std::string gen_err;
726 
727  // we construct a Callback::Callback object here to perform type
728  // erasure. Otherwise we would have to pass scm_with_guile() a
729  // function pointer to a function templated on Translator and Ret,
730  // which must have C++ language linkage (§14/4 of C++ standard).
731  // Technically this would give undefined behaviour as
732  // scm_with_guile() expects a function pointer with C language
733  // linkage, although gcc and clang would accept it. The whole of
734  // this callback will be executed in guile mode via
735  // cgu_guile_wrapper(), so it can safely call libguile functions
736  // (provided that a translator does not allow any guile exceptions
737  // to escape a C++ scope with local objects which are not trivially
738  // destructible). It is also safe to pass 'translator', 'retval',
739  // 'loader', 'result' and the exception strings to it by reference,
740  // because scm_with_guile() will block until it has completed
741  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
742  // exception thrown by the string assignments in the catch blocks in
743  // guile_wrapper_cb. guile_wrapper_cb is safe against a jump to an
744  // exit from scm_with_guile() arising from a native guile exception
745  // in translator, because its body has no objects in local scope
746  // requiring destruction.
747  std::unique_ptr<Cgu::Callback::Callback> cb(
748  Cgu::Callback::lambda<>(std::bind(&guile_wrapper_cb2<Ret, Translator>,
749  &translator,
750  &loader,
751  &retval,
752  &result,
753  &guile_except,
754  &guile_ret_val_err,
755  &gen_err,
756  shared))
757  );
758  // cgu_guile_wrapper(), and so scm_with_guile() will return a
759  // non-NULL value if assigning to one of the exception description
760  // strings above threw std::bad_alloc
761  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
762  throw WrapperError("cgu_guile_wrapper() has trapped std::bad_alloc");
763  if (!guile_except.empty())
764  throw GuileException(guile_except.c_str());
765  if (!guile_ret_val_err.empty())
766  throw ReturnValueError(guile_ret_val_err.c_str());
767  if (!gen_err.empty())
768  throw WrapperError(gen_err.c_str());
769  if (!result)
770  throw WrapperError("the preamble or translator threw a native guile exception");
771  return retval;
772 }
773 
774 #endif // DOXYGEN_PARSING
775 
776 /**
777  * This function is called by Extension::rethrow_guile_exception()
778  * where the scheme code executed by Extension::exec() or
779  * Extension::exec_shared() has exited with a guile exception. It
780  * converts the raw guile exception information represented by the
781  * 'key' and 'args' arguments of a guile catch handler to a more
782  * readable form. It is made available as part of the public
783  * interface so that any custom translators can also use it if they
784  * choose to provide their own catch expressions. This function does
785  * not throw any C++ exceptions. No native guile exception will arise
786  * in this function and so cause guile to jump out of it assuming no
787  * guile out-of-memory condition occurs (and given that this function
788  * is called after a guile extension task has completed, such a
789  * condition is very improbable). It is thread safe, but see the
790  * comments above about the thread safety of Extension::exec() and
791  * Extension::exec_shared().
792  *
793  * @param key An opaque guile SCM object representing a symbol
794  * comprising the 'key' argument of the exception handler of a guile
795  * catch expression.
796  * @param args An opaque guile SCM object representing a list
797  * comprising the 'args' argument of the exception handler of a guile
798  * catch expression.
799  * @return An opaque guile SCM object representing a guile string.
800  *
801  * Since 2.0.22
802  */
803 inline SCM exception_to_string(SCM key, SCM args) {
804  // The args of most exceptions thrown by guile are in the following format:
805  // (car args) - a string comprising the name of the procedure generating the exception
806  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
807  // (caddr args) - a list containing items matching the format directives, or #f if none
808  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
809  // or #f if none
810  SCM ret = SCM_BOOL_F;
811  int length = scm_to_int(scm_length(args));
812  if (length) {
813  SCM first = scm_car(args);
814  if (scm_is_true(scm_string_p(first))) {
815  // if a single user string, output it
816  if (length == 1) {
817  ret = scm_string_append(scm_list_4(scm_from_utf8_string("Exception "),
818  scm_symbol_to_string(key),
819  scm_from_utf8_string(": "),
820  first));
821  }
822  else { // length > 1
823  SCM second = scm_cadr(args);
824  if (scm_is_true(scm_string_p(second))) {
825  // we should have a standard guile exception string, as above
826  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string("Exception "),
827  scm_symbol_to_string(key),
828  scm_from_utf8_string(" in procedure "),
829  first,
830  scm_from_utf8_string(": "),
831  second,
832  SCM_UNDEFINED));
833  if (length == 2)
834  ret = text;
835  else { // length > 2
836  SCM third = scm_caddr(args);
837  if (scm_is_false(third))
838  ret = text;
839  else if (scm_is_true(scm_list_p(third))) {
840  FormatArgs format_args = {text, third};
841  ret = scm_internal_catch(SCM_BOOL_T,
842  &cgu_format_try_handler,
843  &format_args,
844  &cgu_format_catch_handler,
845  0);
846  }
847  }
848  }
849  }
850  }
851  }
852  // fall back to generic formatting if first or second elements of
853  // args is not a string or simple-format failed above
854  if (scm_is_false(ret)) {
855  // there is no need for a catch block: we know simple-format
856  // cannot raise an exception here
857  ret = scm_simple_format(SCM_BOOL_F,
858  scm_from_utf8_string("Exception ~S: ~S"),
859  scm_list_2(key, args));
860  }
861  return ret;
862 }
863 
864 /**
865  * This function tests whether a guile exception arose in executing a
866  * scheme extension file, and throws Cgu::Extension::GuileException if
867  * it did. It is intended for use by custom translators, as the first
868  * thing the translator does. It is thread safe, but see the comments
869  * above about the thread safety of Extension::exec() and
870  * Extension::exec_shared().
871  *
872  * @param scm An opaque guile SCM object representing the value to
873  * which the extension file passed to Extension::exec() or
874  * Extension::exec_shared() evaluated.
875  * @exception std::bad_alloc This function might throw std::bad_alloc
876  * if memory is exhausted and the system throws in that case.
877  * @exception Cgu::Extension::GuileException This exception will be
878  * thrown if the scheme code executed in the extension file passed to
879  * Extension::exec() or Extension::exec_shared() threw a guile
880  * exception. Cgu::Extension::GuileException::what() will give
881  * particulars of the guile exception thrown, in UTF-8 encoding.
882  * @note No native guile exception will arise in this function and so
883  * cause guile to jump out of it if no guile out-of-memory condition
884  * occurs (given that this function is called after a guile extension
885  * task has completed, such a condition is very improbable).
886  *
887  * Since 2.0.22
888  */
889 inline void rethrow_guile_exception(SCM scm) {
890  // guile exceptions are always presented to this function as a
891  // scheme list
892  if (scm_is_false(scm_list_p(scm))
893  || scm_is_true(scm_null_p(scm))) return;
894  SCM first = scm_car(scm);
895  if (scm_is_true(scm_string_p(first))) {
896  size_t len;
897  const char* text = 0;
898  // nothing in this function should throw a guile exception unless
899  // there is a guile out-of-memory exception (which is extremely
900  // improbable). However, let's cover ourselves in case
901  scm_dynwind_begin(scm_t_dynwind_flags(0));
902  char* car = scm_to_utf8_stringn(first, &len);
903  // there may be a weakness in guile's implementation here: if
904  // calling scm_dynwind_unwind_handler() were to give rise to an
905  // out-of-memory exception before the handler is set up by it,
906  // then we could leak memory allocated from the preceding call to
907  // scm_to_utf8_stringn(). Whether that could happen is not
908  // documented, but because (a) it is so improbable, and (b) once
909  // we are in out-of-memory land we are already in severe trouble
910  // and glib is likely to terminate the program at some point
911  // anyway, it is not worth troubling ourselves over.
912  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
913  if (len == strlen("***cgu-guile-exception***")
914  && !strncmp(car, "***cgu-guile-exception***", len)) {
915  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
916  // we don't need a dynwind handler for 'text' because nothing
917  // after the call to scm_to_utf8_stringn() can cause a guile
918  // exception to be raised
919  text = scm_to_utf8_stringn(str, &len);
920  }
921  // all done - no more guile exceptions are possible in this
922  // function after this so end the dynamic context, take control of
923  // the memory by RAII and if necessary throw a C++ exception
924  scm_dynwind_end();
925  std::unique_ptr<char, Cgu::CFree> up_car(car);
926  std::unique_ptr<const char, Cgu::CFree> up_text(text);
927  // if 'text' is not NULL, 'len' contains its length in bytes
928  if (text) throw GuileException(std::string(text, len).c_str());
929  }
930 }
931 
932 /**
933  * A translator function which can be passed to the third argument of
934  * Extension::exec() or Extension::exec_shared(). It converts from a
935  * homogeneous scheme list of integers to a C++ representation of
936  * std::vector<long>. It is thread safe, but see the comments above
937  * about the thread safety of Extension::exec() and
938  * Extension::exec_shared().
939  *
940  * @param scm An opaque guile SCM object representing the value to
941  * which the extension file passed to Extension::exec() or
942  * Extension::exec_shared() evaluated, where that value is a
943  * homogeneous list of integers.
944  * @return The std::vector<long> representation.
945  * @exception std::bad_alloc This function might throw std::bad_alloc
946  * if memory is exhausted and the system throws in that case, or if
947  * the length of the input list exceeds std::vector::max_size().
948  * @exception Cgu::Extension::GuileException This exception will be
949  * thrown if the scheme code in the extension file passed to
950  * Extension::exec() or Extension::exec_shared() caused a guile
951  * exception to be thrown. Cgu::Extension::GuileException::what()
952  * will give particulars of the guile exception thrown, in UTF-8
953  * encoding.
954  * @exception Cgu::Extension::ReturnValueError This exception will be
955  * thrown if the scheme code in the extension file passed to
956  * Extension::exec() or Extension::exec_shared() does not evaluate to
957  * the type expected by the translator, or it is out of range for a
958  * long.
959  * @note No native guile exception will arise in this function and so
960  * cause guile to jump out of it unless a guile out-of-memory
961  * condition occurs (given that this function is called after a guile
962  * extension task has completed, such a condition is very improbable)
963  * or the length of the input list exceeds SIZE_MAX (the maximum value
964  * of std::size_t). If such an exception were to arise, the
965  * implementation would handle it and a C++ exception would be
966  * generated in its place in Extension::exec() or
967  * Extension::exec_shared().
968  *
969  * Since 2.0.22
970  */
971 inline std::vector<long> list_to_vector_long(SCM scm) {
973  if (scm_is_false(scm_list_p(scm)))
974  throw ReturnValueError("scheme code did not evaluate to a list\n");
975 
976  // nothing in this function should throw a guile exception unless
977  // there is a guile out-of-memory exception (which is extremely
978  // improbable). However, let's cover ourselves in case.
979  scm_dynwind_begin(scm_t_dynwind_flags(0));
980  // we cannot have a std::vector object in a scope where a guile
981  // exception might be raised because it has a non-trivial
982  // destructor, nor can we use RAII. Instead allocate on free store
983  // and manage the memory by hand until we can no longer jump on a
984  // guile exception. In addition we cannot store a C++ exception
985  // using std::exception_ptr because std::exception_ptr is not
986  // trivially destructible.
987  bool badalloc = false;
988  const char* rv_error = 0;
989  std::vector<long>* res = 0;
990  VectorDeleteArgs* args = 0;
991  try {
992  // it doesn't matter if the second allocation fails, as we clean
993  // up at the end if there is no guile exception, and if both
994  // allocations succeed and there were to be a subsequent guile
995  // exception, cgu_delete_vector cleans up
996  res = new std::vector<long>;
997  // allocate 'args' on free store, because the continuation in
998  // which it executes will be up the stack
999  args = new VectorDeleteArgs{Long, res};
1000  }
1001  catch (...) {
1002  badalloc = true;
1003  }
1004  if (!badalloc) {
1005  // there may be a weakness in guile's implementation here: if
1006  // calling scm_dynwind_unwind_handler() were to give rise to a
1007  // guile out-of-memory exception before the handler is set up by
1008  // it, then we could leak memory allocated from the preceding new
1009  // expressions. Whether that could happen is not documented by
1010  // guile, but because (a) it is so improbable, and (b) once we are
1011  // in out-of-memory land we are already in severe trouble and glib
1012  // is likely to terminate the program at some point anyway, it is
1013  // not worth troubling ourselves over.
1014  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1015  // convert the list to a guile vector so we can access its items
1016  // efficiently in a for loop. This conversion is reasonably
1017  // efficient, in the sense that an ordinary guile vector is an
1018  // array of pointers, pointing to the same scheme objects that the
1019  // list refers to
1020  SCM guile_vec = scm_vector(scm);
1021 
1022  // std::vector::size_type is the same as size_t with the standard
1023  // allocators (but if we were to get a silent narrowing conversion
1024  // on calling std::vector::reserve() below, that doesn't matter -
1025  // instead if 'length' is less than SIZE_MAX but greater than the
1026  // maximum value of std::vector::size_type, at some point a call
1027  // to std::vector::push_back() below would throw and be caught,
1028  // and this function would end up rethrowing it as std::bad_alloc.
1029  // If in a particular implementation SIZE_MAX exceeds
1030  // std::vector::max_size(), a std::length_error exception would be
1031  // thrown by reserve() where max_size() is exceeded. On all
1032  // common implementations, max_size() is equal to SIZE_MAX, but
1033  // were such an exception to arise it would be swallowed (see
1034  // below) and then rethrown by this function as std::bad_alloc.
1035  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1036  // exception would be thrown by scm_to_size_t() which would be
1037  // rethrown by Cgu:Extension::exec() or
1038  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1039  // C++ exception. This is nice to know but in practice such large
1040  // lists would be unusably slow and a memory exception would be
1041  // reached long before std::vector::max_size() or SIZE_MAX are
1042  // exceeded.
1043  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1044  try {
1045  res->reserve(length);
1046  }
1047  catch (...) {
1048  badalloc = true;
1049  }
1050  for (size_t count = 0;
1051  count < length && !rv_error && !badalloc;
1052  ++count) {
1053  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1054  if (scm_is_false(scm_integer_p(item)))
1055  rv_error = "scheme code did not evaluate to a homogeneous list of integer\n";
1056  else {
1057  SCM min = scm_from_long(std::numeric_limits<long>::min());
1058  SCM max = scm_from_long(std::numeric_limits<long>::max());
1059  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1060  rv_error = "scheme code evaluated out of range for long\n";
1061  else {
1062  try {
1063  res->push_back(scm_to_long(item));
1064  }
1065  catch (...) {
1066  badalloc = true;
1067  }
1068  }
1069  }
1070  }
1071  }
1072  // all done - no more guile exceptions are possible in this function
1073  // after this so end the dynamic context, take control of the memory
1074  // by RAII and if necessary throw a C++ exception
1075  scm_dynwind_end();
1076  std::unique_ptr<std::vector<long>> up_res(res);
1077  std::unique_ptr<VectorDeleteArgs> up_args(args);
1078  if (badalloc) throw std::bad_alloc();
1079  if (rv_error) throw ReturnValueError(rv_error);
1080  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1081  // semantics here, so force it by hand
1082  return std::move(*res);
1083 }
1084 
1085 /**
1086  * A translator function which can be passed to the third argument of
1087  * Extension::exec() or Extension::exec_shared(). It converts from a
1088  * homogeneous scheme list of real numbers to a C++ representation of
1089  * std::vector<double>. It is thread safe, but see the comments above
1090  * about the thread safety of Extension::exec() and
1091  * Extension::exec_shared().
1092  *
1093  * @param scm An opaque guile SCM object representing the value to
1094  * which the extension file passed to Extension::exec() or
1095  * Extension::exec_shared() evaluated, where that value is a
1096  * homogeneous list of real numbers.
1097  * @return The std::vector<double> representation.
1098  * @exception std::bad_alloc This function might throw std::bad_alloc
1099  * if memory is exhausted and the system throws in that case, or if
1100  * the length of the input list exceeds std::vector::max_size().
1101  * @exception Cgu::Extension::GuileException This exception will be
1102  * thrown if the scheme code in the extension file passed to
1103  * Extension::exec() or Extension::exec_shared() caused a guile
1104  * exception to be thrown. Cgu::Extension::GuileException::what()
1105  * will give particulars of the guile exception thrown, in UTF-8
1106  * encoding.
1107  * @exception Cgu::Extension::ReturnValueError This exception will be
1108  * thrown if the scheme code in the extension file passed to
1109  * Extension::exec() or Extension::exec_shared() does not evaluate to
1110  * the type expected by the translator, or it is out of range for a
1111  * double.
1112  * @note 1. Prior to version 2.0.25, this translator had a bug which
1113  * caused an out-of-range Cgu::Extension::ReturnValueError to be
1114  * thrown if any of the numbers in the list to which the scheme code
1115  * in the extension file evaluated was 0.0 or a negative number. This
1116  * was fixed in version 2.0.25.
1117  * @note 2. No native guile exception will arise in this function and
1118  * so cause guile to jump out of it unless a guile out-of-memory
1119  * condition occurs (given that this function is called after a guile
1120  * extension task has completed, such a condition is very improbable)
1121  * or the length of the input list exceeds SIZE_MAX (the maximum value
1122  * of std::size_t). If such an exception were to arise, the
1123  * implementation would handle it and a C++ exception would be
1124  * generated in its place in Extension::exec() or
1125  * Extension::exec_shared().
1126  *
1127  * Since 2.0.22
1128  */
1129 inline std::vector<double> list_to_vector_double(SCM scm) {
1131  if (scm_is_false(scm_list_p(scm)))
1132  throw ReturnValueError("scheme code did not evaluate to a list\n");
1133 
1134  // nothing in this function should throw a guile exception unless
1135  // there is a guile out-of-memory exception (which is extremely
1136  // improbable). However, let's cover ourselves in case.
1137  scm_dynwind_begin(scm_t_dynwind_flags(0));
1138  // we cannot have a std::vector object in a scope where a guile
1139  // exception might be raised because it has a non-trivial
1140  // destructor, nor can we use RAII. Instead allocate on free store
1141  // and manage the memory by hand until we can no longer jump on a
1142  // guile exception. In addition we cannot store a C++ exception
1143  // using std::exception_ptr because std::exception_ptr is not
1144  // trivially destructible.
1145  bool badalloc = false;
1146  const char* rv_error = 0;
1147  std::vector<double>* res = 0;
1148  VectorDeleteArgs* args = 0;
1149  try {
1150  // it doesn't matter if the second allocation fails, as we clean
1151  // up at the end if there is no guile exception, and if both
1152  // allocations succeed and there were to be a subsequent guile
1153  // exception, cgu_delete_vector cleans up
1154  res = new std::vector<double>;
1155  // allocate 'args' on free store, because the continuation in
1156  // which it executes will be up the stack
1157  args = new VectorDeleteArgs{Double, res};
1158  }
1159  catch (...) {
1160  badalloc = true;
1161  }
1162  if (!badalloc) {
1163  // there may be a weakness in guile's implementation here: if
1164  // calling scm_dynwind_unwind_handler() were to give rise to a
1165  // guile out-of-memory exception before the handler is set up by
1166  // it, then we could leak memory allocated from the preceding
1167  // new expressions. Whether that could happen is not documented
1168  // by guile, but because (a) it is so improbable, and (b) once
1169  // we are in out-of-memory land we are already in severe trouble
1170  // and glib is likely to terminate the program at some point
1171  // anyway, it is not worth troubling ourselves over.
1172  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1173  // convert the list to a guile vector so we can access its items
1174  // efficiently in a for loop. This conversion is reasonably
1175  // efficient, in the sense that an ordinary guile vector is an
1176  // array of pointers, pointing to the same scheme objects that the
1177  // list refers to
1178  SCM guile_vec = scm_vector(scm);
1179 
1180  // std::vector::size_type is the same as size_t with the standard
1181  // allocators (but if we were to get a silent narrowing conversion
1182  // on calling std::vector::reserve() below, that doesn't matter -
1183  // instead if 'length' is less than SIZE_MAX but greater than the
1184  // maximum value of std::vector::size_type, at some point a call
1185  // to std::vector::push_back() below would throw and be caught,
1186  // and this function would end up rethrowing it as std::bad_alloc.
1187  // If in a particular implementation SIZE_MAX exceeds
1188  // std::vector::max_size(), a std::length_error exception would be
1189  // thrown by reserve() where max_size() is exceeded. On all
1190  // common implementations, max_size() is equal to SIZE_MAX, but
1191  // were such an exception to arise it would be swallowed (see
1192  // below) and then rethrown by this function as std::bad_alloc.
1193  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1194  // exception would be thrown by scm_to_size_t() which would be
1195  // rethrown by Cgu:Extension::exec() or
1196  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1197  // C++ exception. This is nice to know but in practice such large
1198  // lists would be unusably slow and a memory exception would be
1199  // reached long before std::vector::max_size() or SIZE_MAX are
1200  // exceeded.
1201  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1202  try {
1203  res->reserve(length);
1204  }
1205  catch (...) {
1206  badalloc = true;
1207  }
1208  for (size_t count = 0;
1209  count < length && !rv_error && !badalloc;
1210  ++count) {
1211  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1212  if (scm_is_false(scm_real_p(item)))
1213  rv_error = "scheme code did not evaluate to a homogeneous list of real numbers\n";
1214  else {
1215  SCM min = scm_from_double(-std::numeric_limits<double>::max());
1216  SCM max = scm_from_double(std::numeric_limits<double>::max());
1217  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1218  rv_error = "scheme code evaluated out of range for double\n";
1219  else {
1220  try {
1221  res->push_back(scm_to_double(item));
1222  }
1223  catch (...) {
1224  badalloc = true;
1225  }
1226  }
1227  }
1228  }
1229  }
1230  // all done - no more guile exceptions are possible in this function
1231  // after this so end the dynamic context, take control of the memory
1232  // by RAII and if necessary throw a C++ exception
1233  scm_dynwind_end();
1234  std::unique_ptr<std::vector<double>> up_res(res);
1235  std::unique_ptr<VectorDeleteArgs> up_args(args);
1236  if (badalloc) throw std::bad_alloc();
1237  if (rv_error) throw ReturnValueError(rv_error);
1238  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1239  // semantics here, so force it by hand
1240  return std::move(*res);
1241 }
1242 
1243 /**
1244  * A translator function which can be passed to the third argument of
1245  * Extension::exec() or Extension::exec_shared(). It converts from a
1246  * homogeneous scheme list of strings to a C++ representation of
1247  * std::vector<std::string>. It is thread safe, but see the comments
1248  * above about the thread safety of Extension::exec() and
1249  * Extension::exec_shared().
1250  *
1251  * The returned strings will be in UTF-8 encoding.
1252  *
1253  * Note that the first string in the returned list must not be
1254  * "***cgu-guile-exception***": that string is reserved to the
1255  * implementation.
1256  *
1257  * @param scm An opaque guile SCM object representing the value to
1258  * which the extension file passed to Extension::exec() or
1259  * Extension::exec_shared() evaluated, where that value is a
1260  * homogeneous list of strings.
1261  * @return The std::vector<std::string> representation.
1262  * @exception std::bad_alloc This function might throw std::bad_alloc
1263  * if memory is exhausted and the system throws in that case, or if
1264  * the length of the input list exceeds std::vector::max_size().
1265  * @exception Cgu::Extension::GuileException This exception will be
1266  * thrown if the scheme code in the extension file passed to
1267  * Extension::exec() or Extension::exec_shared() caused a guile
1268  * exception to be thrown. Cgu::Extension::GuileException::what()
1269  * will give particulars of the guile exception thrown, in UTF-8
1270  * encoding.
1271  * @exception Cgu::Extension::ReturnValueError This exception will be
1272  * thrown if the scheme code in the extension file passed to
1273  * Extension::exec() or Extension::exec_shared() does not evaluate to
1274  * the type expected by the translator.
1275  * @note No native guile exception will arise in this function and so
1276  * cause guile to jump out of it unless a guile out-of-memory
1277  * condition occurs (given that this function is called after a guile
1278  * extension task has completed, such a condition is very improbable)
1279  * or the length of the input list exceeds SIZE_MAX (the maximum value
1280  * of std::size_t). If such an exception were to arise, the
1281  * implementation would handle it and a C++ exception would be
1282  * generated in its place in Extension::exec() or
1283  * Extension::exec_shared().
1284  *
1285  * Since 2.0.22
1286  */
1287 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1289  if (scm_is_false(scm_list_p(scm)))
1290  throw ReturnValueError("scheme code did not evaluate to a list\n");
1291 
1292  // nothing in this function should throw a guile exception unless
1293  // there is a guile out-of-memory exception (which is extremely
1294  // improbable). However, let's cover ourselves in case.
1295  scm_dynwind_begin(scm_t_dynwind_flags(0));
1296  // we cannot have a std::vector object in a scope where a guile
1297  // exception might be raised because it has a non-trivial
1298  // destructor, nor can we use RAII. Instead allocate on free store
1299  // and manage the memory by hand until we can no longer jump on a
1300  // guile exception. In addition we cannot store a C++ exception
1301  // using std::exception_ptr because std::exception_ptr is not
1302  // trivially destructible.
1303  bool badalloc = false;
1304  const char* rv_error = 0;
1305  std::vector<std::string>* res = 0;
1306  VectorDeleteArgs* args = 0;
1307  try {
1308  // it doesn't matter if the second allocation fails, as we clean
1309  // up at the end if there is no guile exception, and if both
1310  // allocations succeed and there were to be a subsequent guile
1311  // exception, cgu_delete_vector cleans up
1312  res = new std::vector<std::string>;
1313  // allocate 'args' on free store, because the continuation in
1314  // which it executes will be up the stack
1315  args = new VectorDeleteArgs{String, res};
1316  }
1317  catch (...) {
1318  badalloc = true;
1319  }
1320  if (!badalloc) {
1321  // there may be a weakness in guile's implementation here: if
1322  // calling scm_dynwind_unwind_handler() were to give rise to a
1323  // guile out-of-memory exception before the handler is set up by
1324  // it, then we could leak memory allocated from the preceding new
1325  // expressions. Whether that could happen is not documented by
1326  // guile, but because (a) it is so improbable, and (b) once we are
1327  // in out-of-memory land we are already in severe trouble and glib
1328  // is likely to terminate the program at some point anyway, it is
1329  // not worth troubling ourselves over.
1330  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1331  // convert the list to a guile vector so we can access its items
1332  // efficiently in a for loop. This conversion is reasonably
1333  // efficient, in the sense that an ordinary guile vector is an
1334  // array of pointers, pointing to the same scheme objects that the
1335  // list refers to
1336  SCM guile_vec = scm_vector(scm);
1337 
1338  // std::vector::size_type is the same as size_t with the standard
1339  // allocators (but if we were to get a silent narrowing conversion
1340  // on calling std::vector::reserve() below, that doesn't matter -
1341  // instead if 'length' is less than SIZE_MAX but greater than the
1342  // maximum value of std::vector::size_type, at some point a call
1343  // to std::vector::emplace_back() below would throw and be caught,
1344  // and this function would end up rethrowing it as std::bad_alloc.
1345  // If in a particular implementation SIZE_MAX exceeds
1346  // std::vector::max_size(), a std::length_error exception would be
1347  // thrown by reserve() where max_size() is exceeded. On all
1348  // common implementations, max_size() is equal to SIZE_MAX, but
1349  // were such an exception to arise it would be swallowed (see
1350  // below) and then rethrown by this function as std::bad_alloc.
1351  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1352  // exception would be thrown by scm_to_size_t() which would be
1353  // rethrown by Cgu:Extension::exec() or
1354  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1355  // C++ exception. This is nice to know but in practice such large
1356  // lists would be unusably slow and a memory exception would be
1357  // reached long before std::vector::max_size() or SIZE_MAX are
1358  // exceeded.
1359  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1360  try {
1361  res->reserve(length);
1362  }
1363  catch (...) {
1364  badalloc = true;
1365  }
1366  for (size_t count = 0;
1367  count < length && !rv_error && !badalloc;
1368  ++count) {
1369  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1370  if (scm_is_false(scm_string_p(item)))
1371  rv_error = "scheme code did not evaluate to a homogeneous list of string\n";
1372  else {
1373  size_t len;
1374  // we don't need a dynwind handler for 'str' because nothing
1375  // after the call to scm_to_utf8_stringn() and before the call
1376  // to free() can cause a guile exception to be raised
1377  char* str = scm_to_utf8_stringn(item, &len);
1378  try {
1379  res->emplace_back(str, len);
1380  }
1381  catch (...) {
1382  badalloc = true;
1383  }
1384  free(str);
1385  }
1386  }
1387  }
1388  // all done - no more guile exceptions are possible in this function
1389  // after this so end the dynamic context, take control of the memory
1390  // by RAII and if necessary throw a C++ exception
1391  scm_dynwind_end();
1392  std::unique_ptr<std::vector<std::string>> up_res(res);
1393  std::unique_ptr<VectorDeleteArgs> up_args(args);
1394  if (badalloc) throw std::bad_alloc();
1395  if (rv_error) throw ReturnValueError(rv_error);
1396  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1397  // semantics here, so force it by hand
1398  return std::move(*res);
1399 }
1400 
1401 /**
1402  * A translator function which can be passed to the third argument of
1403  * Extension::exec() or Extension::exec_shared(). It converts from a
1404  * scheme integer to a C++ representation of long. It is thread safe,
1405  * but see the comments above about the thread safety of
1406  * Extension::exec() and Extension::exec_shared().
1407  *
1408  * @param scm An opaque guile SCM object representing the value to
1409  * which the extension file passed to Extension::exec() or
1410  * Extension::exec_shared() evaluated, where that value is an integer.
1411  * @return The C++ long representation.
1412  * @exception std::bad_alloc This function might throw std::bad_alloc
1413  * if memory is exhausted and the system throws in that case.
1414  * @exception Cgu::Extension::GuileException This exception will be
1415  * thrown if the scheme code in the extension file passed to
1416  * Extension::exec() or Extension::exec_shared() caused a guile
1417  * exception to be thrown. Cgu::Extension::GuileException::what()
1418  * will give particulars of the guile exception thrown, in UTF-8
1419  * encoding.
1420  * @exception Cgu::Extension::ReturnValueError This exception will be
1421  * thrown if the scheme code in the extension file passed to
1422  * Extension::exec() or Extension::exec_shared() does not evaluate to
1423  * the type expected by the translator, or it is out of range for a
1424  * long.
1425  * @note No native guile exception will arise in this function and so
1426  * cause guile to jump out of it if no guile out-of-memory condition
1427  * occurs (given that this function is called after a guile extension
1428  * task has completed, such a condition is very improbable). If such
1429  * an exception were to arise, the implementation would handle it and
1430  * a C++ exception would be generated in its place in
1431  * Extension::exec() or Extension::exec_shared().
1432  *
1433  * Since 2.0.22
1434  */
1435 inline long integer_to_long(SCM scm) {
1437  if (scm_is_false(scm_integer_p(scm)))
1438  throw ReturnValueError("scheme code did not evaluate to an integer\n");
1439  SCM min = scm_from_long(std::numeric_limits<long>::min());
1440  SCM max = scm_from_long(std::numeric_limits<long>::max());
1441  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1442  throw ReturnValueError("scheme code evaluated out of range for long\n");
1443  return scm_to_long(scm);
1444 }
1445 
1446 /**
1447  * A translator function which can be passed to the third argument of
1448  * Extension::exec() or Extension::exec_shared(). It converts from a
1449  * scheme real number to a C++ representation of double. It is thread
1450  * safe, but see the comments above about the thread safety of
1451  * Extension::exec() and Extension::exec_shared().
1452  *
1453  * @param scm An opaque guile SCM object representing the value to
1454  * which the extension file passed to Extension::exec() or
1455  * Extension::exec_shared() evaluated, where that value is a real
1456  * number.
1457  * @return The C++ double representation.
1458  * @exception std::bad_alloc This function might throw std::bad_alloc
1459  * if memory is exhausted and the system throws in that case.
1460  * @exception Cgu::Extension::GuileException This exception will be
1461  * thrown if the scheme code in the extension file passed to
1462  * Extension::exec() or Extension::exec_shared() caused a guile
1463  * exception to be thrown. Cgu::Extension::GuileException::what()
1464  * will give particulars of the guile exception thrown, in UTF-8
1465  * encoding.
1466  * @exception Cgu::Extension::ReturnValueError This exception will be
1467  * thrown if the scheme code in the extension file passed to
1468  * Extension::exec() or Extension::exec_shared() does not evaluate to
1469  * the type expected by the translator, or it is out of range for a
1470  * double.
1471  * @note 1. Prior to version 2.0.25, this translator had a bug which
1472  * caused an out-of-range Cgu::Extension::ReturnValueError to be
1473  * thrown if the scheme code in the extension file evaluated to 0.0 or
1474  * a negative number. This was fixed in version 2.0.25.
1475  * @note 2. No native guile exception will arise in this function and
1476  * so cause guile to jump out of it if no guile out-of-memory
1477  * condition occurs (given that this function is called after a guile
1478  * extension task has completed, such a condition is very improbable).
1479  * If such an exception were to arise, the implementation would handle
1480  * it and a C++ exception would be generated in its place in
1481  * Extension::exec() or Extension::exec_shared().
1482  *
1483  * Since 2.0.22
1484  */
1485 inline double real_to_double(SCM scm) {
1487  if (scm_is_false(scm_real_p(scm)))
1488  throw ReturnValueError("scheme code did not evaluate to a real number\n");
1489  SCM min = scm_from_double(-std::numeric_limits<double>::max());
1490  SCM max = scm_from_double(std::numeric_limits<double>::max());
1491  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1492  throw ReturnValueError("scheme code evaluated out of range for double\n");
1493  return scm_to_double(scm);
1494 }
1495 
1496 /**
1497  * A translator function which can be passed to the third argument of
1498  * Extension::exec() or Extension::exec_shared(). It converts from a
1499  * scheme string to a C++ representation of std::string. It is thread
1500  * safe, but see the comments above about the thread safety of
1501  * Extension::exec() and Extension::exec_shared().
1502  *
1503  * The returned string will be in UTF-8 encoding.
1504  *
1505  * @param scm An opaque guile SCM object representing the value to
1506  * which the extension file passed to Extension::exec() or
1507  * Extension::exec_shared() evaluated, where that value is a string.
1508  * @return The std::string representation.
1509  * @exception std::bad_alloc This function might throw std::bad_alloc
1510  * if memory is exhausted and the system throws in that case.
1511  * @exception Cgu::Extension::GuileException This exception will be
1512  * thrown if the scheme code in the extension file passed to
1513  * Extension::exec() or Extension::exec_shared() caused a guile
1514  * exception to be thrown. Cgu::Extension::GuileException::what()
1515  * will give particulars of the guile exception thrown, in UTF-8
1516  * encoding.
1517  * @exception Cgu::Extension::ReturnValueError This exception will be
1518  * thrown if the scheme code in the extension file passed to
1519  * Extension::exec() or Extension::exec_shared() does not evaluate to
1520  * the type expected by the translator.
1521  * @note No native guile exception will arise in this function and so
1522  * cause guile to jump out of it if no guile out-of-memory condition
1523  * occurs (given that this function is called after a guile extension
1524  * task has completed, such a condition is very improbable). If such
1525  * an exception were to arise, the implementation would handle it and
1526  * a C++ exception would be generated in its place in
1527  * Extension::exec() or Extension::exec_shared().
1528  *
1529  * Since 2.0.22
1530  */
1531 inline std::string string_to_string(SCM scm) {
1533  if (scm_is_false(scm_string_p(scm)))
1534  throw ReturnValueError("scheme code did not evaluate to a string\n");
1535  size_t len;
1536  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1537  // succeeds then nothing after it in this function can cause a guile
1538  // exception.
1539  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1540  return std::string(s.get(), len);
1541 }
1542 
1543 /**
1544  * A translator function which can be passed to the third argument of
1545  * Extension::exec() or Extension::exec_shared(). It disregards the
1546  * scheme value passed to it except to trap any guile exception thrown
1547  * by the scheme task and rethrow it as a C++ exception, and returns a
1548  * NULL void* object. It is thread safe, but see the comments above
1549  * about the thread safety of Extension::exec() and
1550  * Extension::exec_shared().
1551  *
1552  * It is mainly intended for use where the scheme script is executed
1553  * for its side effects, perhaps for I/O, and any communication
1554  * necessary is done by guile exceptions.
1555  *
1556  * @param scm An opaque guile SCM object representing the value to
1557  * which the extension file passed to Extension::exec() or
1558  * Extension::exec_shared() evaluated, which is ignored.
1559  * @return A NULL void* object.
1560  * @exception std::bad_alloc This function might throw std::bad_alloc
1561  * if memory is exhausted and the system throws in that case.
1562  * @exception Cgu::Extension::GuileException This exception will be
1563  * thrown if the scheme code in the extension file passed to
1564  * Extension::exec() or Extension::exec_shared() caused a guile
1565  * exception to be thrown. Cgu::Extension::GuileException::what()
1566  * will give particulars of the guile exception thrown, in UTF-8
1567  * encoding.
1568  * @note No native guile exception will arise in this function and so
1569  * cause guile to jump out of it if no guile out-of-memory condition
1570  * occurs (given that this function is called after a guile extension
1571  * task has completed, such a condition is very improbable). If such
1572  * an exception were to arise, the implementation would handle it and
1573  * a C++ exception would be generated in its place in
1574  * Extension::exec() or Extension::exec_shared().
1575  *
1576  * Since 2.0.22
1577  */
1578 inline void* any_to_void(SCM scm) {
1580  return 0;
1581 }
1582 
1583 /**
1584  * This function executes scheme code on the guile VM within a C++
1585  * program using this library. See the introductory remarks above for
1586  * its potential uses, about the thread safety of this function, and
1587  * about the use of the TaskManager::exec_shared() as an alternative.
1588  *
1589  * The first argument to this function is a preamble, which can be
1590  * used to pass top level definitions to the scheme code (in other
1591  * words, for argument passing). It's second argument is the filename
1592  * (with path) of the file containing the scheme code to be executed.
1593  * It's third argument is a translator, which will convert the value
1594  * to which the scheme code evaluates (in C++ terms, its return value)
1595  * to a suitable C++ representation. Preformed translators are
1596  * provided by this library to translate from scheme's integers, real
1597  * numbers and strings to C++ longs, doubles and strings respectively,
1598  * and from any uniform lists of these to C++ vectors of the
1599  * corresponding type. There is also a translator for void return
1600  * types. See the introductory remarks above for more information
1601  * about translators.
1602  *
1603  * Any native guile exceptions thrown by the code executed by this
1604  * function (and by any code which it calls) are converted and
1605  * rethrown as C++ exceptions.
1606  *
1607  * The scheme file can call other scheme code, and load modules, in
1608  * the ordinary way. Thus, this function can execute any scheme code
1609  * which guile can execute as a program, and the programmer can (if
1610  * wanted) act on its return value in the C++ code which invokes it.
1611  *
1612  * Thread cancellation is blocked for the thread in which this
1613  * function executes until this function returns.
1614  *
1615  * @param preamble Scheme code such as top level definitions to be
1616  * seen by the code in the file to be executed. This is mainly
1617  * intended for argument passing, but can comprise any valid scheme
1618  * code. It can also be empty (you can pass ""). Any string literals
1619  * must be in UTF-8 encoding.
1620  * @param file The file which is to be executed on the guile VM. This
1621  * should include the full pathname or a pathname relative to the
1622  * current directory. The contents of the file, and in particular any
1623  * string literals in it, must be in UTF-8 encoding. The filename and
1624  * path must also be given in UTF-8 encoding, even if the local
1625  * filename encoding is something different: guile will convert the
1626  * UTF-8 name which it is given to its own internal string encoding
1627  * using unicode code points, and then convert that to locale encoding
1628  * on looking up the filename. However sticking to ASCII for
1629  * filenames and paths (which is always valid UTF-8) will maximise
1630  * portability. The file name can be empty (you can pass ""), in
1631  * which case only the preamble will be evaluated (but for efficiency
1632  * reasons any complex code not at the top level should be included in
1633  * the file rather than in the preamble).
1634  * @param translator The function or callable object which will
1635  * convert the value to which the scheme code evaluates to a C++
1636  * representation which will be returned by this function. The
1637  * translator should take a single argument comprising an opaque guile
1638  * object of type SCM, and return the C++ representation for it.
1639  * @return The C++ representation returned by the translator.
1640  * @exception std::bad_alloc This function might throw std::bad_alloc
1641  * if memory is exhausted and the system throws in that case.
1642  * @exception Cgu::Extension::GuileException This exception will be
1643  * thrown if the scheme code in 'file' (or called by it) throws a
1644  * guile exception. Cgu::Extension::GuileException::what() will give
1645  * particulars of the guile exception thrown, in UTF-8 encoding.
1646  * @exception Cgu::Extension::ReturnValueError This exception will be
1647  * thrown if the code in 'file' does not evaluate to the type expected
1648  * by the translator.
1649  * @exception Cgu::Extension::WrapperError This exception will be
1650  * thrown if a custom translator throws a native guile exception or a
1651  * C++ exception not comprising Extension::GuileException or
1652  * Extension::ReturnValueError, one of the preformed translators
1653  * throws std::bad_alloc or encounters a guile out-of-memory
1654  * exception, one of the preformed list translators encounters an
1655  * input list exceeding SIZE_MAX in length, assigning to an internal
1656  * exception description string throws std::bad_alloc, or evaluation
1657  * of the preamble throws a native guile exception.
1658  *
1659  * Since 2.0.22
1660  */
1661 // we cannot take 'translator' by collapsible reference, because with
1662 // gcc-4.4 std::result_of fails if Translator deduces to a reference
1663 // type, and gcc-4.4 does not have std::declval. This is fixed in the
1664 // 2.2 series of this library, which has a minimum requirement of
1665 // gcc-4.6.
1666 template <class Translator>
1667 auto exec(const std::string& preamble,
1668  const std::string& file,
1669  Translator translator) -> typename std::result_of<Translator(SCM)>::type {
1670  // exec_impl() will fail to compile if Ret is a reference type: that
1671  // is a feature, not a bug, as there is no good reason for a
1672  // translator ever to return a reference
1673  typedef typename std::result_of<Translator(SCM)>::type Ret;
1674  return exec_impl<Ret>(preamble, file, translator, false);
1675 }
1676 
1677 /**
1678  * This function executes scheme code on the guile VM within a C++
1679  * program using this library. See the introductory remarks above for
1680  * its potential uses, about the thread safety of this function, and
1681  * about the use of the TaskManager::exec() as an alternative.
1682  *
1683  * The first argument to this function is a preamble, which can be
1684  * used to pass top level definitions to the scheme code (in other
1685  * words, for argument passing). It's second argument is the filename
1686  * (with path) of the file containing the scheme code to be executed.
1687  * It's third argument is a translator, which will convert the value
1688  * to which the scheme code evaluates (in C++ terms, its return value)
1689  * to a suitable C++ representation. Preformed translators are
1690  * provided by this library to translate from scheme's integers, real
1691  * numbers and strings to C++ longs, doubles and strings respectively,
1692  * and from any uniform lists of these to C++ vectors of the
1693  * corresponding type. There is also a translator for void return
1694  * types. See the introductory remarks above for more information
1695  * about translators.
1696  *
1697  * Any native guile exceptions thrown by the code executed by this
1698  * function (and by any code which it calls) are converted and
1699  * rethrown as C++ exceptions.
1700  *
1701  * The scheme file can call other scheme code, and load modules, in
1702  * the ordinary way. Thus, this function can execute any scheme code
1703  * which guile can execute as a program, and the programmer can (if
1704  * wanted) act on its return value in the C++ code which invokes it.
1705  *
1706  * Thread cancellation is blocked for the thread in which this
1707  * function executes until this function returns.
1708  *
1709  * @param preamble Scheme code such as top level definitions to be
1710  * seen by the code in the file to be executed. This is mainly
1711  * intended for argument passing, but can comprise any valid scheme
1712  * code. It can also be empty (you can pass ""). Any string literals
1713  * must be in UTF-8 encoding.
1714  * @param file The file which is to be executed on the guile VM. This
1715  * should include the full pathname or a pathname relative to the
1716  * current directory. The contents of the file, and in particular any
1717  * string literals in it, must be in UTF-8 encoding. The filename and
1718  * path must also be given in UTF-8 encoding, even if the local
1719  * filename encoding is something different: guile will convert the
1720  * UTF-8 name which it is given to its own internal string encoding
1721  * using unicode code points, and then convert that to locale encoding
1722  * on looking up the filename. However sticking to ASCII for
1723  * filenames and paths (which is always valid UTF-8) will maximise
1724  * portability. The file name can be empty (you can pass ""), in
1725  * which case only the preamble will be evaluated.
1726  * @param translator The function or callable object which will
1727  * convert the value to which the scheme code evaluates to a C++
1728  * representation which will be returned by this function. The
1729  * translator should take a single argument comprising an opaque guile
1730  * object of type SCM, and return the C++ representation for it.
1731  * @return The C++ representation returned by the translator.
1732  * @exception std::bad_alloc This function might throw std::bad_alloc
1733  * if memory is exhausted and the system throws in that case.
1734  * @exception Cgu::Extension::GuileException This exception will be
1735  * thrown if the scheme code in 'file' (or called by it) throws a
1736  * guile exception. Cgu::Extension::GuileException::what() will give
1737  * particulars of the guile exception thrown, in UTF-8 encoding.
1738  * @exception Cgu::Extension::ReturnValueError This exception will be
1739  * thrown if the code in 'file' does not evaluate to the type expected
1740  * by the translator.
1741  * @exception Cgu::Extension::WrapperError This exception will be
1742  * thrown if a custom translator throws a native guile exception or a
1743  * C++ exception not comprising Extension::GuileException or
1744  * Extension::ReturnValueError, one of the preformed translators
1745  * throws std::bad_alloc or encounters a guile out-of-memory
1746  * exception, one of the preformed list translators encounters an
1747  * input list exceeding SIZE_MAX in length, assigning to an internal
1748  * exception description string throws std::bad_alloc, or evaluation
1749  * of the preamble throws a native guile exception.
1750  *
1751  * Since 2.0.24
1752  */
1753 // we cannot take 'translator' by collapsible reference, because with
1754 // gcc-4.4 std::result_of fails if Translator deduces to a reference
1755 // type, and gcc-4.4 does not have std::declval. This is fixed in the
1756 // 2.2 series of this library, which has a minimum requirement of
1757 // gcc-4.6.
1758 template <class Translator>
1759 auto exec_shared(const std::string& preamble,
1760  const std::string& file,
1761  Translator translator) -> typename std::result_of<Translator(SCM)>::type {
1762  // exec_impl() will fail to compile if Ret is a reference type: that
1763  // is a feature, not a bug, as there is no good reason for a
1764  // translator ever to return a reference
1765  typedef typename std::result_of<Translator(SCM)>::type Ret;
1766  return exec_impl<Ret>(preamble, file, translator, true);
1767 }
1768 
1769 } // namespace Extension
1770 
1771 } // namespace Cgu
1772 
1773 #endif // CGU_EXTENSION_H
std::vector< long > list_to_vector_long(SCM scm)
Definition: extension.h:971
GuileException(const char *msg)
Definition: extension.h:552
long integer_to_long(SCM scm)
Definition: extension.h:1435
~ReturnValueError()
Definition: extension.h:567
~GuileException()
Definition: extension.h:555
const char * err_text() const
Definition: extension.h:563
void * any_to_void(SCM scm)
Definition: extension.h:1578
auto exec(const std::string &preamble, const std::string &file, Translator translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1667
WrapperError(const char *msg)
Definition: extension.h:574
This file provides classes for type erasure.
Definition: extension.h:558
A class enabling the cancellation state of a thread to be controlled.
Definition: thread.h:681
double real_to_double(SCM scm)
Definition: extension.h:1485
Definition: extension.h:546
std::string string_to_string(SCM scm)
Definition: extension.h:1531
std::vector< double > list_to_vector_double(SCM scm)
Definition: extension.h:1129
auto exec_shared(const std::string &preamble, const std::string &file, Translator translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1759
virtual const char * what() const
Definition: extension.h:573
T get() const
Definition: shared_handle.h:762
A wrapper class for pthread mutexes.
Definition: mutex.h:117
Provides wrapper classes for pthread mutexes and condition variables, and scoped locking classes for ...
Definition: application.h:44
SCM exception_to_string(SCM key, SCM args)
Definition: extension.h:803
std::vector< std::string > list_to_vector_string(SCM scm)
Definition: extension.h:1287
Definition: extension.h:570
virtual const char * what() const
Definition: extension.h:562
~WrapperError()
Definition: extension.h:576
virtual const char * what() const
Definition: extension.h:550
void rethrow_guile_exception(SCM scm)
Definition: extension.h:889
ReturnValueError(const char *msg)
Definition: extension.h:564
The callback interface class.
Definition: callback.h:522
const char * guile_text() const
Definition: extension.h:551