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