Christophe Weblog Wiki Code Publications Music
log and fix bug #20: infinite errors on disconnect.
[swankr.git] / swank.R
1 ### This program is free software; you can redistribute it and/or
2 ### modify it under the terms of the GNU General Public Licence as
3 ### published by the Free Software Foundation; either version 2 of the
4 ### Licence, or (at your option) any later version.
5 ###
6 ### This program is distributed in the hope that it will be useful,
7 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
8 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 ### GNU General Public Licence for more details.
10 ###
11 ### A copy of version 2 of the GNU General Public Licence is available
12 ### at <http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt>; the
13 ### latest version of the GNU General Public Licence is available at
14 ### <http://www.gnu.org/licenses/gpl.txt>.
15
16 ### KLUDGE: this assumes that we're being sourced with chdir=TRUE.
17 ### (If not, `swank:swank-require` will work under the circumstances
18 ### that it used to work anyway -- i.e. the working directory is the
19 ### swankr directory)
20 swankrPath <- getwd() 
21
22 swank <- function(port=4005) {
23   acceptConnections(port, FALSE)
24 }
25
26 startSwank <- function(portFile) {
27   acceptConnections(4005, portFile)
28 }
29
30 acceptConnections <- function(port, portFile) {
31   if(portFile != FALSE) {
32     f <- file(portFile, open="w+")
33     cat(port, file=f)
34     close(f)
35   }
36   ## FIXME: maybe we should support dontClose here?
37   s <- socketConnection(host="localhost", server=TRUE, port=port, open="r+b")
38   on.exit(close(s))
39   tryCatch(serve(s), endOfFile=function(c) NULL)
40 }
41
42 serve <- function(io) {
43   mainLoop(io)
44 }
45
46 mainLoop <- function(io) {
47   slimeConnection <- new.env()
48   slimeConnection$io <- io
49   while(TRUE) {
50     withRestarts(tryCatch(dispatch(slimeConnection, readPacket(io)),
51                           swankTopLevel=function(c) NULL),
52                  abort="return to SLIME's toplevel")
53   }
54 }
55
56 dispatch <- function(slimeConnection, event, sldbState=NULL) {
57   kind <- event[[1]]
58   if(kind == quote(`:emacs-rex`)) {
59     do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
60   }
61 }
62
63 sendToEmacs <- function(slimeConnection, obj) {
64   io <- slimeConnection$io
65   payload <- writeSexpToString(obj)
66   writeChar(sprintf("%06x", nchar(payload, type="bytes")), io, eos=NULL)
67   writeChar(payload, io, eos=NULL)
68   flush(io)
69 }
70
71 callify <- function(form) {
72   ## we implement here the conversion from Lisp S-expression (or list)
73   ## expressions of code into our own, swankr, calling convention,
74   ## with slimeConnection and sldbState as first and second arguments.
75   ## as.call() gets us part of the way, but we need to walk the list
76   ## recursively to mimic CL:EVAL; we need to avoid converting R
77   ## special operators which we are punning (only `quote`, for now)
78   ## into this calling convention.
79   if(is.list(form)) {
80     if(form[[1]] == quote(quote)) {
81       as.call(form)
82     } else {
83       as.call(c(list(form[[1]], quote(slimeConnection), quote(sldbState)), lapply(form[-1], callify)))
84     }
85   } else {
86     form
87   }
88 }
89
90 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
91   ok <- FALSE
92   value <- NULL
93   conn <- textConnection(NULL, open="w")
94   condition <- NULL
95   tryCatch({
96     withCallingHandlers({
97       call <- callify(form)
98       capture.output(value <- eval(call), file=conn)
99       string <- paste(textConnectionValue(conn), sep="", collapse="\n")
100       if(nchar(string) > 0) {
101         sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
102         sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
103       }
104       close(conn)
105       ok <- TRUE
106     }, error=function(c) {
107       condition <<- c
108       string <- paste(textConnectionValue(conn), sep="", collapse="\n")
109       if(nchar(string) > 0) {
110         sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
111         sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
112       }
113       close(conn)
114       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
115       withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
116     finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
117 }
118
119 makeSldbState <- function(condition, level, id) {
120   calls <- rev(sys.calls())[-1]
121   frames <- rev(sys.frames())[-1]
122   restarts <- rev(computeRestarts(condition))[-1]
123   ret <- list(condition=condition, level=level, id=id, restarts=restarts, calls=calls, frames=frames)
124   class(ret) <- c("sldbState", class(ret))
125   ret
126 }
127
128 sldbLoop <- function(slimeConnection, sldbState, id) {
129   tryCatch({
130     io <- slimeConnection$io
131     sendToEmacs(slimeConnection, c(list(quote(`:debug`), id, sldbState$level), `swank:debugger-info-for-emacs`(slimeConnection, sldbState)))
132     sendToEmacs(slimeConnection, list(quote(`:debug-activate`), id, sldbState$level, FALSE))
133     while(TRUE) {
134       dispatch(slimeConnection, readPacket(io), sldbState)
135     }
136   }, finally=sendToEmacs(slimeConnection, c(list(quote(`:debug-return`), id, sldbState$level, FALSE))))
137 }
138
139 readPacket <- function(io) {
140   socketSelect(list(io))
141   header <- readChunk(io, 6)
142   len <- strtoi(header, base=16)
143   payload <- readChunk(io, len)
144   readSexpFromString(payload)
145 }
146
147 readChunk <- function(io, len) {
148   buffer <- readChar(io, len)
149   if(length(buffer) == 0) {
150     condition <- simpleCondition("End of file on io")
151     class(condition) <- c("endOfFile", class(condition))
152     signalCondition(condition)
153   }
154   if(nchar(buffer) != len) {
155     stop("short read in readChunk")
156   }
157   buffer
158 }
159
160 readSexpFromString <- function(string) {
161   pos <- 1
162   read <- function() {
163     skipWhitespace()
164     char <- substr(string, pos, pos)
165     switch(char,
166            "("=readList(),
167            "\""=readString(),
168            "'"=readQuote(),
169            {
170              if(pos > nchar(string))
171                stop("EOF during read")
172              obj <- readNumberOrSymbol()
173              if(obj == quote(`.`)) {
174                stop("Consing dot not implemented")
175              }
176              obj
177            })
178   }
179   skipWhitespace <- function() {
180     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
181       pos <<- pos + 1
182     }
183   }
184   readList <- function() {
185     ret <- list()
186     pos <<- pos + 1
187     while(TRUE) {
188       skipWhitespace()
189       char <- substr(string, pos, pos)
190       if(char == ")") {
191         pos <<- pos + 1
192         break
193       } else {
194         obj <- read()
195         if(length(obj) == 1 && obj == quote(`.`)) {
196           stop("Consing dot not implemented")
197         }
198         ret <- c(ret, list(obj))
199       }
200     }
201     ret
202   }
203   readString <- function() {
204     ret <- ""
205     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
206     while(TRUE) {
207       pos <<- pos + 1
208       char <- substr(string, pos, pos)
209       switch(char,
210              "\""={ pos <<- pos + 1; break },
211              "\\"={ pos <<- pos + 1
212                     char2 <- substr(string, pos, pos)
213                     switch(char2,
214                            "\""=addChar(char2),
215                            "\\"=addChar(char2),
216                            stop("Unrecognized escape character")) },
217              addChar(char))
218     }
219     ret
220   }
221   readNumberOrSymbol <- function() {
222     token <- readToken()
223     if(nchar(token)==0) {
224       stop("End of file reading token")
225     } else if(grepl("^[0-9]+$", token)) {
226       strtoi(token)
227     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
228       as.double(token)
229     } else {
230       name <- as.name(token)
231       if(name == quote(t)) {
232         TRUE
233       } else if(name == quote(nil)) {
234         FALSE
235       } else {
236         name
237       }
238     }
239   }
240   readToken <- function() {
241     token <- ""
242     while(TRUE) {
243       char <- substr(string, pos, pos)
244       if(char == "") {
245         break;
246       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
247         break;
248       } else {
249         token <- paste(token, char, sep="")
250         pos <<- pos + 1
251       }
252     }
253     token
254   }
255   read()
256 }
257
258 writeSexpToString <- function(obj) {
259   writeSexpToStringLoop <- function(obj) {
260     switch(typeof(obj),
261            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
262            "list"={ string <- paste(string, "(", sep="")
263                     max <- length(obj)
264                     if(max > 0) {
265                       for(i in 1:max) {
266                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
267                         if(i != max) {
268                           string <- paste(string, " ", sep="")
269                         }
270                       }
271                     }
272                     string <- paste(string, ")", sep="") },
273            "symbol"={ string <- paste(string, as.character(obj), sep="") },
274            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
275            "double"={ string <- paste(string, as.character(obj), sep="") },
276            "integer"={ string <- paste(string, as.character(obj), sep="") },
277            stop(paste("can't write object ", obj, sep="")))
278     string
279   }
280   string <- ""
281   writeSexpToStringLoop(obj)
282 }
283
284 prin1ToString <- function(val) {
285   paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
286         sep="", collapse="\n")
287 }
288
289 printToString <- function(val) {
290   paste(capture.output(print(val)), sep="", collapse="\n")
291 }
292
293 `swank:connection-info` <- function (slimeConnection, sldbState) {
294   list(quote(`:pid`), Sys.getpid(),
295        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
296        quote(`:encoding`), list(quote(`:coding-systems`), list("utf-8-unix")),
297        quote(`:lisp-implementation`), list(quote(`:type`), "R",
298                                            quote(`:name`), "R",
299                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
300 }
301
302 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
303   for(contrib in contribs) {
304     filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
305     if(file.exists(filename)) {
306       source(filename)
307     }
308   }
309   list()
310 }
311
312 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
313   list("R", "R")
314 }
315
316 makeReplResult <- function(value) {
317   string <- printToString(value)
318   list(quote(`:write-string`), string,
319        quote(`:repl-result`))
320 }
321
322 makeReplResultFunction <- makeReplResult
323
324 sendReplResult <- function(slimeConnection, value) {
325   result <- makeReplResultFunction(value)
326   sendToEmacs(slimeConnection, result)
327 }
328
329 sendReplResultFunction <- sendReplResult
330
331 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
332   ## O how ugly
333   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
334   for(expr in parse(text=string)) {
335     expr <- expr
336     ## O maybe this is even uglier
337     lookedup <- do.call("bquote", list(expr))
338     tmp <- withVisible(eval(lookedup, envir = globalenv()))
339     if(tmp$visible) {
340       sendReplResultFunction(slimeConnection, tmp$value)
341     }
342   }
343   list()
344 }
345
346 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
347   "No Arglist Information"
348 }
349
350 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
351   list()
352 }
353
354 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
355   condition <- simpleCondition("Throw to toplevel")
356   class(condition) <- c("swankTopLevel", class(condition))
357   signalCondition(condition)
358 }
359
360 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
361   calls <- sldbState$calls
362   if(is.null(to)) to <- length(calls)
363   from <- from+1
364   calls <- lapply(calls[from:to],
365                   { frameNumber <- from-1;
366                     function (x) {
367                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
368                       frameNumber <<- 1+frameNumber
369                       ret
370                     }
371                   })
372 }
373
374 computeRestartsForEmacs <- function (sldbState) {
375   lapply(sldbState$restarts,
376          function(x) {
377            ## this is all a little bit internalsy
378            restartName <- x[[1]][[1]]
379            description <- restartDescription(x)
380            list(restartName, if(is.null(description)) restartName else description)
381          })
382 }
383
384 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
385   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
386        computeRestartsForEmacs(sldbState),
387        `swank:backtrace`(slimeConnection, sldbState, from, to),
388        list(sldbState$id))
389 }
390
391 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
392   if(sldbState$level == level) {
393     invokeRestart(sldbState$restarts[[n+1]])
394   }
395 }
396
397 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
398   call <- sldbState$calls[[n+1]]
399   srcref <- attr(call, "srcref")
400   srcfile <- attr(srcref, "srcfile")
401   if(is.null(srcfile)) {
402     list(quote(`:error`), "no srcfile")
403   } else {
404     filename <- get("filename", srcfile)
405     ## KLUDGE: what this means is "is the srcfile filename
406     ## absolute?"
407     if(substr(filename, 1, 1) == "/") {
408       file <- filename
409     } else {
410       file <- sprintf("%s/%s", srcfile$wd, filename)
411     }
412     list(quote(`:location`),
413          list(quote(`:file`), file),
414          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
415          FALSE)
416   }
417 }
418
419 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
420   FALSE
421 }
422
423 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
424   frame <- sldbState$frames[[1+index]]
425   withRetryRestart("retry SLIME interactive evaluation request",
426                    value <- eval(parse(text=string), envir=frame))
427   printToString(value)
428 }
429
430 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
431   frame <- sldbState$frames[[1+index]]
432   objs <- ls(envir=frame)
433   if(identical(frame, globalenv())) {
434     objs <- c()
435   }
436   list(lapply(objs, function(name) { list(quote(`:name`), name,
437                                           quote(`:id`), 0,
438                                           quote(`:value`),
439                                           tryCatch({
440                                             printToString(eval(parse(text=name), envir=frame))
441                                           }, error=function(c) {
442                                             sprintf("error printing object")
443                                           }))}),
444        list())
445 }
446
447 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
448   literal2rx <- function(string) {
449     ## list of ERE metacharacters from ?regexp
450     gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
451   }
452   matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
453   nmatches <- length(matches)
454   if(nmatches == 0) {
455     list(list(), "")
456   } else {
457     longest <- matches[order(nchar(matches))][1]
458     while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
459       longest <- substr(longest, 1, nchar(longest)-1)
460     }
461     list(as.list(matches), longest)
462   }
463 }
464
465 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
466   lineOffset <- charOffset <- colOffset <- NULL
467   for(pos in position) {
468     switch(as.character(pos[[1]]),
469            `:position` = {charOffset <- pos[[2]]},
470            `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
471            warning("unknown content in pos", pos))
472   }
473   frob <- function(refs) {
474     lapply(refs,
475            function(x)
476            srcref(attr(x,"srcfile"),
477                   c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
478                     x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
479                     ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
480                     ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
481   }
482   transformSrcrefs <- function(s) {
483     srcrefs <- attr(s, "srcref")
484     attribs <- attributes(s)
485     new <- 
486       switch(mode(s),
487              "call"=as.call(lapply(s, transformSrcrefs)),
488              "expression"=as.expression(lapply(s, transformSrcrefs)),
489              s)
490     attributes(new) <- attribs
491     if(!is.null(attr(s, "srcref"))) {
492       attr(new, "srcref") <- frob(srcrefs)
493     }
494     new
495   }
496   withRestarts({
497     times <- system.time({
498       exprs <- parse(text=string, srcfile=srcfile(filename))
499       eval(transformSrcrefs(exprs), envir = globalenv()) })},
500                abort="abort compilation")
501   list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
502 }
503
504 withRetryRestart <- function(description, expr) {
505   call <- substitute(expr)
506   retry <- TRUE
507   while(retry) {
508     retry <- FALSE
509     withRestarts(eval.parent(call),
510                  retry=list(description=description,
511                    handler=function() retry <<- TRUE))
512   }
513 }
514
515 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
516   withRetryRestart("retry SLIME interactive evaluation request",
517                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
518   if(tmp$visible) {
519     prin1ToString(tmp$value)
520   } else {
521     "# invisible value"
522   }
523 }
524
525 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
526   withRetryRestart("retry SLIME interactive evaluation request",
527                    { output <-
528                        capture.output(tmp <- withVisible(eval(parse(text=string),
529                                                               envir=globalenv()))) })
530   output <- paste(output, sep="", collapse="\n")
531   if(tmp$visible) {
532     list(output, prin1ToString(tmp$value))
533   } else {
534     list(output, "# invisible value")
535   }
536 }
537
538 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
539   withRetryRestart("retry SLIME interactive evaluation request",
540                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
541   if(tmp$visible) {
542     prin1ToString(tmp$value)
543   } else {
544     "# invisible value"
545   }
546 }
547
548 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
549   if(exists(string, envir = globalenv())) {
550     thing <- get(string, envir = globalenv())
551     if(inherits(thing, "function")) {
552       body <- body(thing)
553       srcref <- attr(body, "srcref")
554       srcfile <- attr(body, "srcfile")
555       if(is.null(srcfile)) {
556         list()
557       } else {
558         filename <- get("filename", srcfile)
559         ## KLUDGE: what this means is "is the srcfile filename
560         ## absolute?"
561         if(substr(filename, 1, 1) == "/") {
562           file <- filename
563         } else {
564           file <- sprintf("%s/%s", srcfile$wd, filename)
565         }
566         list(list(sprintf("function %s", string),
567                   list(quote(`:location`),
568                        list(quote(`:file`), file),
569                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
570                        list())))
571       }
572     } else {
573       list()
574     }
575   } else {
576     list()
577   }
578 }
579
580 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
581   paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
582         collapse="\n", sep="")
583 }
584
585 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
586   eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
587   TRUE
588 }
589
590 resetInspector <- function(slimeConnection) {
591   assign("istate", list(), envir=slimeConnection)
592   assign("inspectorHistory", NULL, envir=slimeConnection)
593 }
594
595 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
596   withRetryRestart("retry SLIME inspection request",
597                    { resetInspector(slimeConnection)
598                      value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
599                    })
600   value
601 }
602
603 inspectObject <- function(slimeConnection, object) {
604   previous <- slimeConnection$istate
605   slimeConnection$istate <- new.env()
606   slimeConnection$istate$object <- object
607   slimeConnection$istate$previous <- previous
608   slimeConnection$istate$content <- emacsInspect(object)
609   if(!(object %in% slimeConnection$inspectorHistory)) {
610     slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
611   }
612   if(!is.null(slimeConnection$istate$previous)) {
613     slimeConnection$istate$previous$`next` <- slimeConnection$istate
614   }
615   istateToElisp(slimeConnection$istate)
616 }
617
618 valuePart <- function(istate, object, string) {
619   list(quote(`:value`),
620        if(is.null(string)) printToString(object) else string,
621        assignIndexInParts(object, istate))
622 }
623
624 preparePart <- function(istate, part) {
625   if(is.character(part)) {
626     list(part)
627   } else {
628     switch(as.character(part[[1]]),
629            `:newline` = list("\n"),
630            `:value` = valuePart(istate, part[[2]], part[[3]]),
631            `:line` = list(printToString(part[[2]]), ": ",
632              valuePart(istate, part[[3]], NULL), "\n"))
633   }
634 }
635
636 prepareRange <- function(istate, start, end) {
637   range <- istate$content[start+1:min(end+1, length(istate$content))]
638   ps <- NULL
639   for(part in range) {
640     ps <- c(ps, preparePart(istate, part))
641   }
642   list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
643        start, end)
644 }
645
646 assignIndexInParts <- function(object, istate) {
647   ret <- 1+length(istate$parts)
648   istate$parts <- c(istate$parts, list(object))
649   ret
650 }
651
652 istateToElisp <- function(istate) {
653   list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
654        quote(`:id`), assignIndexInParts(istate$object, istate),
655        quote(`:content`), prepareRange(istate, 0, 500))
656 }
657
658 emacsInspect <- function(object) {
659   UseMethod("emacsInspect")
660 }
661
662 emacsInspect.default <- function(thing) {
663   c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
664 }
665
666 emacsInspect.list <- function(list) {
667   c(list("a list", list(quote(`:newline`))),
668     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
669            names(list), list))
670 }
671
672 emacsInspect.numeric <- function(numeric) {
673   c(list("a numeric", list(quote(`:newline`))),
674     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
675            (1:length(numeric)), numeric))
676 }
677
678 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
679   resetInspector(slimeConnection)
680   FALSE
681 }
682
683 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
684   slimeConnection$istate$parts[[index]]
685 }
686
687 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
688   object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
689   inspectObject(slimeConnection, object)
690 }
691
692 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
693   if(!is.null(slimeConnection$istate$previous)) {
694     slimeConnection$istate <- slimeConnection$istate$previous
695     istateToElisp(slimeConnection$istate)
696   } else {
697     FALSE
698   }
699 }
700
701 `swank:inspector-next` <- function(slimeConnection, sldbState) {
702   if(!is.null(slimeConnection$istate$`next`)) {
703     slimeConnection$istate <- slimeConnection$istate$`next`
704     istateToElisp(slimeConnection$istate)
705   } else {
706     FALSE
707   }
708 }
709
710 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
711   expr <- parse(text=string)[[1]]
712   object <- slimeConnection$istate$object
713   if(inherits(object, "list")|inherits(object, "environment")) {
714     substituted <- substituteDirect(expr, object)
715     eval(substituted, envir=globalenv())
716   } else {
717     eval(expr, envir=globalenv())
718   }
719 }
720
721 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
722   resetInspector(slimeConnection)
723   inspectObject(slimeConnection, sldbState$condition)
724 }
725
726 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
727   resetInspector(slimeConnection)
728   frame <- sldbState$frames[[1+frame]]
729   name <- ls(envir=frame)[[1+var]]
730   object <- get(name, envir=frame)
731   inspectObject(slimeConnection, object)
732 }
733
734 `swank:default-directory` <- function(slimeConnection, sldbState) {
735   getwd()
736 }
737
738 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
739   setwd(directory)
740   `swank:default-directory`(slimeConnection, sldbState)
741 }
742
743 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
744   source(filename, local=FALSE, keep.source=TRUE)
745   TRUE
746 }
747
748 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
749   times <- system.time(parse(filename, srcfile=srcfile(filename)))
750   if(loadp) {
751     ## KLUDGE: inelegant, but works.  It might be more in the spirit
752     ## of things to keep the result of the parse above around to
753     ## evaluate.
754     `swank:load-file`(slimeConnection, sldbState, filename)
755   }
756   list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
757 }
758
759 `swank:quit-lisp` <- function(slimeConnection, sldbState) {
760   quit()
761 }