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