Merge remote-tracking branch 'origin/stable-2.0'
[bpt/guile.git] / module / ice-9 / eval-string.scm
1 ;;; Evaluating code from users
2
3 ;;; Copyright (C) 2011, 2013 Free Software Foundation, Inc.
4
5 ;;;; This library is free software; you can redistribute it and/or
6 ;;;; modify it under the terms of the GNU Lesser General Public
7 ;;;; License as published by the Free Software Foundation; either
8 ;;;; version 3 of the License, or (at your option) any later version.
9 ;;;;
10 ;;;; This library is distributed in the hope that it will be useful,
11 ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;;;; Lesser General Public License for more details.
14 ;;;;
15 ;;;; You should have received a copy of the GNU Lesser General Public
16 ;;;; License along with this library; if not, write to the Free Software
17 ;;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18
19 ;;; Code:
20
21 (define-module (ice-9 eval-string)
22 #:use-module (system base compile)
23 #:use-module (system base language)
24 #:use-module (system vm program)
25 #:use-module (system vm loader)
26 #:replace (eval-string))
27
28 (define (ensure-language x)
29 (if (language? x)
30 x
31 (lookup-language x)))
32
33 (define* (read-and-eval port #:key (lang (current-language)))
34 (parameterize ((current-language (ensure-language lang)))
35 (define (read)
36 ((language-reader (current-language)) port (current-module)))
37 (define (eval exp)
38 ((language-evaluator (current-language)) exp (current-module)))
39
40 (let ((exp (read)))
41 (if (eof-object? exp)
42 ;; The behavior of read-and-compile and of the old
43 ;; eval-string.
44 *unspecified*
45 (let lp ((exp exp))
46 (call-with-values
47 (lambda () (eval exp))
48 (lambda vals
49 (let ((next (read)))
50 (cond
51 ((eof-object? next)
52 (apply values vals))
53 (else
54 (lp next)))))))))))
55
56 (define* (eval-string str #:key
57 (module (current-module))
58 (file #f)
59 (line #f)
60 (column #f)
61 (lang (current-language))
62 (compile? #f))
63 (define (maybe-with-module module thunk)
64 (if module
65 (save-module-excursion
66 (lambda ()
67 (set-current-module module)
68 (thunk)))
69 (thunk)))
70
71 (let ((lang (ensure-language lang)))
72 (call-with-input-string
73 str
74 (lambda (port)
75 (maybe-with-module
76 module
77 (lambda ()
78 (if module
79 (set-current-module module))
80 (if file
81 (set-port-filename! port file))
82 (if line
83 (set-port-line! port line))
84 (if column
85 (set-port-column! port line))
86
87 (if (or compile? (not (language-evaluator lang)))
88 ((load-thunk-from-memory
89 (read-and-compile port #:from lang #:to 'rtl)))
90 (read-and-eval port #:lang lang))))))))