Check if make-local-hook exists.
[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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, 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   :prefix "riece-"
56   :group 'riece)
57
58 (defcustom riece-ruby-command "ruby"
59   "Command name for Ruby interpreter."
60   :type 'string
61   :group 'riece-ruby)
62
63 (defcustom riece-ruby-out-file (expand-file-name "riece-ruby.out"
64                                                  riece-directory)
65   "A file which records stdout of Ruby programs."
66   :type 'string
67   :group 'riece-ruby)
68
69 (defcustom riece-ruby-err-file (expand-file-name "riece-ruby.err"
70                                                  riece-directory)
71   "A file which records stderr of Ruby programs."
72   :type 'string
73   :group 'riece-ruby)
74
75 (defcustom riece-ruby-log-file (expand-file-name "riece-ruby.log"
76                                                  riece-directory)
77   "A file used to logging."
78   :type 'string
79   :group 'riece-ruby)
80
81 (defvar riece-ruby-server-program "server.rb"
82   "The server program file.  If the filename is not absolute, it is
83 assumed that the file is in the same directory of this file.")
84
85 (defvar riece-ruby-server-program-arguments (list "-o" riece-ruby-out-file
86                                                   "-e" riece-ruby-err-file
87                                                   "-l" riece-ruby-log-file)
88   "Command line arguments passed to `riece-ruby-server-program'.")
89
90 (defvar riece-ruby-process nil
91   "Process object of Ruby interpreter.")
92
93 (defvar riece-ruby-lock nil
94   "Lock for waiting server response.
95 Local to the process buffer.")
96 (defvar riece-ruby-response nil
97   "The server response.
98 Local to the process buffer.")
99 (defvar riece-ruby-data nil
100   "Data from server.
101 Local to the process buffer.")
102 (defvar riece-ruby-escaped-data nil
103   "Escaped data from server.  This variable is cleared every time
104 server response arrives.
105 Local to the process buffer.")
106 (defvar riece-ruby-status-alist nil
107   "Status from server.
108 Local to the process buffer.")
109
110 (defvar riece-ruby-output-queue-alist nil
111   "An alist mapping from program name to output data.")
112 (defvar riece-ruby-output-handler-alist nil
113   "An alist mapping from program name to output handler.
114 Output handlers are called every time \"# output\" line arrives.
115 Use `riece-ruby-set-output-handler' to set this variable.")
116 (defvar riece-ruby-exit-handler-alist nil
117   "An alist mapping from program name to exit handler.
118 Exit handlers are called once when \"# exit\" line arrives.
119 Use `riece-ruby-set-exit-handler' to set this variable.")
120 (defvar riece-ruby-property-alist nil
121   "An alist mapping from program name to the property list.
122 Use `riece-ruby-set-property' to set this variable.")
123
124 (defun riece-ruby-escape-data (data)
125   (let ((index 0))
126     (while (string-match "[%\r\n]+" data index)
127       (setq data (replace-match
128                   (mapconcat (lambda (c) (format "%%%02X" c))
129                              (match-string 0 data) "")
130                   nil nil data)
131             index (+ (match-end 0)
132                      (* (- (match-end 0) (match-beginning 0)) 2))))
133     data))
134
135 (defun riece-ruby-unescape-data (data)
136   (let ((index 0))
137     (while (string-match "%\\([0-9A-F][0-9A-F]\\)" data index)
138       (setq data (replace-match
139                   (read (concat "\"\\x" (match-string 1 data) "\""))
140                   nil nil data)
141             index (- (match-end 0) 2)))
142     data))
143
144 (defun riece-ruby-reset-process-buffer ()
145   (with-current-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   (with-current-buffer (process-buffer process)
183     (goto-char (point-max))
184     (insert input)
185     (goto-char (point-min))
186     (beginning-of-line)
187     (while (looking-at ".*\r\n")
188       (if (looking-at "OK\\( \\(.*\\)\\)?\r")
189           (progn
190             (if riece-ruby-escaped-data
191                 (setq riece-ruby-data (mapconcat #'riece-ruby-unescape-data
192                                                  riece-ruby-escaped-data "")))
193             (setq riece-ruby-escaped-data nil
194                   riece-ruby-response (list 'OK (match-string 2))
195                   riece-ruby-lock nil))
196         (if (looking-at "ERR \\([0-9]+\\)\\( \\(.*\\)\\)?\r")
197             (progn
198               (setq riece-ruby-escaped-data nil
199                     riece-ruby-response
200                     (list 'ERR (string-to-number (match-string 1))
201                           (match-string 3))
202                     riece-ruby-lock nil))
203           (if (looking-at "D \\(.*\\)\r")
204               (setq riece-ruby-escaped-data (cons (match-string 1)
205                                                   riece-ruby-escaped-data))
206             (if (looking-at "S \\([^ ]*\\) \\(.*\\)\r")
207                 (progn
208                   (setq riece-ruby-status-alist (cons (cons (match-string 1)
209                                                             (match-string 2))
210                                                       riece-ruby-status-alist))
211                   (if (member (car (car riece-ruby-status-alist))
212                               '("finished" "exited"))
213                       (riece-ruby-run-exit-handler
214                        (cdr (car riece-ruby-status-alist)))))
215               (if (looking-at "# output \\([^ ]*\\) \\(.*\\)\r")
216                   (riece-ruby-run-output-handler (match-string 1)
217                                                  (match-string 2)
218                                                  (current-time))
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 (if (symbolp (cdr entry))
230                                        (symbol-name (cdr entry))
231                                      (format "%s-exit-handler" name))
232                                    (cdr entry) (car entry))
233       (riece-ruby-clear name))))
234
235 (defun riece-ruby-run-output-handler (name output time)
236   (let ((handler-entry (assoc name riece-ruby-output-handler-alist))
237         (entry (assoc name riece-ruby-output-queue-alist)))
238     (if handler-entry
239         (riece-funcall-ignore-errors (if (symbolp (cdr handler-entry))
240                                          (symbol-name (cdr handler-entry))
241                                        (format "%s-output-handler" name))
242                                      (cdr handler-entry) name output time)
243       (if entry
244           (setcdr entry (cons (cons output time) (cdr entry)))
245         (setq riece-ruby-output-queue-alist
246               (cons (list name (cons output time))
247                     riece-ruby-output-queue-alist))))))
248
249 (defun riece-ruby-sentinel (process status)
250   (kill-buffer (process-buffer process)))
251
252 (defun riece-ruby-execute (program)
253   "Schedule an execution of a Ruby PROGRAM.
254 Return a string name assigned by the server."
255   (unless (and riece-ruby-process
256                (eq (process-status riece-ruby-process) 'run))
257     (let (selective-display
258           (coding-system-for-write 'binary)
259           (coding-system-for-read 'binary))
260       (setq riece-ruby-process
261             (apply #'start-process "riece-ruby" (generate-new-buffer " *Ruby*")
262                    riece-ruby-command
263                    (expand-file-name riece-ruby-server-program
264                                      riece-data-directory)
265                    riece-ruby-server-program-arguments))
266       (riece-set-process-query-on-exit-flag riece-ruby-process nil)
267       (set-process-filter riece-ruby-process #'riece-ruby-filter)
268       (set-process-sentinel riece-ruby-process #'riece-ruby-sentinel)))
269   (with-current-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   (with-current-buffer (process-buffer riece-ruby-process)
288     (riece-ruby-reset-process-buffer)
289     (make-local-variable 'riece-ruby-lock)
290     (setq riece-ruby-lock t)
291     (riece-ruby-send-poll name)
292     (while riece-ruby-lock
293       (accept-process-output riece-ruby-process))
294     (list riece-ruby-response
295           riece-ruby-data
296           riece-ruby-status-alist)))
297
298 (defun riece-ruby-clear (name)
299   "Clear a result of program execution distinguished by NAME.
300 Note that riece-ruby-clear is automatically called iff an exit-handler
301 is specified.  Otherwise, it should be called explicitly."
302   (with-current-buffer (process-buffer riece-ruby-process)
303     (riece-ruby-reset-process-buffer)
304     (make-local-variable 'riece-ruby-lock)
305     (setq riece-ruby-lock t)
306     (riece-ruby-send-exit name)
307     (while riece-ruby-lock
308       (accept-process-output riece-ruby-process)))
309   (let ((entry (assoc name riece-ruby-property-alist)))
310     (if entry
311         (delq entry riece-ruby-property-alist))))
312
313 (defun riece-ruby-set-exit-handler (name handler)
314   "Set an exit-handler HANDLER for the program distinguished by NAME.
315 An exit-handler is called when the program is finished or exited abnormally.
316 An exit-handler is called with an argument same as NAME.
317 Note that riece-ruby-clear is automatically called iff an exit-handler
318 is specified.  Otherwise, it should be called explicitly."
319   (let ((entry (assoc name riece-ruby-exit-handler-alist)))
320     (if handler
321         (progn
322           (if entry
323               (setcdr entry handler)
324             (setq riece-ruby-exit-handler-alist
325                   (cons (cons name handler)
326                         riece-ruby-exit-handler-alist)))
327           ;;check if the program already exited
328           (riece-ruby-inspect name))
329       (if entry
330           (setq riece-ruby-exit-handler-alist
331                 (delq entry riece-ruby-exit-handler-alist))))))
332
333 (defun riece-ruby-set-output-handler (name handler)
334   "Set an output-handler HANDLER for the program distinguished by NAME.
335 An output-handler is called when the program sends any output by using
336 `output' method in the Ruby program.
337 An output-handler is called with three argument.  The first argument
338 is the same as NAME.  The second argument is the output string.  The
339 third argument is the timestamp of the output event."
340   (let ((entry (assoc name riece-ruby-output-handler-alist))
341         queue-entry pointer)
342     (if handler
343         (progn
344           (when (setq queue-entry (assoc name riece-ruby-output-queue-alist))
345             (setq pointer (nreverse (cdr queue-entry))
346                   riece-ruby-output-queue-alist
347                   (delq queue-entry riece-ruby-output-queue-alist))
348             (while pointer
349               (riece-funcall-ignore-errors (if (symbolp handler)
350                                                (symbol-name handler)
351                                              (format "%s-output-handler" name))
352                                            handler name (car (car pointer))
353                                            (cdr (car pointer)))
354               (setq pointer (cdr pointer))))
355           (if entry
356               (setcdr entry handler)
357             (setq riece-ruby-output-handler-alist
358                   (cons (cons name handler)
359                         riece-ruby-output-handler-alist))))
360       (if entry
361           (setq riece-ruby-output-handler-alist
362                 (delq entry riece-ruby-output-handler-alist))))))
363
364 (defun riece-ruby-set-property (name property value)
365   "Set given PROPERTY/VALUE pair to the program distinguished by NAME."
366   (let ((entry (assoc name riece-ruby-property-alist))
367         property-entry)
368     (unless entry
369       (setq entry (list name)
370             riece-ruby-property-alist (cons entry riece-ruby-property-alist)))
371     (if (setq property-entry (assoc property (cdr entry)))
372         (setcdr property-entry value)
373       (setcdr entry (cons (cons property value) (cdr entry))))))
374
375 (defun riece-ruby-property (name property)
376   "Return the value of PROPERTY set to the program distinguished by NAME."
377   (cdr (assoc property (cdr (assoc name riece-ruby-property-alist)))))
378
379 (defun riece-ruby-substitute-variables (program alist)
380   "Substitute symbols in PROGRAM by looking up ALIST.
381 Return a string concatenating elements in PROGRAM."
382   (setq program (copy-sequence program))
383   (while alist
384     (let ((pointer program))
385       (while pointer
386         (setq pointer (memq (car (car alist)) program))
387         (if pointer
388             (setcar pointer (cdr (car alist))))))
389     (setq alist (cdr alist)))
390   (apply #'concat program))
391
392 (provide 'riece-ruby)
393
394 ;;; riece-ruby.el ends here