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 #:replace (eval-string))
26
27 (define (ensure-language x)
28 (if (language? x)
29 x
30 (lookup-language x)))
31
32 (define* (read-and-eval port #:key (lang (current-language)))
33 (parameterize ((current-language (ensure-language lang)))
34 (define (read)
35 ((language-reader (current-language)) port (current-module)))
36 (define (eval exp)
37 ((language-evaluator (current-language)) exp (current-module)))
38
39 (let ((exp (read)))
40 (if (eof-object? exp)
41 ;; The behavior of read-and-compile and of the old
42 ;; eval-string.
43 *unspecified*
44 (let lp ((exp exp))
45 (call-with-values
46 (lambda () (eval exp))
47 (lambda vals
48 (let ((next (read)))
49 (cond
50 ((eof-object? next)
51 (apply values vals))
52 (else
53 (lp next)))))))))))
54
55 (define* (eval-string str #:key
56 (module (current-module))
57 (file #f)
58 (line #f)
59 (column #f)
60 (lang (current-language))
61 (compile? #f))
62 (define (maybe-with-module module thunk)
63 (if module
64 (save-module-excursion
65 (lambda ()
66 (set-current-module module)
67 (thunk)))
68 (thunk)))
69
70 (let ((lang (ensure-language lang)))
71 (call-with-input-string
72 str
73 (lambda (port)
74 (maybe-with-module
75 module
76 (lambda ()
77 (if module
78 (set-current-module module))
79 (if file
80 (set-port-filename! port file))
81 (if line
82 (set-port-line! port line))
83 (if column
84 (set-port-column! port line))
85
86 (if (or compile? (not (language-evaluator lang)))
87 ((make-program (read-and-compile port #:from lang #:to 'objcode)))
88 (read-and-eval port #:lang lang))))))))