Fixed error location.
[riece] / lisp / riece-ruby.el
1 ;;; riece-ruby.el --- interact with Ruby interpreter
2 ;; Copyright (C) 1998-2005 Daiki Ueno
3
4 ;; Author: Daiki Ueno <ueno@unixuser.org>
5 ;; Created: 1998-09-28
6 ;; Keywords: IRC, riece, Ruby
7
8 ;; This file is part of Riece.
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; riece-ruby.el is a library to interact with Ruby interpreter.
28 ;; It supports concurrent execution of Ruby programs in a single
29 ;; session.  For example:
30 ;; 
31 ;; (riece-ruby-execute "sleep 30"); returns immediately
32 ;; => "rubyserv0"
33 ;;
34 ;; (riece-ruby-execute "1 + 1")
35 ;; => "rubyserv1"
36 ;;
37 ;; (riece-ruby-execute "\"")
38 ;; => "rubyserv2"
39 ;;
40 ;; (riece-ruby-inspect "rubyserv0")
41 ;; => ((OK nil) nil (("running")))
42 ;;
43 ;; (riece-ruby-inspect "rubyserv1")
44 ;; => ((OK nil) "2" (("finished")))
45 ;;
46 ;; (riece-ruby-inspect "rubyserv2")
47 ;; => ((OK nil) "(eval):1: unterminated string meets end of file" (("exited")))
48
49 ;;; Code:
50
51 (require 'riece-debug)
52
53 (defgroup riece-ruby nil
54   "Interact with Ruby interpreter."
55   :group 'riece)
56
57 (defcustom riece-ruby-command "ruby"
58   "Command name for Ruby interpreter."
59   :type 'string
60   :group 'riece-ruby)
61
62 (defcustom riece-ruby-out-file (expand-file-name "riece-ruby.out"
63                                                  riece-directory)
64   "A file which records stdout of Ruby programs."
65   :type 'string
66   :group 'riece-ruby)
67
68 (defcustom riece-ruby-err-file (expand-file-name "riece-ruby.err"
69                                                  riece-directory)
70   "A file which records stderr of Ruby programs."
71   :type 'string
72   :group 'riece-ruby)
73
74 (defcustom riece-ruby-log-file (expand-file-name "riece-ruby.log"
75                                                  riece-directory)
76   "A file used to logging."
77   :type 'string
78   :group 'riece-ruby)
79
80 (defvar riece-ruby-server-program "server.rb"
81   "The server program file.  If the filename is not absolute, it is
82 assumed that the file is in the same directory of this file.")
83
84 (defvar riece-ruby-server-program-arguments (list "-o" riece-ruby-out-file
85                                                   "-e" riece-ruby-err-file
86                                                   "-l" riece-ruby-log-file)
87   "Command line arguments passed to `riece-ruby-server-program'.")
88
89 (defvar riece-ruby-process nil
90   "Process object of Ruby interpreter.")
91
92 (defvar riece-ruby-lock nil
93   "Lock for waiting server response.
94 Local to the process buffer.")
95 (defvar riece-ruby-response nil
96   "The server response.
97 Local to the process buffer.")
98 (defvar riece-ruby-data nil
99   "Data from server.
100 Local to the process buffer.")
101 (defvar riece-ruby-escaped-data nil
102   "Escaped data from server.  This variable is cleared every time
103 server response arrives.
104 Local to the process buffer.")
105 (defvar riece-ruby-status-alist nil
106   "Status from server.
107 Local to the process buffer.")
108
109 (defvar riece-ruby-output-queue-alist nil
110   "An alist mapping from program name to output data.")
111 (defvar riece-ruby-output-handler-alist nil
112   "An alist mapping from program name to output handler.
113 Output handlers are called every time \"# output\" line arrives.
114 Use `riece-ruby-set-output-handler' to set this variable.")
115 (defvar riece-ruby-exit-handler-alist nil
116   "An alist mapping from program name to exit handler.
117 Exit handlers are called once when \"# exit\" line arrives.
118 Use `riece-ruby-set-exit-handler' to set this variable.")
119 (defvar riece-ruby-property-alist nil
120   "An alist mapping from program name to the property list.
121 Use `riece-ruby-set-property' to set this variable.")
122
123 (defun riece-ruby-escape-data (data)
124   (let ((index 0))
125     (while (string-match "[%\r\n]+" data index)
126       (setq data (replace-match
127                   (mapconcat (lambda (c) (format "%%%02X" c))
128                              (match-string 0 data) "")
129                   nil nil data)
130             index (+ (match-end 0)
131                      (* (- (match-end 0) (match-beginning 0)) 2))))
132     data))
133
134 (defun riece-ruby-unescape-data (data)
135   (let ((index 0))
136     (while (string-match "%\\([0-9A-F][0-9A-F]\\)" data index)
137       (setq data (replace-match
138                   (read (concat "\"\\x" (match-string 1 data) "\""))
139                   nil nil data)
140             index (- (match-end 0) 2)))
141     data))
142
143 (defun riece-ruby-reset-process-buffer ()
144   (save-excursion
145     (set-buffer (process-buffer riece-ruby-process))
146     (buffer-disable-undo)
147     (make-local-variable 'riece-ruby-response)
148     (setq riece-ruby-response nil)
149     (make-local-variable 'riece-ruby-data)
150     (setq riece-ruby-data nil)
151     (make-local-variable 'riece-ruby-escaped-data)
152     (setq riece-ruby-escaped-data nil)
153     (make-local-variable 'riece-ruby-status-alist)
154     (setq riece-ruby-status-alist nil)))
155
156 (defun riece-ruby-send-eval (program)
157   (let* ((string (riece-ruby-escape-data program))
158          (length (- (length string) 998))
159          (index 0)
160          data)
161     (while (< index length)
162       (setq data (cons (substring string index (setq index (+ index 998)))
163                        data)))
164     (setq data (cons (substring string index) data)
165           data (nreverse data))
166     (process-send-string riece-ruby-process "EVAL\r\n")
167     (while data
168       (process-send-string riece-ruby-process
169                            (concat "D " (car data) "\r\n"))
170       (setq data (cdr data)))
171     (process-send-string riece-ruby-process "END\r\n")))
172
173 (defun riece-ruby-send-poll (name)
174   (process-send-string riece-ruby-process
175                        (concat "POLL " name "\r\n")))
176
177 (defun riece-ruby-send-exit (name)
178   (process-send-string riece-ruby-process
179                        (concat "EXIT " name "\r\n")))
180
181 (defun riece-ruby-filter (process input)
182   (save-excursion
183     (set-buffer (process-buffer process))
184     (goto-char (point-max))
185     (insert input)
186     (goto-char (point-min))
187     (beginning-of-line)
188     (while (looking-at ".*\r\n")
189       (if (looking-at "OK\\( \\(.*\\)\\)?\r")
190           (progn
191             (if riece-ruby-escaped-data
192                 (setq riece-ruby-data (mapconcat #'riece-ruby-unescape-data
193                                                  riece-ruby-escaped-data "")))
194             (setq riece-ruby-escaped-data nil
195                   riece-ruby-response (list 'OK (match-string 2))
196                   riece-ruby-lock nil))
197         (if (looking-at "ERR \\([0-9]+\\)\\( \\(.*\\)\\)?\r")
198             (progn
199               (setq riece-ruby-escaped-data nil
200                     riece-ruby-response
201                     (list 'ERR (string-to-number (match-string 1))
202                           (match-string 3))
203                     riece-ruby-lock nil))
204           (if (looking-at "D \\(.*\\)\r")
205               (setq riece-ruby-escaped-data (cons (match-string 1)
206                                                   riece-ruby-escaped-data))
207             (if (looking-at "S \\([^ ]*\\) \\(.*\\)\r")
208                 (progn
209                   (setq riece-ruby-status-alist (cons (cons (match-string 1)
210                                                             (match-string 2))
211                                                       riece-ruby-status-alist))
212                   (if (member (car (car riece-ruby-status-alist))
213                               '("finished" "exited"))
214                       (riece-ruby-run-exit-handler
215                        (cdr (car riece-ruby-status-alist)))))
216               (if (looking-at "# output \\([^ ]*\\) \\(.*\\)\r")
217                   (riece-ruby-run-output-handler (match-string 1)
218                                                  (match-string 2))
219                 (if (looking-at "# exit \\(.*\\)\r")
220                     (riece-ruby-run-exit-handler (match-string 1))))))))
221       (forward-line))
222     (delete-region (point-min) (point))))
223
224 (defun riece-ruby-run-exit-handler (name)
225   (let ((entry (assoc name riece-ruby-exit-handler-alist)))
226     (when entry
227       (setq riece-ruby-exit-handler-alist
228             (delq entry riece-ruby-exit-handler-alist))
229       (riece-funcall-ignore-errors name (cdr entry) (car entry))
230       (riece-ruby-clear name))))
231
232 (defun riece-ruby-run-output-handler (name output)
233   (let ((handler-entry (assoc name riece-ruby-output-handler-alist))
234         (entry (assoc name riece-ruby-output-queue-alist)))
235     (if handler-entry
236         (riece-funcall-ignore-errors name (cdr handler-entry) name output)
237       (if entry
238           (setcdr entry (cons output (cdr entry)))
239         (setq riece-ruby-output-queue-alist
240               (cons (list name output)
241                     riece-ruby-output-queue-alist))))))
242
243 (defun riece-ruby-sentinel (process status)
244   (kill-buffer (process-buffer process)))
245
246 (defun riece-ruby-execute (program)
247   "Schedule an execution of a Ruby PROGRAM.
248 Return a string name assigned by the server."
249   (unless (and riece-ruby-process
250                (eq (process-status riece-ruby-process) 'run))
251     (let (selective-display
252           (coding-system-for-write 'binary)
253           (coding-system-for-read 'binary))
254       (setq riece-ruby-process
255             (apply #'start-process "riece-ruby" (generate-new-buffer " *Ruby*")
256                    riece-ruby-command
257                    (if (file-name-absolute-p riece-ruby-server-program)
258                        riece-ruby-server-program
259                      (expand-file-name
260                       riece-ruby-server-program
261                       (file-name-directory
262                        (locate-library
263                         (symbol-file 'riece-ruby-execute)))))
264                    riece-ruby-server-program-arguments))
265       (process-kill-without-query riece-ruby-process)
266       (set-process-filter riece-ruby-process #'riece-ruby-filter)
267       (set-process-sentinel riece-ruby-process #'riece-ruby-sentinel)))
268   (save-excursion
269     (set-buffer (process-buffer riece-ruby-process))
270     (riece-ruby-reset-process-buffer)
271     (make-local-variable 'riece-ruby-lock)
272     (setq riece-ruby-lock t)
273     (riece-ruby-send-eval program)
274     (while riece-ruby-lock
275       (accept-process-output riece-ruby-process))
276     (if (eq (car riece-ruby-response) 'ERR)
277         (error "Couldn't execute: %S" (cdr riece-ruby-response)))
278     (cdr (assoc "name" riece-ruby-status-alist))))
279
280 (defun riece-ruby-inspect (name)
281   "Inspect a result of program execution distinguished by NAME.
282 Return a three element list.
283 The car is protocol response line which looks like:
284   \(ERR 103 \"Not implemented\").
285 The cadr is data from the server, that is, the result of the program.
286 The caddr is status from the server."
287   (save-excursion
288     (set-buffer (process-buffer riece-ruby-process))
289     (riece-ruby-reset-process-buffer)
290     (make-local-variable 'riece-ruby-lock)
291     (setq riece-ruby-lock t)
292     (riece-ruby-send-poll name)
293     (while riece-ruby-lock
294       (accept-process-output riece-ruby-process))
295     (list riece-ruby-response
296           riece-ruby-data
297           riece-ruby-status-alist)))
298
299 (defun riece-ruby-clear (name)
300   "Clear a result of program execution distinguished by NAME.
301 Note that riece-ruby-clear is automatically called iff an exit-handler
302 is specified.  Otherwise, it should be called explicitly."
303   (save-excursion
304     (set-buffer (process-buffer riece-ruby-process))
305     (riece-ruby-reset-process-buffer)
306     (make-local-variable 'riece-ruby-lock)
307     (setq riece-ruby-lock t)
308     (riece-ruby-send-exit name)
309     (while riece-ruby-lock
310       (accept-process-output riece-ruby-process)))
311   (let ((entry (assoc name riece-ruby-property-alist)))
312     (if entry
313         (delq entry riece-ruby-property-alist))))
314
315 (defun riece-ruby-set-exit-handler (name handler)
316   "Set an exit-handler HANDLER for the program distinguished by NAME.
317 An exit-handler is called when the program is finished or exited abnormally.
318 An exit-handler is called with an argument same as NAME.
319 Note that riece-ruby-clear is automatically called iff an exit-handler
320 is specified.  Otherwise, it should be called explicitly."
321   (let ((entry (assoc name riece-ruby-exit-handler-alist)))
322     (if handler
323         (progn
324           (if entry
325               (setcdr entry handler)
326             (setq riece-ruby-exit-handler-alist
327                   (cons (cons name handler)
328                         riece-ruby-exit-handler-alist)))
329           ;;check if the program already exited
330           (riece-ruby-inspect name))
331       (if entry
332           (setq riece-ruby-exit-handler-alist
333                 (delq entry riece-ruby-exit-handler-alist))))))
334
335 (defun riece-ruby-set-output-handler (name handler)
336   "Set an output-handler HANDLER for the program distinguished by NAME.
337 An output-handler is called when the program sends any output by using
338 `output' method in the Ruby program.
339 An output-handler is called with two argument.  The first argument is
340 the same as NAME.  The second argument is output string."
341   (let ((entry (assoc name riece-ruby-output-handler-alist))
342         queue-entry pointer)
343     (if handler
344         (progn
345           (when (setq queue-entry (assoc name riece-ruby-output-queue-alist))
346             (setq pointer (nreverse (cdr queue-entry))
347                   riece-ruby-output-queue-alist
348                   (delq queue-entry riece-ruby-output-queue-alist))
349             (while pointer
350               (riece-funcall-ignore-errors name handler name (car pointer))
351               (setq pointer (cdr pointer))))
352           (if entry
353               (setcdr entry handler)
354             (setq riece-ruby-output-handler-alist
355                   (cons (cons name handler)
356                         riece-ruby-output-handler-alist))))
357       (if entry
358           (setq riece-ruby-output-handler-alist
359                 (delq entry riece-ruby-output-handler-alist))))))
360
361 (defun riece-ruby-set-property (name property value)
362   "Set given PROPERTY/VALUE pair to the program distinguished by NAME."
363   (let ((entry (assoc name riece-ruby-property-alist))
364         property-entry)
365     (unless entry
366       (setq entry (list name)
367             riece-ruby-property-alist (cons entry riece-ruby-property-alist)))
368     (if (setq property-entry (assoc property (cdr entry)))
369         (setcdr property-entry value)
370       (setcdr entry (cons (cons property value) (cdr entry))))))
371
372 (defun riece-ruby-property (name property)
373   "Return the value of PROPERTY set to the program distinguished by NAME."
374   (cdr (assoc property (cdr (assoc name riece-ruby-property-alist)))))
375
376 (defun riece-ruby-substitute-variables (program alist)
377   "Substitute symbols in PROGRAM by looking up ALIST.
378 Return a string concatenating elements in PROGRAM."
379   (setq program (copy-sequence program))
380   (while alist
381     (let ((pointer program))
382       (while pointer
383         (setq pointer (memq (car (car alist)) program))
384         (if pointer
385             (setcar pointer (cdr (car alist))))))
386     (setq alist (cdr alist)))
387   (apply #'concat program))
388
389 (provide 'riece-ruby)
390
391 ;;; riece-ruby.el ends here