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 >=
79  * 2.0.2, guile-2.2 >= 2.1.3 or guile-3.0 >= 2.9.1 is 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  * If a C++ program is to run guile tasks on a TaskManager object
323  * having a maximum thread count greater than one (or in more than one
324  * thread in some other way), one other point should be noted. When a
325  * scheme file is executed for the first time by a user by being
326  * passed as the second argument of Extension::exec() (or by having
327  * 'load' applied to it in some other way), it will be compiled into
328  * byte code, the byte code will then be cached on the file system for
329  * that and subsequent calls, and the byte code then executed. Bad
330  * things might happen if concurrent calls to Extension::exec(), or to
331  * the 'load' or 'use-modules' procedures, are made in respect of the
332  * same scheme file for the "first" time, if there might be a race as
333  * to which of them is the "first" call in respect of the file: that
334  * is, if it causes two or more threads to try to compile the same
335  * file into byte code concurrently. This is only an issue the first
336  * time a particular user executes a scheme file, and can be avoided
337  * (amongst other ways) by having the C++ program concerned
338  * pre-compile the relevant scheme file before Extension::exec() or
339  * Extension::exec_shared() is first called, by means of the 'guild
340  * compile [filename]' command. The following gives more information
341  * about compilation: <A
342  * HREF="http://www.gnu.org/software/guile/manual/html_node/Compilation.html#Compilation">
343  * Compiling Scheme Code</A>
344  *
345  * Licence
346  * -------
347  *
348  * The c++-gtk-utils library (and this c++-gtk-utils/extension.h
349  * header file) follows glib and GTK+ by being released under the LGPL
350  * version 2.1 or later. libguile is released under the LGPL version
351  * 3 or later. The c++-gtk-utils library object code does not link to
352  * libguile, nor does it incorporate anything in the
353  * c++-gtk-utils/extension.h header. Instead
354  * c++-gtk-utils/extension.h contains all its code as a separate
355  * unlinked header for any program which wants to include it (this is
356  * partly because some of it comprises template functions).
357  *
358  * There are two consequences. If you want to use Extension::exec()
359  * or Extension::exec_shared(), the program which calls it will need
360  * to link itself explicitly with libguile as well as c++-gtk-utils,
361  * and to do that will need to use pkg-config to obtain libguile's
362  * cflags and libs particulars (its pkg-config file is guile-2.0.pc,
363  * guile-2.2.pc or guile-3.0.pc). This library does NOT do that for
364  * you. Secondly, by linking with libguile you will be governed by
365  * the LGPL version 3 or later, instead of the LGPL version 2.1 or
366  * later, with respect to that linking. That's fine (there is nothing
367  * wrong with the LGPL version 3 and this library permits that) but
368  * you should be aware of it. The scheme code in guile's scheme level
369  * modules is also in the main released under the LGPL version 3 or
370  * later ("in the main" because readline.scm, comprised in the
371  * readline module, is released under the GPL version 3 or later).
372  *
373  * Configuration
374  * -------------
375  *
376  * By default, when the c++-gtk-utils library is configured,
377  * configuration will first look for guile-3.0 >= 2.9.1, then if it
378  * does not find that it will look for guile-2.2 >= 2.1.3, then if it
379  * does not find that it will look for guile-2.0 >= 2.0.2, and then if
380  * it finds none it will disable guile support; and the library header
381  * files will then be set up appropriately. guile-3.0, guile-2.2 or
382  * guile-2.0 can be specifically picked with the \--with-guile=3.0,
383  * \--with-guile=2.2 or \--with-guile=2.0 configuration options
384  * respectively. Guile support can be omitted with the
385  * \--with-guile=no option.
386 
387  * However, as mentioned under "Licence" above, any program using
388  * Extension::exec() or Extension::exec_shared() must link itself
389  * explicitly with libguile via either guile-2.0.pc (for guile-2.0),
390  * guile-2.2.pc (for guile-2.2) or guile-3.0.pc (for guile-3.0).
391  * Programs should use whichever of those is the one for which
392  * c++-gtk-utils was configured. If you get link-time messages from a
393  * program about being unable to link to scm_dynwind_block_asyncs(),
394  * then there has been a version mismatch. If you get link-time
395  * messages about being unable to link to Cgu::Extension::init_mutex()
396  * or Cgu::Extension::get_user_module_mutex() then c++-gtk-utils has
397  * not been configured to offer guile support.
398  *
399  * Custom translators
400  * ------------------
401  *
402  * Any function or callable object which translates from an opaque SCM
403  * value to a suitable C++ representation can be passed as the third
404  * argument of Extension::exec() or Extension::exec_shared(). C++
405  * type deduction on template resolution will take care of everything
406  * else. The translator can execute any functions offered by
407  * libguile, because when the translator is run the program is still
408  * in guile mode. The fulsome guile documentation sets out the
409  * libguile functions which are callable in C/C++ code.
410  *
411  * The first call in a custom translator should normally be to the
412  * Extension::rethrow_guile_exception() function. This function tests
413  * whether a guile exception arose in executing the scheme file, and
414  * throws a C++ exception if it did. The preformed translators in
415  * extension.h provide worked examples of how a custom translator
416  * might be written.
417  *
418  * If something done in a custom translator were to raise a guile
419  * exception, the library implementation would handle it and a C++
420  * exception would be generated in its place in Extension::exec() or
421  * Extension::exec_shared(). However, a custom translator should not
422  * allow a guile exception arising from calls to libguile made by it
423  * to exit a C++ scope in which the translator has constructed a local
424  * C++ object which is not trivially destructible: that would give
425  * rise to undefined behaviour, with the likely result that the C++
426  * object's destructor would not be called. One approach to this
427  * (adopted in the preformed translators) is to allocate on free store
428  * all local C++ objects to be constructed in the translator which are
429  * not trivially destructible, and to manage their lifetimes manually
430  * using local C++ try/catch blocks rather than RAII, with dynwind
431  * unwind handlers to release memory were there to be a guile
432  * exception (but note that no C++ exception should transit out of a
433  * scm_dynwind_begin()/scm_dynwind_end() pair). It is also a good
434  * idea to test for any condition which might cause a guile exception
435  * to be raised in the translator in the first place, and throw a C++
436  * exception beforehand. Then the only condition which might cause a
437  * guile exception to occur in the translator is an out-of-memory
438  * condition, which is highly improbable in a translator as the
439  * translator is run after the guile task has completed. Heap
440  * exhaustion in such a case probably spells doom for the program
441  * concerned anyway, if it has other work to do.
442  *
443  * Note also that code in a custom translator should not store guile
444  * SCM objects (which are pointers to guile scheme objects) in memory
445  * blocks allocated by malloc() or the new expression, or they will
446  * not be seen by the garbage collector used by libguile (which is the
447  * gc library) and therefore may be prematurely deallocated. To keep
448  * such items alive in custom translators, SCM variables should be
449  * kept as local variables or parameter names in functions (and so
450  * stored on the stack or in registers, where they will be seen by the
451  * garbage collector), or in memory allocated with scm_gc_malloc(),
452  * where they will also be seen by the garbage collector.
453  *
454  * Scheme
455  * ------
456  * If you want to learn more about scheme, these are useful sources:
457  * <P>
458  * <A HREF="http://www.gnu.org/software/guile/manual/html_node/Hello-Scheme_0021.html"> Chapter 3 of the Guile Manual</A>
459  * (the rest of the manual is also good reading).</P>
460  * <P>
461  * <A HREF="http://www.scheme.com/tspl4/">The Scheme Programming Language, 4th edition</A></P>
462  */
463 
464 #include <string>
465 #include <vector>
466 #include <exception>
467 #include <memory> // for std::unique_ptr
468 #include <type_traits> // for std::remove_reference, std::remove_const and std::result_of
469 #include <limits> // for std::numeric_limits
470 #include <functional> // for std::bind
471 #include <utility> // for std::move
472 #include <new> // for std::bad_alloc
473 
474 #include <stddef.h> // for size_t
475 #include <stdlib.h> // for free()
476 #include <string.h> // for strlen() and strncmp()
477 
478 #include <glib.h>
479 
481 #include <c++-gtk-utils/callback.h>
482 #include <c++-gtk-utils/thread.h>
483 #include <c++-gtk-utils/mutex.h>
485 
486 #include <libguile.h>
487 
488 
489 #ifndef DOXYGEN_PARSING
490 namespace Cgu {
491 
492 namespace Extension {
493 
494 struct FormatArgs {
495  SCM text;
496  SCM rest;
497 };
498 
499 enum VectorDeleteType {Long, Double, String};
500 
501 struct VectorDeleteArgs {
502  VectorDeleteType type;
503  void* vec;
504 };
505 
506 // defined in extension_helper.cpp
507 extern Cgu::Thread::Mutex* get_user_module_mutex();
508 extern bool init_mutex();
509 
510 } // namespace Extension
511 
512 } // namespace Cgu
513 
514 namespace {
515 extern "C" {
516  inline SCM cgu_format_try_handler(void* data) {
517  using Cgu::Extension::FormatArgs;
518  FormatArgs* format_args = static_cast<FormatArgs*>(data);
519  return scm_simple_format(SCM_BOOL_F, format_args->text, format_args->rest);
520  }
521  inline SCM cgu_format_catch_handler(void*, SCM, SCM) {
522  return SCM_BOOL_F;
523  }
524  inline void* cgu_guile_wrapper(void* data) {
525  try {
526  static_cast<Cgu::Callback::Callback*>(data)->dispatch();
527  }
528  // an elipsis catch block is fine as thread cancellation is
529  // blocked. We can only enter this block if assigning to one of
530  // the exception strings in the callback has thrown
531  // std::bad_alloc. For that case we return a non-NULL pointer to
532  // indicate error (the 'data' argument is convenient and
533  // guaranteed to be standard-conforming for this).
534  catch (...) {
535  return data;
536  }
537  return 0;
538  }
539  inline void cgu_delete_vector(void* data) {
540  using Cgu::Extension::VectorDeleteArgs;
541  VectorDeleteArgs* args = static_cast<VectorDeleteArgs*>(data);
542  switch (args->type) {
543  case Cgu::Extension::Long:
544  delete static_cast<std::vector<long>*>(args->vec);
545  break;
546  case Cgu::Extension::Double:
547  delete static_cast<std::vector<double>*>(args->vec);
548  break;
549  case Cgu::Extension::String:
550  delete static_cast<std::vector<std::string>*>(args->vec);
551  break;
552  default:
553  g_critical("Incorrect argument passed to cgu_delete_vector");
554  }
555  delete args;
556  }
557  inline void cgu_unlock_module_mutex(void*) {
558  // this cannot give rise to an allocation or mutex error -
559  // we must have been called init_mutex() first
560  Cgu::Extension::get_user_module_mutex()->unlock();
561  }
562 } // extern "C"
563 } // unnamed namespace
564 #endif // DOXYGEN_PARSING
565 
566 namespace Cgu {
567 
568 namespace Extension {
569 
570 class GuileException: public std::exception {
571  Cgu::GcharSharedHandle message;
572  Cgu::GcharSharedHandle guile_message;
573 public:
574  virtual const char* what() const throw() {return (const char*)message.get();}
575  const char* guile_text() const throw() {return (const char*)guile_message.get();}
576  GuileException(const char* msg):
577  message(g_strdup_printf("Cgu::Extension::GuileException: %s", msg)),
578  guile_message(g_strdup(msg)) {}
579  ~GuileException() throw() {}
580 };
581 
582 class ReturnValueError: public std::exception {
583  Cgu::GcharSharedHandle message;
584  Cgu::GcharSharedHandle err_message;
585 public:
586  virtual const char* what() const throw() {return (const char*)message.get();}
587  const char* err_text() const throw() {return (const char*)err_message.get();}
588  ReturnValueError(const char* msg):
589  message(g_strdup_printf("Cgu::Extension::ReturnValueError: %s", msg)),
590  err_message(g_strdup(msg)) {}
591  ~ReturnValueError() throw() {}
592 };
593 
594 class WrapperError: public std::exception {
595  Cgu::GcharSharedHandle message;
596 public:
597  virtual const char* what() const throw() {return (const char*)message.get();}
598  WrapperError(const char* msg):
599  message(g_strdup_printf("Cgu::Extension::WrapperError: %s", msg)) {}
600  ~WrapperError() throw() {}
601 };
602 
603 #ifndef DOXYGEN_PARSING
604 
605 // this function has been renamed guile_wrapper_cb2 in version 2.0.28
606 // in order to prevent ODR issues and ensure exec_impl() in 2.0.28
607 // calls the correct version of this function
608 template <class Ret, class TransType>
609 void guile_wrapper_cb2(TransType* translator,
610  std::string* loader,
611  Ret* retval,
612  bool* result,
613  std::string* guile_except,
614  std::string* guile_ret_val_err,
615  std::string* gen_err,
616  bool shared) {
617  SCM scm;
618  if (shared) {
619  scm = scm_eval_string_in_module(scm_from_utf8_string(loader->c_str()),
620  scm_c_resolve_module("guile-user"));
621  }
622  else {
623  if (!init_mutex())
624  throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
625 
626  scm_dynwind_begin(scm_t_dynwind_flags(0));
627  scm_dynwind_unwind_handler(&cgu_unlock_module_mutex, 0, SCM_F_WIND_EXPLICITLY);
628  get_user_module_mutex()->lock(); // won't throw
629  SCM new_mod = scm_call_0(scm_c_public_ref("guile", "make-fresh-user-module"));
630  scm_dynwind_end();
631 
632  scm = scm_eval_string_in_module(scm_from_utf8_string(loader->c_str()),
633  new_mod);
634  }
635 
636  // have a dynwind context and async block while translator is
637  // executing. This is to cater for the pathological case of the
638  // scheme script having set up a signal handler which might throw a
639  // guile exception, or having chained a series of system asyncs
640  // which are still queued for action, which might otherwise cause
641  // the translator to trigger a guile exception while a non-trivially
642  // destructible object is in the local scope of translator. (Highly
643  // unlikely, but easy to deal with.) This is entirely safe as no
644  // C++ exception arising from the translator can transit across the
645  // dynamic context in this function - see below. So we have (i) no
646  // C++ exception can transit across a guile dynamic context, and
647  // (ii) no guile exception can escape out of a local C++ scope by
648  // virtue of an async executing (it might still escape with a
649  // non-trivially destructible object in existence if a custom
650  // translator has not been written correctly, but there is nothing
651  // we can do about that). Note that some guile installations do not
652  // link scm_dynwind_block_asyncs() correctly - this is tested at
653  // configuration time.
654 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
655  scm_dynwind_begin(scm_t_dynwind_flags(0));
656  scm_dynwind_block_asyncs();
657 #endif
658  // we cannot use std::exception_ptr here to store a C++ exception
659  // object, because std::exception_ptr is not trivially destructible
660  // and a guile exception in 'translator' could jump out of this
661  // scope to its continuation in scm_with_guile()
662  bool badalloc = false;
663  try {
664  *retval = (*translator)(scm);
665  *result = true; // this will detect any guile exception in the
666  // preamble or 'translator' which causes
667  // scm_with_guile() to return prematurely. We
668  // have could have done it instead by reversing
669  // the return values of cgu_guile_wrapper
670  // (non-NULL for success and NULL for failure)
671  // because scm_with_guile() returns NULL if it
672  // exits on an uncaught guile exception, but this
673  // approach enables us to discriminate between a
674  // C++ memory exception in the wrapper and a guile
675  // exception in the preamble or 'translator', at a
676  // minimal cost of one assignment to a bool.
677  }
678  catch (Cgu::Extension::GuileException& e) {
679  try {
680  *guile_except = e.guile_text();
681  }
682  catch (...) {
683  badalloc = true;
684  }
685  }
687  try {
688  *guile_ret_val_err = e.err_text();
689  }
690  catch (...) {
691  badalloc = true;
692  }
693  }
694  catch (std::exception& e) {
695  try {
696  *gen_err = e.what();
697  }
698  catch (...) {
699  badalloc = true;
700  }
701  }
702  catch (...) {
703  try {
704  *gen_err = "C++ exception thrown in guile_wrapper_cb()";
705  }
706  catch (...) {
707  badalloc = true;
708  }
709  }
710 #ifndef CGU_GUILE_HAS_BROKEN_LINKING
711  scm_dynwind_end();
712 #endif
713  if (badalloc) throw std::bad_alloc(); // this will be caught in cgu_guile_wrapper()
714 }
715 
716 template <class Ret, class Translator>
717 Ret exec_impl(const std::string& preamble,
718  const std::string& file,
719  Translator translator,
720  bool shared) {
721 
723 
724  std::string loader;
725  loader += preamble;
726  if (!file.empty()) {
727  if (shared)
728  loader += "((lambda ()";
729  loader += "(catch "
730  "#t"
731  "(lambda ()"
732  "(";
733  if (shared)
734  loader += "primitive-load \"";
735  else
736  loader += "load \"";
737  loader += file;
738  loader += "\"))"
739  "(lambda (key . details)"
740  "(cons \"***cgu-guile-exception***\" (cons key details))))";
741  if (shared)
742  loader += "))";
743  }
744 
745  Ret retval;
746  bool result = false;
747  std::string guile_except;
748  std::string guile_ret_val_err;
749  std::string gen_err;
750 
751  // we construct a Callback::Callback object here to perform type
752  // erasure. Otherwise we would have to pass scm_with_guile() a
753  // function pointer to a function templated on Translator and Ret,
754  // which must have C++ language linkage (§14/4 of C++ standard).
755  // Technically this would give undefined behaviour as
756  // scm_with_guile() expects a function pointer with C language
757  // linkage, although gcc and clang would accept it. The whole of
758  // this callback will be executed in guile mode via
759  // cgu_guile_wrapper(), so it can safely call libguile functions
760  // (provided that a translator does not allow any guile exceptions
761  // to escape a C++ scope with local objects which are not trivially
762  // destructible). It is also safe to pass 'translator', 'retval',
763  // 'loader', 'result' and the exception strings to it by reference,
764  // because scm_with_guile() will block until it has completed
765  // executing. cgu_guile_wrapper() will trap any std::bad_alloc
766  // exception thrown by the string assignments in the catch blocks in
767  // guile_wrapper_cb. guile_wrapper_cb is safe against a jump to an
768  // exit from scm_with_guile() arising from a native guile exception
769  // in translator, because its body has no objects in local scope
770  // requiring destruction.
771  std::unique_ptr<Cgu::Callback::Callback> cb(
772  Cgu::Callback::lambda<>(std::bind(&guile_wrapper_cb2<Ret, Translator>,
773  &translator,
774  &loader,
775  &retval,
776  &result,
777  &guile_except,
778  &guile_ret_val_err,
779  &gen_err,
780  shared))
781  );
782  // cgu_guile_wrapper(), and so scm_with_guile() will return a
783  // non-NULL value if assigning to one of the exception description
784  // strings above threw std::bad_alloc
785  if (scm_with_guile(&cgu_guile_wrapper, cb.get()))
786  throw WrapperError("cgu_guile_wrapper() has trapped std::bad_alloc");
787  if (!guile_except.empty())
788  throw GuileException(guile_except.c_str());
789  if (!guile_ret_val_err.empty())
790  throw ReturnValueError(guile_ret_val_err.c_str());
791  if (!gen_err.empty())
792  throw WrapperError(gen_err.c_str());
793  if (!result)
794  throw WrapperError("the preamble or translator threw a native guile exception");
795  return retval;
796 }
797 
798 #endif // DOXYGEN_PARSING
799 
800 /**
801  * This function is called by Extension::rethrow_guile_exception()
802  * where the scheme code executed by Extension::exec() or
803  * Extension::exec_shared() has exited with a guile exception. It
804  * converts the raw guile exception information represented by the
805  * 'key' and 'args' arguments of a guile catch handler to a more
806  * readable form. It is made available as part of the public
807  * interface so that any custom translators can also use it if they
808  * choose to provide their own catch expressions. This function does
809  * not throw any C++ exceptions. No native guile exception will arise
810  * in this function and so cause guile to jump out of it assuming no
811  * guile out-of-memory condition occurs (and given that this function
812  * is called after a guile extension task has completed, such a
813  * condition is very improbable). It is thread safe, but see the
814  * comments above about the thread safety of Extension::exec() and
815  * Extension::exec_shared().
816  *
817  * @param key An opaque guile SCM object representing a symbol
818  * comprising the 'key' argument of the exception handler of a guile
819  * catch expression.
820  * @param args An opaque guile SCM object representing a list
821  * comprising the 'args' argument of the exception handler of a guile
822  * catch expression.
823  * @return An opaque guile SCM object representing a guile string.
824  *
825  * Since 2.0.22
826  */
827 inline SCM exception_to_string(SCM key, SCM args) {
828  // The args of most exceptions thrown by guile are in the following format:
829  // (car args) - a string comprising the name of the procedure generating the exception
830  // (cadr args) - a string containing text, possibly with format directives (escape sequences)
831  // (caddr args) - a list containing items matching the format directives, or #f if none
832  // (cadddr args) - (not used here) a list of additional objects (eg the errno for some errors),
833  // or #f if none
834  SCM ret = SCM_BOOL_F;
835  int length = scm_to_int(scm_length(args));
836  if (length) {
837  SCM first = scm_car(args);
838  if (scm_is_true(scm_string_p(first))) {
839  // if a single user string, output it
840  if (length == 1) {
841  ret = scm_string_append(scm_list_4(scm_from_utf8_string("Exception "),
842  scm_symbol_to_string(key),
843  scm_from_utf8_string(": "),
844  first));
845  }
846  else { // length > 1
847  SCM second = scm_cadr(args);
848  if (scm_is_true(scm_string_p(second))) {
849  // we should have a standard guile exception string, as above
850  SCM text = scm_string_append(scm_list_n(scm_from_utf8_string("Exception "),
851  scm_symbol_to_string(key),
852  scm_from_utf8_string(" in procedure "),
853  first,
854  scm_from_utf8_string(": "),
855  second,
856  SCM_UNDEFINED));
857  if (length == 2)
858  ret = text;
859  else { // length > 2
860  SCM third = scm_caddr(args);
861  if (scm_is_false(third))
862  ret = text;
863  else if (scm_is_true(scm_list_p(third))) {
864  FormatArgs format_args = {text, third};
865  ret = scm_internal_catch(SCM_BOOL_T,
866  &cgu_format_try_handler,
867  &format_args,
868  &cgu_format_catch_handler,
869  0);
870  }
871  }
872  }
873  }
874  }
875  }
876  // fall back to generic formatting if first or second elements of
877  // args is not a string or simple-format failed above
878  if (scm_is_false(ret)) {
879  // there is no need for a catch block: we know simple-format
880  // cannot raise an exception here
881  ret = scm_simple_format(SCM_BOOL_F,
882  scm_from_utf8_string("Exception ~S: ~S"),
883  scm_list_2(key, args));
884  }
885  return ret;
886 }
887 
888 /**
889  * This function tests whether a guile exception arose in executing a
890  * scheme extension file, and throws Cgu::Extension::GuileException if
891  * it did. It is intended for use by custom translators, as the first
892  * thing the translator does. It is thread safe, but see the comments
893  * above about the thread safety of Extension::exec() and
894  * Extension::exec_shared().
895  *
896  * @param scm An opaque guile SCM object representing the value to
897  * which the extension file passed to Extension::exec() or
898  * Extension::exec_shared() evaluated.
899  * @exception std::bad_alloc This function might throw std::bad_alloc
900  * if memory is exhausted and the system throws in that case.
901  * @exception Cgu::Extension::GuileException This exception will be
902  * thrown if the scheme code executed in the extension file passed to
903  * Extension::exec() or Extension::exec_shared() threw a guile
904  * exception. Cgu::Extension::GuileException::what() will give
905  * particulars of the guile exception thrown, in UTF-8 encoding.
906  * @note No native guile exception will arise in this function and so
907  * cause guile to jump out of it if no guile out-of-memory condition
908  * occurs (given that this function is called after a guile extension
909  * task has completed, such a condition is very improbable).
910  *
911  * Since 2.0.22
912  */
913 inline void rethrow_guile_exception(SCM scm) {
914  // guile exceptions are always presented to this function as a
915  // scheme list
916  if (scm_is_false(scm_list_p(scm))
917  || scm_is_true(scm_null_p(scm))) return;
918  SCM first = scm_car(scm);
919  if (scm_is_true(scm_string_p(first))) {
920  size_t len;
921  const char* text = 0;
922  // nothing in this function should throw a guile exception unless
923  // there is a guile out-of-memory exception (which is extremely
924  // improbable). However, let's cover ourselves in case
925  scm_dynwind_begin(scm_t_dynwind_flags(0));
926  char* car = scm_to_utf8_stringn(first, &len);
927  // there may be a weakness in guile's implementation here: if
928  // calling scm_dynwind_unwind_handler() were to give rise to an
929  // out-of-memory exception before the handler is set up by it,
930  // then we could leak memory allocated from the preceding call to
931  // scm_to_utf8_stringn(). Whether that could happen is not
932  // documented, but because (a) it is so improbable, and (b) once
933  // we are in out-of-memory land we are already in severe trouble
934  // and glib is likely to terminate the program at some point
935  // anyway, it is not worth troubling ourselves over.
936  scm_dynwind_unwind_handler(&free, car, scm_t_wind_flags(0));
937  if (len == strlen("***cgu-guile-exception***")
938  && !strncmp(car, "***cgu-guile-exception***", len)) {
939  SCM str = exception_to_string(scm_cadr(scm), scm_cddr(scm));
940  // we don't need a dynwind handler for 'text' because nothing
941  // after the call to scm_to_utf8_stringn() can cause a guile
942  // exception to be raised
943  text = scm_to_utf8_stringn(str, &len);
944  }
945  // all done - no more guile exceptions are possible in this
946  // function after this so end the dynamic context, take control of
947  // the memory by RAII and if necessary throw a C++ exception
948  scm_dynwind_end();
949  std::unique_ptr<char, Cgu::CFree> up_car(car);
950  std::unique_ptr<const char, Cgu::CFree> up_text(text);
951  // if 'text' is not NULL, 'len' contains its length in bytes
952  if (text) throw GuileException(std::string(text, len).c_str());
953  }
954 }
955 
956 /**
957  * A translator function which can be passed to the third argument of
958  * Extension::exec() or Extension::exec_shared(). It converts from a
959  * homogeneous scheme list of integers to a C++ representation of
960  * std::vector<long>. It is thread safe, but see the comments above
961  * about the thread safety of Extension::exec() and
962  * Extension::exec_shared().
963  *
964  * @param scm An opaque guile SCM object representing the value to
965  * which the extension file passed to Extension::exec() or
966  * Extension::exec_shared() evaluated, where that value is a
967  * homogeneous list of integers.
968  * @return The std::vector<long> representation.
969  * @exception std::bad_alloc This function might throw std::bad_alloc
970  * if memory is exhausted and the system throws in that case, or if
971  * the length of the input list exceeds std::vector::max_size().
972  * @exception Cgu::Extension::GuileException This exception will be
973  * thrown if the scheme code in the extension file passed to
974  * Extension::exec() or Extension::exec_shared() caused a guile
975  * exception to be thrown. Cgu::Extension::GuileException::what()
976  * will give particulars of the guile exception thrown, in UTF-8
977  * encoding.
978  * @exception Cgu::Extension::ReturnValueError This exception will be
979  * thrown if the scheme code in the extension file passed to
980  * Extension::exec() or Extension::exec_shared() does not evaluate to
981  * the type expected by the translator, or it is out of range for a
982  * long.
983  * @note No native guile exception will arise in this function and so
984  * cause guile to jump out of it unless a guile out-of-memory
985  * condition occurs (given that this function is called after a guile
986  * extension task has completed, such a condition is very improbable)
987  * or the length of the input list exceeds SIZE_MAX (the maximum value
988  * of std::size_t). If such an exception were to arise, the
989  * implementation would handle it and a C++ exception would be
990  * generated in its place in Extension::exec() or
991  * Extension::exec_shared().
992  *
993  * Since 2.0.22
994  */
995 inline std::vector<long> list_to_vector_long(SCM scm) {
997  if (scm_is_false(scm_list_p(scm)))
998  throw ReturnValueError("scheme code did not evaluate to a list\n");
999 
1000  // nothing in this function should throw a guile exception unless
1001  // there is a guile out-of-memory exception (which is extremely
1002  // improbable). However, let's cover ourselves in case.
1003  scm_dynwind_begin(scm_t_dynwind_flags(0));
1004  // we cannot have a std::vector object in a scope where a guile
1005  // exception might be raised because it has a non-trivial
1006  // destructor, nor can we use RAII. Instead allocate on free store
1007  // and manage the memory by hand until we can no longer jump on a
1008  // guile exception. In addition we cannot store a C++ exception
1009  // using std::exception_ptr because std::exception_ptr is not
1010  // trivially destructible.
1011  bool badalloc = false;
1012  const char* rv_error = 0;
1013  std::vector<long>* res = 0;
1014  VectorDeleteArgs* args = 0;
1015  try {
1016  // it doesn't matter if the second allocation fails, as we clean
1017  // up at the end if there is no guile exception, and if both
1018  // allocations succeed and there were to be a subsequent guile
1019  // exception, cgu_delete_vector cleans up
1020  res = new std::vector<long>;
1021  // allocate 'args' on free store, because the continuation in
1022  // which it executes will be up the stack
1023  args = new VectorDeleteArgs{Long, res};
1024  }
1025  catch (...) {
1026  badalloc = true;
1027  }
1028  if (!badalloc) {
1029  // there may be a weakness in guile's implementation here: if
1030  // calling scm_dynwind_unwind_handler() were to give rise to a
1031  // guile out-of-memory exception before the handler is set up by
1032  // it, then we could leak memory allocated from the preceding new
1033  // expressions. Whether that could happen is not documented by
1034  // guile, but because (a) it is so improbable, and (b) once we are
1035  // in out-of-memory land we are already in severe trouble and glib
1036  // is likely to terminate the program at some point anyway, it is
1037  // not worth troubling ourselves over.
1038  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1039  // convert the list to a guile vector so we can access its items
1040  // efficiently in a for loop. This conversion is reasonably
1041  // efficient, in the sense that an ordinary guile vector is an
1042  // array of pointers, pointing to the same scheme objects that the
1043  // list refers to
1044  SCM guile_vec = scm_vector(scm);
1045 
1046  // std::vector::size_type is the same as size_t with the standard
1047  // allocators (but if we were to get a silent narrowing conversion
1048  // on calling std::vector::reserve() below, that doesn't matter -
1049  // instead if 'length' is less than SIZE_MAX but greater than the
1050  // maximum value of std::vector::size_type, at some point a call
1051  // to std::vector::push_back() below would throw and be caught,
1052  // and this function would end up rethrowing it as std::bad_alloc.
1053  // If in a particular implementation SIZE_MAX exceeds
1054  // std::vector::max_size(), a std::length_error exception would be
1055  // thrown by reserve() where max_size() is exceeded. On all
1056  // common implementations, max_size() is equal to SIZE_MAX, but
1057  // were such an exception to arise it would be swallowed (see
1058  // below) and then rethrown by this function as std::bad_alloc.
1059  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1060  // exception would be thrown by scm_to_size_t() which would be
1061  // rethrown by Cgu:Extension::exec() or
1062  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1063  // C++ exception. This is nice to know but in practice such large
1064  // lists would be unusably slow and a memory exception would be
1065  // reached long before std::vector::max_size() or SIZE_MAX are
1066  // exceeded.
1067  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1068  try {
1069  res->reserve(length);
1070  }
1071  catch (...) {
1072  badalloc = true;
1073  }
1074  for (size_t count = 0;
1075  count < length && !rv_error && !badalloc;
1076  ++count) {
1077  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1078  if (scm_is_false(scm_integer_p(item)))
1079  rv_error = "scheme code did not evaluate to a homogeneous list of integer\n";
1080  else {
1081  SCM min = scm_from_long(std::numeric_limits<long>::min());
1082  SCM max = scm_from_long(std::numeric_limits<long>::max());
1083  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1084  rv_error = "scheme code evaluated out of range for long\n";
1085  else {
1086  try {
1087  res->push_back(scm_to_long(item));
1088  }
1089  catch (...) {
1090  badalloc = true;
1091  }
1092  }
1093  }
1094  }
1095  }
1096  // all done - no more guile exceptions are possible in this function
1097  // after this so end the dynamic context, take control of the memory
1098  // by RAII and if necessary throw a C++ exception
1099  scm_dynwind_end();
1100  std::unique_ptr<std::vector<long>> up_res(res);
1101  std::unique_ptr<VectorDeleteArgs> up_args(args);
1102  if (badalloc) throw std::bad_alloc();
1103  if (rv_error) throw ReturnValueError(rv_error);
1104  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1105  // semantics here, so force it by hand
1106  return std::move(*res);
1107 }
1108 
1109 /**
1110  * A translator function which can be passed to the third argument of
1111  * Extension::exec() or Extension::exec_shared(). It converts from a
1112  * homogeneous scheme list of real numbers to a C++ representation of
1113  * std::vector<double>. It is thread safe, but see the comments above
1114  * about the thread safety of Extension::exec() and
1115  * Extension::exec_shared().
1116  *
1117  * @param scm An opaque guile SCM object representing the value to
1118  * which the extension file passed to Extension::exec() or
1119  * Extension::exec_shared() evaluated, where that value is a
1120  * homogeneous list of real numbers.
1121  * @return The std::vector<double> representation.
1122  * @exception std::bad_alloc This function might throw std::bad_alloc
1123  * if memory is exhausted and the system throws in that case, or if
1124  * the length of the input list exceeds std::vector::max_size().
1125  * @exception Cgu::Extension::GuileException This exception will be
1126  * thrown if the scheme code in the extension file passed to
1127  * Extension::exec() or Extension::exec_shared() caused a guile
1128  * exception to be thrown. Cgu::Extension::GuileException::what()
1129  * will give particulars of the guile exception thrown, in UTF-8
1130  * encoding.
1131  * @exception Cgu::Extension::ReturnValueError This exception will be
1132  * thrown if the scheme code in the extension file passed to
1133  * Extension::exec() or Extension::exec_shared() does not evaluate to
1134  * the type expected by the translator, or it is out of range for a
1135  * double.
1136  * @note 1. Prior to version 2.0.25, this translator had a bug which
1137  * caused an out-of-range Cgu::Extension::ReturnValueError to be
1138  * thrown if any of the numbers in the list to which the scheme code
1139  * in the extension file evaluated was 0.0 or a negative number. This
1140  * was fixed in version 2.0.25.
1141  * @note 2. No native guile exception will arise in this function and
1142  * so cause guile to jump out of it unless a guile out-of-memory
1143  * condition occurs (given that this function is called after a guile
1144  * extension task has completed, such a condition is very improbable)
1145  * or the length of the input list exceeds SIZE_MAX (the maximum value
1146  * of std::size_t). If such an exception were to arise, the
1147  * implementation would handle it and a C++ exception would be
1148  * generated in its place in Extension::exec() or
1149  * Extension::exec_shared().
1150  *
1151  * Since 2.0.22
1152  */
1153 inline std::vector<double> list_to_vector_double(SCM scm) {
1155  if (scm_is_false(scm_list_p(scm)))
1156  throw ReturnValueError("scheme code did not evaluate to a list\n");
1157 
1158  // nothing in this function should throw a guile exception unless
1159  // there is a guile out-of-memory exception (which is extremely
1160  // improbable). However, let's cover ourselves in case.
1161  scm_dynwind_begin(scm_t_dynwind_flags(0));
1162  // we cannot have a std::vector object in a scope where a guile
1163  // exception might be raised because it has a non-trivial
1164  // destructor, nor can we use RAII. Instead allocate on free store
1165  // and manage the memory by hand until we can no longer jump on a
1166  // guile exception. In addition we cannot store a C++ exception
1167  // using std::exception_ptr because std::exception_ptr is not
1168  // trivially destructible.
1169  bool badalloc = false;
1170  const char* rv_error = 0;
1171  std::vector<double>* res = 0;
1172  VectorDeleteArgs* args = 0;
1173  try {
1174  // it doesn't matter if the second allocation fails, as we clean
1175  // up at the end if there is no guile exception, and if both
1176  // allocations succeed and there were to be a subsequent guile
1177  // exception, cgu_delete_vector cleans up
1178  res = new std::vector<double>;
1179  // allocate 'args' on free store, because the continuation in
1180  // which it executes will be up the stack
1181  args = new VectorDeleteArgs{Double, res};
1182  }
1183  catch (...) {
1184  badalloc = true;
1185  }
1186  if (!badalloc) {
1187  // there may be a weakness in guile's implementation here: if
1188  // calling scm_dynwind_unwind_handler() were to give rise to a
1189  // guile out-of-memory exception before the handler is set up by
1190  // it, then we could leak memory allocated from the preceding
1191  // new expressions. Whether that could happen is not documented
1192  // by guile, but because (a) it is so improbable, and (b) once
1193  // we are in out-of-memory land we are already in severe trouble
1194  // and glib is likely to terminate the program at some point
1195  // anyway, it is not worth troubling ourselves over.
1196  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1197  // convert the list to a guile vector so we can access its items
1198  // efficiently in a for loop. This conversion is reasonably
1199  // efficient, in the sense that an ordinary guile vector is an
1200  // array of pointers, pointing to the same scheme objects that the
1201  // list refers to
1202  SCM guile_vec = scm_vector(scm);
1203 
1204  // std::vector::size_type is the same as size_t with the standard
1205  // allocators (but if we were to get a silent narrowing conversion
1206  // on calling std::vector::reserve() below, that doesn't matter -
1207  // instead if 'length' is less than SIZE_MAX but greater than the
1208  // maximum value of std::vector::size_type, at some point a call
1209  // to std::vector::push_back() below would throw and be caught,
1210  // and this function would end up rethrowing it as std::bad_alloc.
1211  // If in a particular implementation SIZE_MAX exceeds
1212  // std::vector::max_size(), a std::length_error exception would be
1213  // thrown by reserve() where max_size() is exceeded. On all
1214  // common implementations, max_size() is equal to SIZE_MAX, but
1215  // were such an exception to arise it would be swallowed (see
1216  // below) and then rethrown by this function as std::bad_alloc.
1217  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1218  // exception would be thrown by scm_to_size_t() which would be
1219  // rethrown by Cgu:Extension::exec() or
1220  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1221  // C++ exception. This is nice to know but in practice such large
1222  // lists would be unusably slow and a memory exception would be
1223  // reached long before std::vector::max_size() or SIZE_MAX are
1224  // exceeded.
1225  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1226  try {
1227  res->reserve(length);
1228  }
1229  catch (...) {
1230  badalloc = true;
1231  }
1232  for (size_t count = 0;
1233  count < length && !rv_error && !badalloc;
1234  ++count) {
1235  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1236  if (scm_is_false(scm_real_p(item)))
1237  rv_error = "scheme code did not evaluate to a homogeneous list of real numbers\n";
1238  else {
1239  SCM min = scm_from_double(-std::numeric_limits<double>::max());
1240  SCM max = scm_from_double(std::numeric_limits<double>::max());
1241  if (scm_is_false(scm_leq_p(item, max)) || scm_is_false(scm_geq_p(item, min)))
1242  rv_error = "scheme code evaluated out of range for double\n";
1243  else {
1244  try {
1245  res->push_back(scm_to_double(item));
1246  }
1247  catch (...) {
1248  badalloc = true;
1249  }
1250  }
1251  }
1252  }
1253  }
1254  // all done - no more guile exceptions are possible in this function
1255  // after this so end the dynamic context, take control of the memory
1256  // by RAII and if necessary throw a C++ exception
1257  scm_dynwind_end();
1258  std::unique_ptr<std::vector<double>> up_res(res);
1259  std::unique_ptr<VectorDeleteArgs> up_args(args);
1260  if (badalloc) throw std::bad_alloc();
1261  if (rv_error) throw ReturnValueError(rv_error);
1262  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1263  // semantics here, so force it by hand
1264  return std::move(*res);
1265 }
1266 
1267 /**
1268  * A translator function which can be passed to the third argument of
1269  * Extension::exec() or Extension::exec_shared(). It converts from a
1270  * homogeneous scheme list of strings to a C++ representation of
1271  * std::vector<std::string>. It is thread safe, but see the comments
1272  * above about the thread safety of Extension::exec() and
1273  * Extension::exec_shared().
1274  *
1275  * The returned strings will be in UTF-8 encoding.
1276  *
1277  * Note that the first string in the returned list must not be
1278  * "***cgu-guile-exception***": that string is reserved to the
1279  * implementation.
1280  *
1281  * @param scm An opaque guile SCM object representing the value to
1282  * which the extension file passed to Extension::exec() or
1283  * Extension::exec_shared() evaluated, where that value is a
1284  * homogeneous list of strings.
1285  * @return The std::vector<std::string> representation.
1286  * @exception std::bad_alloc This function might throw std::bad_alloc
1287  * if memory is exhausted and the system throws in that case, or if
1288  * the length of the input list exceeds std::vector::max_size().
1289  * @exception Cgu::Extension::GuileException This exception will be
1290  * thrown if the scheme code in the extension file passed to
1291  * Extension::exec() or Extension::exec_shared() caused a guile
1292  * exception to be thrown. Cgu::Extension::GuileException::what()
1293  * will give particulars of the guile exception thrown, in UTF-8
1294  * encoding.
1295  * @exception Cgu::Extension::ReturnValueError This exception will be
1296  * thrown if the scheme code in the extension file passed to
1297  * Extension::exec() or Extension::exec_shared() does not evaluate to
1298  * the type expected by the translator.
1299  * @note No native guile exception will arise in this function and so
1300  * cause guile to jump out of it unless a guile out-of-memory
1301  * condition occurs (given that this function is called after a guile
1302  * extension task has completed, such a condition is very improbable)
1303  * or the length of the input list exceeds SIZE_MAX (the maximum value
1304  * of std::size_t). If such an exception were to arise, the
1305  * implementation would handle it and a C++ exception would be
1306  * generated in its place in Extension::exec() or
1307  * Extension::exec_shared().
1308  *
1309  * Since 2.0.22
1310  */
1311 inline std::vector<std::string> list_to_vector_string(SCM scm) {
1313  if (scm_is_false(scm_list_p(scm)))
1314  throw ReturnValueError("scheme code did not evaluate to a list\n");
1315 
1316  // nothing in this function should throw a guile exception unless
1317  // there is a guile out-of-memory exception (which is extremely
1318  // improbable). However, let's cover ourselves in case.
1319  scm_dynwind_begin(scm_t_dynwind_flags(0));
1320  // we cannot have a std::vector object in a scope where a guile
1321  // exception might be raised because it has a non-trivial
1322  // destructor, nor can we use RAII. Instead allocate on free store
1323  // and manage the memory by hand until we can no longer jump on a
1324  // guile exception. In addition we cannot store a C++ exception
1325  // using std::exception_ptr because std::exception_ptr is not
1326  // trivially destructible.
1327  bool badalloc = false;
1328  const char* rv_error = 0;
1329  std::vector<std::string>* res = 0;
1330  VectorDeleteArgs* args = 0;
1331  try {
1332  // it doesn't matter if the second allocation fails, as we clean
1333  // up at the end if there is no guile exception, and if both
1334  // allocations succeed and there were to be a subsequent guile
1335  // exception, cgu_delete_vector cleans up
1336  res = new std::vector<std::string>;
1337  // allocate 'args' on free store, because the continuation in
1338  // which it executes will be up the stack
1339  args = new VectorDeleteArgs{String, res};
1340  }
1341  catch (...) {
1342  badalloc = true;
1343  }
1344  if (!badalloc) {
1345  // there may be a weakness in guile's implementation here: if
1346  // calling scm_dynwind_unwind_handler() were to give rise to a
1347  // guile out-of-memory exception before the handler is set up by
1348  // it, then we could leak memory allocated from the preceding new
1349  // expressions. Whether that could happen is not documented by
1350  // guile, but because (a) it is so improbable, and (b) once we are
1351  // in out-of-memory land we are already in severe trouble and glib
1352  // is likely to terminate the program at some point anyway, it is
1353  // not worth troubling ourselves over.
1354  scm_dynwind_unwind_handler(&cgu_delete_vector, args, scm_t_wind_flags(0));
1355  // convert the list to a guile vector so we can access its items
1356  // efficiently in a for loop. This conversion is reasonably
1357  // efficient, in the sense that an ordinary guile vector is an
1358  // array of pointers, pointing to the same scheme objects that the
1359  // list refers to
1360  SCM guile_vec = scm_vector(scm);
1361 
1362  // std::vector::size_type is the same as size_t with the standard
1363  // allocators (but if we were to get a silent narrowing conversion
1364  // on calling std::vector::reserve() below, that doesn't matter -
1365  // instead if 'length' is less than SIZE_MAX but greater than the
1366  // maximum value of std::vector::size_type, at some point a call
1367  // to std::vector::emplace_back() below would throw and be caught,
1368  // and this function would end up rethrowing it as std::bad_alloc.
1369  // If in a particular implementation SIZE_MAX exceeds
1370  // std::vector::max_size(), a std::length_error exception would be
1371  // thrown by reserve() where max_size() is exceeded. On all
1372  // common implementations, max_size() is equal to SIZE_MAX, but
1373  // were such an exception to arise it would be swallowed (see
1374  // below) and then rethrown by this function as std::bad_alloc.
1375  // If 'length' is greater than SIZE_MAX, a guile out-of-range
1376  // exception would be thrown by scm_to_size_t() which would be
1377  // rethrown by Cgu:Extension::exec() or
1378  // Cgu::Exception::exec_shared as a Cgu::Extension::WrapperError
1379  // C++ exception. This is nice to know but in practice such large
1380  // lists would be unusably slow and a memory exception would be
1381  // reached long before std::vector::max_size() or SIZE_MAX are
1382  // exceeded.
1383  size_t length = scm_to_size_t(scm_vector_length(guile_vec));
1384  try {
1385  res->reserve(length);
1386  }
1387  catch (...) {
1388  badalloc = true;
1389  }
1390  for (size_t count = 0;
1391  count < length && !rv_error && !badalloc;
1392  ++count) {
1393  SCM item = scm_vector_ref(guile_vec, scm_from_size_t(count));
1394  if (scm_is_false(scm_string_p(item)))
1395  rv_error = "scheme code did not evaluate to a homogeneous list of string\n";
1396  else {
1397  size_t len;
1398  // we don't need a dynwind handler for 'str' because nothing
1399  // after the call to scm_to_utf8_stringn() and before the call
1400  // to free() can cause a guile exception to be raised
1401  char* str = scm_to_utf8_stringn(item, &len);
1402  try {
1403  res->emplace_back(str, len);
1404  }
1405  catch (...) {
1406  badalloc = true;
1407  }
1408  free(str);
1409  }
1410  }
1411  }
1412  // all done - no more guile exceptions are possible in this function
1413  // after this so end the dynamic context, take control of the memory
1414  // by RAII and if necessary throw a C++ exception
1415  scm_dynwind_end();
1416  std::unique_ptr<std::vector<std::string>> up_res(res);
1417  std::unique_ptr<VectorDeleteArgs> up_args(args);
1418  if (badalloc) throw std::bad_alloc();
1419  if (rv_error) throw ReturnValueError(rv_error);
1420  // neither gcc-4.9 nor clang-3.4 will optimize with RVO or move
1421  // semantics here, so force it by hand
1422  return std::move(*res);
1423 }
1424 
1425 /**
1426  * A translator function which can be passed to the third argument of
1427  * Extension::exec() or Extension::exec_shared(). It converts from a
1428  * scheme integer to a C++ representation of long. It is thread safe,
1429  * but see the comments above about the thread safety of
1430  * Extension::exec() and Extension::exec_shared().
1431  *
1432  * @param scm An opaque guile SCM object representing the value to
1433  * which the extension file passed to Extension::exec() or
1434  * Extension::exec_shared() evaluated, where that value is an integer.
1435  * @return The C++ long representation.
1436  * @exception std::bad_alloc This function might throw std::bad_alloc
1437  * if memory is exhausted and the system throws in that case.
1438  * @exception Cgu::Extension::GuileException This exception will be
1439  * thrown if the scheme code in the extension file passed to
1440  * Extension::exec() or Extension::exec_shared() caused a guile
1441  * exception to be thrown. Cgu::Extension::GuileException::what()
1442  * will give particulars of the guile exception thrown, in UTF-8
1443  * encoding.
1444  * @exception Cgu::Extension::ReturnValueError This exception will be
1445  * thrown if the scheme code in the extension file passed to
1446  * Extension::exec() or Extension::exec_shared() does not evaluate to
1447  * the type expected by the translator, or it is out of range for a
1448  * long.
1449  * @note No native guile exception will arise in this function and so
1450  * cause guile to jump out of it if no guile out-of-memory condition
1451  * occurs (given that this function is called after a guile extension
1452  * task has completed, such a condition is very improbable). If such
1453  * an exception were to arise, the implementation would handle it and
1454  * a C++ exception would be generated in its place in
1455  * Extension::exec() or Extension::exec_shared().
1456  *
1457  * Since 2.0.22
1458  */
1459 inline long integer_to_long(SCM scm) {
1461  if (scm_is_false(scm_integer_p(scm)))
1462  throw ReturnValueError("scheme code did not evaluate to an integer\n");
1463  SCM min = scm_from_long(std::numeric_limits<long>::min());
1464  SCM max = scm_from_long(std::numeric_limits<long>::max());
1465  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1466  throw ReturnValueError("scheme code evaluated out of range for long\n");
1467  return scm_to_long(scm);
1468 }
1469 
1470 /**
1471  * A translator function which can be passed to the third argument of
1472  * Extension::exec() or Extension::exec_shared(). It converts from a
1473  * scheme real number to a C++ representation of double. It is thread
1474  * safe, but see the comments above about the thread safety of
1475  * Extension::exec() and Extension::exec_shared().
1476  *
1477  * @param scm An opaque guile SCM object representing the value to
1478  * which the extension file passed to Extension::exec() or
1479  * Extension::exec_shared() evaluated, where that value is a real
1480  * number.
1481  * @return The C++ double representation.
1482  * @exception std::bad_alloc This function might throw std::bad_alloc
1483  * if memory is exhausted and the system throws in that case.
1484  * @exception Cgu::Extension::GuileException This exception will be
1485  * thrown if the scheme code in the extension file passed to
1486  * Extension::exec() or Extension::exec_shared() caused a guile
1487  * exception to be thrown. Cgu::Extension::GuileException::what()
1488  * will give particulars of the guile exception thrown, in UTF-8
1489  * encoding.
1490  * @exception Cgu::Extension::ReturnValueError This exception will be
1491  * thrown if the scheme code in the extension file passed to
1492  * Extension::exec() or Extension::exec_shared() does not evaluate to
1493  * the type expected by the translator, or it is out of range for a
1494  * double.
1495  * @note 1. Prior to version 2.0.25, this translator had a bug which
1496  * caused an out-of-range Cgu::Extension::ReturnValueError to be
1497  * thrown if the scheme code in the extension file evaluated to 0.0 or
1498  * a negative number. This was fixed in version 2.0.25.
1499  * @note 2. No native guile exception will arise in this function and
1500  * so cause guile to jump out of it if no guile out-of-memory
1501  * condition occurs (given that this function is called after a guile
1502  * extension task has completed, such a condition is very improbable).
1503  * If such an exception were to arise, the implementation would handle
1504  * it and a C++ exception would be generated in its place in
1505  * Extension::exec() or Extension::exec_shared().
1506  *
1507  * Since 2.0.22
1508  */
1509 inline double real_to_double(SCM scm) {
1511  if (scm_is_false(scm_real_p(scm)))
1512  throw ReturnValueError("scheme code did not evaluate to a real number\n");
1513  SCM min = scm_from_double(-std::numeric_limits<double>::max());
1514  SCM max = scm_from_double(std::numeric_limits<double>::max());
1515  if (scm_is_false(scm_leq_p(scm, max)) || scm_is_false(scm_geq_p(scm, min)))
1516  throw ReturnValueError("scheme code evaluated out of range for double\n");
1517  return scm_to_double(scm);
1518 }
1519 
1520 /**
1521  * A translator function which can be passed to the third argument of
1522  * Extension::exec() or Extension::exec_shared(). It converts from a
1523  * scheme string to a C++ representation of std::string. It is thread
1524  * safe, but see the comments above about the thread safety of
1525  * Extension::exec() and Extension::exec_shared().
1526  *
1527  * The returned string will be in UTF-8 encoding.
1528  *
1529  * @param scm An opaque guile SCM object representing the value to
1530  * which the extension file passed to Extension::exec() or
1531  * Extension::exec_shared() evaluated, where that value is a string.
1532  * @return The std::string representation.
1533  * @exception std::bad_alloc This function might throw std::bad_alloc
1534  * if memory is exhausted and the system throws in that case.
1535  * @exception Cgu::Extension::GuileException This exception will be
1536  * thrown if the scheme code in the extension file passed to
1537  * Extension::exec() or Extension::exec_shared() caused a guile
1538  * exception to be thrown. Cgu::Extension::GuileException::what()
1539  * will give particulars of the guile exception thrown, in UTF-8
1540  * encoding.
1541  * @exception Cgu::Extension::ReturnValueError This exception will be
1542  * thrown if the scheme code in the extension file passed to
1543  * Extension::exec() or Extension::exec_shared() does not evaluate to
1544  * the type expected by the translator.
1545  * @note No native guile exception will arise in this function and so
1546  * cause guile to jump out of it if no guile out-of-memory condition
1547  * occurs (given that this function is called after a guile extension
1548  * task has completed, such a condition is very improbable). If such
1549  * an exception were to arise, the implementation would handle it and
1550  * a C++ exception would be generated in its place in
1551  * Extension::exec() or Extension::exec_shared().
1552  *
1553  * Since 2.0.22
1554  */
1555 inline std::string string_to_string(SCM scm) {
1557  if (scm_is_false(scm_string_p(scm)))
1558  throw ReturnValueError("scheme code did not evaluate to a string\n");
1559  size_t len;
1560  // it is safe to use unique_ptr here. If scm_to_utf8_stringn()
1561  // succeeds then nothing after it in this function can cause a guile
1562  // exception.
1563  std::unique_ptr<const char, Cgu::CFree> s(scm_to_utf8_stringn(scm, &len));
1564  return std::string(s.get(), len);
1565 }
1566 
1567 /**
1568  * A translator function which can be passed to the third argument of
1569  * Extension::exec() or Extension::exec_shared(). It disregards the
1570  * scheme value passed to it except to trap any guile exception thrown
1571  * by the scheme task and rethrow it as a C++ exception, and returns a
1572  * NULL void* object. It is thread safe, but see the comments above
1573  * about the thread safety of Extension::exec() and
1574  * Extension::exec_shared().
1575  *
1576  * It is mainly intended for use where the scheme script is executed
1577  * for its side effects, perhaps for I/O, and any communication
1578  * necessary is done by guile exceptions.
1579  *
1580  * @param scm An opaque guile SCM object representing the value to
1581  * which the extension file passed to Extension::exec() or
1582  * Extension::exec_shared() evaluated, which is ignored.
1583  * @return A NULL void* object.
1584  * @exception std::bad_alloc This function might throw std::bad_alloc
1585  * if memory is exhausted and the system throws in that case.
1586  * @exception Cgu::Extension::GuileException This exception will be
1587  * thrown if the scheme code in the extension file passed to
1588  * Extension::exec() or Extension::exec_shared() caused a guile
1589  * exception to be thrown. Cgu::Extension::GuileException::what()
1590  * will give particulars of the guile exception thrown, in UTF-8
1591  * encoding.
1592  * @note No native guile exception will arise in this function and so
1593  * cause guile to jump out of it if no guile out-of-memory condition
1594  * occurs (given that this function is called after a guile extension
1595  * task has completed, such a condition is very improbable). If such
1596  * an exception were to arise, the implementation would handle it and
1597  * a C++ exception would be generated in its place in
1598  * Extension::exec() or Extension::exec_shared().
1599  *
1600  * Since 2.0.22
1601  */
1602 inline void* any_to_void(SCM scm) {
1604  return 0;
1605 }
1606 
1607 /**
1608  * This function executes scheme code on the guile VM within a C++
1609  * program using this library. See the introductory remarks above for
1610  * its potential uses, about the thread safety of this function, and
1611  * about the use of the TaskManager::exec_shared() as an alternative.
1612  *
1613  * The first argument to this function is a preamble, which can be
1614  * used to pass top level definitions to the scheme code (in other
1615  * words, for argument passing). It's second argument is the filename
1616  * (with path) of the file containing the scheme code to be executed.
1617  * It's third argument is a translator, which will convert the value
1618  * to which the scheme code evaluates (in C++ terms, its return value)
1619  * to a suitable C++ representation. Preformed translators are
1620  * provided by this library to translate from scheme's integers, real
1621  * numbers and strings to C++ longs, doubles and strings respectively,
1622  * and from any uniform lists of these to C++ vectors of the
1623  * corresponding type. There is also a translator for void return
1624  * types. See the introductory remarks above for more information
1625  * about translators.
1626  *
1627  * Any native guile exceptions thrown by the code executed by this
1628  * function (and by any code which it calls) are converted and
1629  * rethrown as C++ exceptions.
1630  *
1631  * The scheme file can call other scheme code, and load modules, in
1632  * the ordinary way. Thus, this function can execute any scheme code
1633  * which guile can execute as a program, and the programmer can (if
1634  * wanted) act on its return value in the C++ code which invokes it.
1635  *
1636  * Thread cancellation is blocked for the thread in which this
1637  * function executes until this function returns.
1638  *
1639  * @param preamble Scheme code such as top level definitions to be
1640  * seen by the code in the file to be executed. This is mainly
1641  * intended for argument passing, but can comprise any valid scheme
1642  * code. It can also be empty (you can pass ""). Any string literals
1643  * must be in UTF-8 encoding.
1644  * @param file The file which is to be executed on the guile VM. This
1645  * should include the full pathname or a pathname relative to the
1646  * current directory. The contents of the file, and in particular any
1647  * string literals in it, must be in UTF-8 encoding. The filename and
1648  * path must also be given in UTF-8 encoding, even if the local
1649  * filename encoding is something different: guile will convert the
1650  * UTF-8 name which it is given to its own internal string encoding
1651  * using unicode code points, and then convert that to locale encoding
1652  * on looking up the filename. However sticking to ASCII for
1653  * filenames and paths (which is always valid UTF-8) will maximise
1654  * portability. The file name can be empty (you can pass ""), in
1655  * which case only the preamble will be evaluated (but for efficiency
1656  * reasons any complex code not at the top level should be included in
1657  * the file rather than in the preamble).
1658  * @param translator The function or callable object which will
1659  * convert the value to which the scheme code evaluates to a C++
1660  * representation which will be returned by this function. The
1661  * translator should take a single argument comprising an opaque guile
1662  * object of type SCM, and return the C++ representation for it.
1663  * @return The C++ representation returned by the translator.
1664  * @exception std::bad_alloc This function might throw std::bad_alloc
1665  * if memory is exhausted and the system throws in that case.
1666  * @exception Cgu::Extension::GuileException This exception will be
1667  * thrown if the scheme code in 'file' (or called by it) throws a
1668  * guile exception. Cgu::Extension::GuileException::what() will give
1669  * particulars of the guile exception thrown, in UTF-8 encoding.
1670  * @exception Cgu::Extension::ReturnValueError This exception will be
1671  * thrown if the code in 'file' does not evaluate to the type expected
1672  * by the translator.
1673  * @exception Cgu::Extension::WrapperError This exception will be
1674  * thrown if a custom translator throws a native guile exception or a
1675  * C++ exception not comprising Extension::GuileException or
1676  * Extension::ReturnValueError, one of the preformed translators
1677  * throws std::bad_alloc or encounters a guile out-of-memory
1678  * exception, one of the preformed list translators encounters an
1679  * input list exceeding SIZE_MAX in length, assigning to an internal
1680  * exception description string throws std::bad_alloc, or evaluation
1681  * of the preamble throws a native guile exception.
1682  *
1683  * Since 2.0.22
1684  */
1685 // we cannot take 'translator' by collapsible reference, because with
1686 // gcc-4.4 std::result_of fails if Translator deduces to a reference
1687 // type, and gcc-4.4 does not have std::declval. This is fixed in the
1688 // 2.2 series of this library, which has a minimum requirement of
1689 // gcc-4.6.
1690 template <class Translator>
1691 auto exec(const std::string& preamble,
1692  const std::string& file,
1693  Translator translator) -> typename std::result_of<Translator(SCM)>::type {
1694  // exec_impl() will fail to compile if Ret is a reference type: that
1695  // is a feature, not a bug, as there is no good reason for a
1696  // translator ever to return a reference
1697  typedef typename std::result_of<Translator(SCM)>::type Ret;
1698  return exec_impl<Ret>(preamble, file, translator, false);
1699 }
1700 
1701 /**
1702  * This function executes scheme code on the guile VM within a C++
1703  * program using this library. See the introductory remarks above for
1704  * its potential uses, about the thread safety of this function, and
1705  * about the use of the TaskManager::exec() as an alternative.
1706  *
1707  * The first argument to this function is a preamble, which can be
1708  * used to pass top level definitions to the scheme code (in other
1709  * words, for argument passing). It's second argument is the filename
1710  * (with path) of the file containing the scheme code to be executed.
1711  * It's third argument is a translator, which will convert the value
1712  * to which the scheme code evaluates (in C++ terms, its return value)
1713  * to a suitable C++ representation. Preformed translators are
1714  * provided by this library to translate from scheme's integers, real
1715  * numbers and strings to C++ longs, doubles and strings respectively,
1716  * and from any uniform lists of these to C++ vectors of the
1717  * corresponding type. There is also a translator for void return
1718  * types. See the introductory remarks above for more information
1719  * about translators.
1720  *
1721  * Any native guile exceptions thrown by the code executed by this
1722  * function (and by any code which it calls) are converted and
1723  * rethrown as C++ exceptions.
1724  *
1725  * The scheme file can call other scheme code, and load modules, in
1726  * the ordinary way. Thus, this function can execute any scheme code
1727  * which guile can execute as a program, and the programmer can (if
1728  * wanted) act on its return value in the C++ code which invokes it.
1729  *
1730  * Thread cancellation is blocked for the thread in which this
1731  * function executes until this function returns.
1732  *
1733  * @param preamble Scheme code such as top level definitions to be
1734  * seen by the code in the file to be executed. This is mainly
1735  * intended for argument passing, but can comprise any valid scheme
1736  * code. It can also be empty (you can pass ""). Any string literals
1737  * must be in UTF-8 encoding.
1738  * @param file The file which is to be executed on the guile VM. This
1739  * should include the full pathname or a pathname relative to the
1740  * current directory. The contents of the file, and in particular any
1741  * string literals in it, must be in UTF-8 encoding. The filename and
1742  * path must also be given in UTF-8 encoding, even if the local
1743  * filename encoding is something different: guile will convert the
1744  * UTF-8 name which it is given to its own internal string encoding
1745  * using unicode code points, and then convert that to locale encoding
1746  * on looking up the filename. However sticking to ASCII for
1747  * filenames and paths (which is always valid UTF-8) will maximise
1748  * portability. The file name can be empty (you can pass ""), in
1749  * which case only the preamble will be evaluated.
1750  * @param translator The function or callable object which will
1751  * convert the value to which the scheme code evaluates to a C++
1752  * representation which will be returned by this function. The
1753  * translator should take a single argument comprising an opaque guile
1754  * object of type SCM, and return the C++ representation for it.
1755  * @return The C++ representation returned by the translator.
1756  * @exception std::bad_alloc This function might throw std::bad_alloc
1757  * if memory is exhausted and the system throws in that case.
1758  * @exception Cgu::Extension::GuileException This exception will be
1759  * thrown if the scheme code in 'file' (or called by it) throws a
1760  * guile exception. Cgu::Extension::GuileException::what() will give
1761  * particulars of the guile exception thrown, in UTF-8 encoding.
1762  * @exception Cgu::Extension::ReturnValueError This exception will be
1763  * thrown if the code in 'file' does not evaluate to the type expected
1764  * by the translator.
1765  * @exception Cgu::Extension::WrapperError This exception will be
1766  * thrown if a custom translator throws a native guile exception or a
1767  * C++ exception not comprising Extension::GuileException or
1768  * Extension::ReturnValueError, one of the preformed translators
1769  * throws std::bad_alloc or encounters a guile out-of-memory
1770  * exception, one of the preformed list translators encounters an
1771  * input list exceeding SIZE_MAX in length, assigning to an internal
1772  * exception description string throws std::bad_alloc, or evaluation
1773  * of the preamble throws a native guile exception.
1774  *
1775  * Since 2.0.24
1776  */
1777 // we cannot take 'translator' by collapsible reference, because with
1778 // gcc-4.4 std::result_of fails if Translator deduces to a reference
1779 // type, and gcc-4.4 does not have std::declval. This is fixed in the
1780 // 2.2 series of this library, which has a minimum requirement of
1781 // gcc-4.6.
1782 template <class Translator>
1783 auto exec_shared(const std::string& preamble,
1784  const std::string& file,
1785  Translator translator) -> typename std::result_of<Translator(SCM)>::type {
1786  // exec_impl() will fail to compile if Ret is a reference type: that
1787  // is a feature, not a bug, as there is no good reason for a
1788  // translator ever to return a reference
1789  typedef typename std::result_of<Translator(SCM)>::type Ret;
1790  return exec_impl<Ret>(preamble, file, translator, true);
1791 }
1792 
1793 } // namespace Extension
1794 
1795 } // namespace Cgu
1796 
1797 #endif // CGU_EXTENSION_H
virtual const char * what() const
Definition: extension.h:586
std::vector< long > list_to_vector_long(SCM scm)
Definition: extension.h:995
GuileException(const char *msg)
Definition: extension.h:576
long integer_to_long(SCM scm)
Definition: extension.h:1459
~ReturnValueError()
Definition: extension.h:591
~GuileException()
Definition: extension.h:579
void * any_to_void(SCM scm)
Definition: extension.h:1602
const char * err_text() const
Definition: extension.h:587
auto exec(const std::string &preamble, const std::string &file, Translator translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1691
virtual const char * what() const
Definition: extension.h:597
virtual const char * what() const
Definition: extension.h:574
const char * guile_text() const
Definition: extension.h:575
WrapperError(const char *msg)
Definition: extension.h:598
This file provides classes for type erasure.
Definition: extension.h:582
A class enabling the cancellation state of a thread to be controlled.
Definition: thread.h:686
double real_to_double(SCM scm)
Definition: extension.h:1509
Definition: extension.h:570
std::string string_to_string(SCM scm)
Definition: extension.h:1555
std::vector< double > list_to_vector_double(SCM scm)
Definition: extension.h:1153
auto exec_shared(const std::string &preamble, const std::string &file, Translator translator) -> typename std::result_of< Translator(SCM)>::type
Definition: extension.h:1783
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:827
std::vector< std::string > list_to_vector_string(SCM scm)
Definition: extension.h:1311
Definition: extension.h:594
~WrapperError()
Definition: extension.h:600
void rethrow_guile_exception(SCM scm)
Definition: extension.h:913
T get() const
Definition: shared_handle.h:762
ReturnValueError(const char *msg)
Definition: extension.h:588
The callback interface class.
Definition: callback.h:522