c++-gtk-utils: extension.h Source File

c++-gtk-utils

- Main Page
- Related Pages
- Modules
- Namespaces
- Classes
- Files

- File List
- File Members

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