Christophe Weblog Wiki Code Publications Music
Rename README to README.org
[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   sexp <- readSexpFromString(payload)
145   sexp
146 }
147
148 readChunk <- function(io, len) {
149   buffer <- readChar(io, len, useBytes=TRUE)
150   if(length(buffer) == 0) {
151     condition <- simpleCondition("End of file on io")
152     class(condition) <- c("endOfFile", class(condition))
153     signalCondition(condition)
154   }
155   ## FIXME: with the useBytes argument to readChar, it is normal for
156   ## the buffer returned to be fewer character than bytes were read,
157   ## given the possibility of multibyte characters.  However, that
158   ## means we can’t detect at all the case where there is actually a
159   ## short read (though empirically the readChar call blocks rather
160   ## than returning early).
161   ##
162   ## if(nchar(buffer) != len) {
163   ##   stop("short read in readChunk")
164   ## }
165   buffer
166 }
167
168 readSexpFromString <- function(string) {
169   pos <- 1
170   read <- function() {
171     skipWhitespace()
172     char <- substr(string, pos, pos)
173     switch(char,
174            "("=readList(),
175            "\""=readString(),
176            "'"=readQuote(),
177            {
178              if(pos > nchar(string))
179                stop("EOF during read")
180              obj <- readNumberOrSymbol()
181              if(obj == quote(`.`)) {
182                stop("Consing dot not implemented")
183              }
184              obj
185            })
186   }
187   skipWhitespace <- function() {
188     while(substr(string, pos, pos) %in% c(" ", "\t", "\n")) {
189       pos <<- pos + 1
190     }
191   }
192   readList <- function() {
193     ret <- list()
194     pos <<- pos + 1
195     while(TRUE) {
196       skipWhitespace()
197       char <- substr(string, pos, pos)
198       if(char == ")") {
199         pos <<- pos + 1
200         break
201       } else {
202         obj <- read()
203         if(length(obj) == 1 && obj == quote(`.`)) {
204           stop("Consing dot not implemented")
205         }
206         ret <- c(ret, list(obj))
207       }
208     }
209     ret
210   }
211   readString <- function() {
212     ret <- ""
213     addChar <- function(c) { ret <<- paste(ret, c, sep="") }
214     while(TRUE) {
215       pos <<- pos + 1
216       char <- substr(string, pos, pos)
217       switch(char,
218              "\""={ pos <<- pos + 1; break },
219              "\\"={ pos <<- pos + 1
220                     char2 <- substr(string, pos, pos)
221                     switch(char2,
222                            "\""=addChar(char2),
223                            "\\"=addChar(char2),
224                            stop("Unrecognized escape character")) },
225              addChar(char))
226     }
227     ret
228   }
229   readNumberOrSymbol <- function() {
230     token <- readToken()
231     if(nchar(token)==0) {
232       stop("End of file reading token")
233     } else if(grepl("^[0-9]+$", token)) {
234       strtoi(token)
235     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
236       as.double(token)
237     } else {
238       name <- as.name(token)
239       if(name == quote(t)) {
240         TRUE
241       } else if(name == quote(nil)) {
242         FALSE
243       } else {
244         name
245       }
246     }
247   }
248   readToken <- function() {
249     token <- ""
250     while(TRUE) {
251       char <- substr(string, pos, pos)
252       if(char == "") {
253         break;
254       } else if(char %in% c(" ", "\n", "\t", "(", ")", "\"", "'")) {
255         break;
256       } else {
257         token <- paste(token, char, sep="")
258         pos <<- pos + 1
259       }
260     }
261     token
262   }
263   read()
264 }
265
266 writeSexpToString <- function(obj) {
267   writeSexpToStringLoop <- function(obj) {
268     switch(typeof(obj),
269            "character"={ string <- paste(string, "\"", gsub("([\"\\])", "\\\\\\1", obj), "\"", sep="") },
270            "list"={ string <- paste(string, "(", sep="")
271                     max <- length(obj)
272                     if(max > 0) {
273                       for(i in 1:max) {
274                         string <- paste(string, writeSexpToString(obj[[i]]), sep="")
275                         if(i != max) {
276                           string <- paste(string, " ", sep="")
277                         }
278                       }
279                     }
280                     string <- paste(string, ")", sep="") },
281            "symbol"={ string <- paste(string, as.character(obj), sep="") },
282            "logical"={ string <- if(obj) { paste(string, "t", sep="") } else { paste(string, "nil", sep="") }},
283            "double"={ string <- paste(string, as.character(obj), sep="") },
284            "integer"={ string <- paste(string, as.character(obj), sep="") },
285            stop(paste("can't write object ", obj, sep="")))
286     string
287   }
288   string <- ""
289   writeSexpToStringLoop(obj)
290 }
291
292 prin1ToString <- function(val) {
293   paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
294         sep="", collapse="\n")
295 }
296
297 printToString <- function(val) {
298   paste(capture.output(print(val)), sep="", collapse="\n")
299 }
300
301 `swank:connection-info` <- function (slimeConnection, sldbState) {
302   list(quote(`:pid`), Sys.getpid(),
303        quote(`:package`), list(quote(`:name`), "R", quote(`:prompt`), "R> "),
304        quote(`:version`), "2014-09-13",
305        quote(`:encoding`), list(quote(`:coding-systems`), list("utf-8-unix")),
306        quote(`:lisp-implementation`), list(quote(`:type`), "R",
307                                            quote(`:name`), "R",
308                                            quote(`:version`), paste(R.version$major, R.version$minor, sep=".")))
309 }
310
311 `swank:swank-require` <- function (slimeConnection, sldbState, contribs) {
312   for(contrib in contribs) {
313     filename <- sprintf("%s/%s.R", swankrPath, as.character(contrib))
314     if(file.exists(filename)) {
315       source(filename)
316     }
317   }
318   list()
319 }
320
321 `swank:create-repl` <- function(slimeConnection, sldbState, env, ...) {
322   list("R", "R")
323 }
324
325 `swank-repl:create-repl` <- `swank:create-repl`
326
327 makeReplResult <- function(value) {
328   string <- printToString(value)
329   list(quote(`:write-string`), string,
330        quote(`:repl-result`))
331 }
332
333 makeReplResultFunction <- makeReplResult
334
335 sendReplResult <- function(slimeConnection, value) {
336   result <- makeReplResultFunction(value)
337   sendToEmacs(slimeConnection, result)
338 }
339
340 sendReplResultFunction <- sendReplResult
341
342 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
343   ## O how ugly
344   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
345   for(expr in parse(text=string)) {
346     expr <- expr
347     ## O maybe this is even uglier
348     lookedup <- do.call("bquote", list(expr))
349     tmp <- withVisible(eval(lookedup, envir = globalenv()))
350     if(tmp$visible) {
351       sendReplResultFunction(slimeConnection, tmp$value)
352     }
353   }
354   list()
355 }
356
357 `swank-repl:listener-eval` <- `swank:listener-eval`
358
359 `swank:clear-repl-variables` <- function(slimeConnection, sldbState) {
360   list()
361 }
362
363 `swank:autodoc` <- function(slimeConnection, sldbState, rawForm, ...) {
364   list("No Arglist Information", TRUE)
365 }
366
367 `swank:operator-arglist` <- function(slimeConnection, sldbState, op, package) {
368   if(!exists(op, envir = globalenv())) {
369     return(list())
370   }
371   funoid <- get(op, envir = globalenv())
372   if(is.function(funoid)) {
373     args <- formals(funoid)
374     paste(sprintf("%s=%s", names(args), args), collapse=", ")
375   } else {
376     list()
377   }
378 }
379
380 `swank:describe-function` <- function(slimeConnection, sldbState, op, package) {
381   ## FIXME: maybe not the best match?
382   `swank:operator-arglist`(slimeConnection, sldbState, op, package)
383 }
384
385 helpFilesWithTopicString <- function(value) {
386   output <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(value),
387                                           options=list(underline_titles=FALSE)))
388   paste(output, collapse="\n")
389 }
390
391 `swank:describe-symbol` <- function(slimeConnection, sldbState, op, package) {
392   value <- help(op)
393   helpFilesWithTopicString(value)
394 }
395
396 `swank:apropos-list-for-emacs` <- function(slimeConnection, sldbState, name, onlyExternal, package, caseSensitive) {
397   x <- help.search(name, fields="alias", package=.packages())$matches
398   brieflyDescribe <- function(name, title) {
399     if (exists(name, globalenv())) {
400       val <- get(name, globalenv())
401       kind <- if("function" %in% class(val)) quote(`:function`) else quote(`:variable`)
402       list(quote(`:designator`), name, kind, title)
403     } else {
404       ## maybe
405       list(quote(`:designator`), name, quote(`:type`), title)
406     }
407   }
408   mapply(brieflyDescribe, x[,"name"], x[,"title"], SIMPLIFY=FALSE)
409 }
410
411 `swank:describe-definition-for-emacs` <- function(slimeConnection, sldbState, name, kind) {
412   `swank:describe-symbol`(slimeConnection, sldbState, name, NULL)
413 }
414
415 `swank:throw-to-toplevel` <- function(slimeConnection, sldbState) {
416   condition <- simpleCondition("Throw to toplevel")
417   class(condition) <- c("swankTopLevel", class(condition))
418   signalCondition(condition)
419 }
420
421 `swank:backtrace` <- function(slimeConnection, sldbState, from=0, to=NULL) {
422   calls <- sldbState$calls
423   if(is.null(to)) to <- length(calls)
424   from <- from+1
425   calls <- lapply(calls[from:to],
426                   { frameNumber <- from-1;
427                     function (x) {
428                       ret <- list(frameNumber, paste(format(x), sep="", collapse=" "))
429                       frameNumber <<- 1+frameNumber
430                       ret
431                     }
432                   })
433 }
434
435 computeRestartsForEmacs <- function (sldbState) {
436   lapply(sldbState$restarts,
437          function(x) {
438            ## this is all a little bit internalsy
439            restartName <- x[[1]][[1]]
440            description <- restartDescription(x)
441            list(restartName, if(is.null(description)) restartName else description)
442          })
443 }
444
445 `swank:debugger-info-for-emacs` <- function(slimeConnection, sldbState, from=0, to=NULL) {
446   list(list(as.character(sldbState$condition), sprintf("  [%s]", class(sldbState$condition)[[1]]), FALSE),
447        computeRestartsForEmacs(sldbState),
448        `swank:backtrace`(slimeConnection, sldbState, from, to),
449        list(sldbState$id))
450 }
451
452 `swank:invoke-nth-restart-for-emacs` <- function(slimeConnection, sldbState, level, n) {
453   if(sldbState$level == level) {
454     invokeRestart(sldbState$restarts[[n+1]])
455   }
456 }
457
458 `swank:frame-source-location` <- function(slimeConnection, sldbState, n) {
459   call <- sldbState$calls[[n+1]]
460   srcref <- attr(call, "srcref")
461   srcfile <- attr(srcref, "srcfile")
462   if(is.null(srcfile)) {
463     list(quote(`:error`), "no srcfile")
464   } else {
465     filename <- get("filename", srcfile)
466     ## KLUDGE: what this means is "is the srcfile filename
467     ## absolute?"
468     if(substr(filename, 1, 1) == "/") {
469       file <- filename
470     } else {
471       file <- sprintf("%s/%s", srcfile$wd, filename)
472     }
473     list(quote(`:location`),
474          list(quote(`:file`), file),
475          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
476          FALSE)
477   }
478 }
479
480 `swank:buffer-first-change` <- function(slimeConnection, sldbState, filename) {
481   FALSE
482 }
483
484 `swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
485   frame <- sldbState$frames[[1+index]]
486   withRetryRestart("retry SLIME interactive evaluation request",
487                    value <- eval(parse(text=string), envir=frame))
488   printToString(value)
489 }
490
491 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
492   frame <- sldbState$frames[[1+index]]
493   objs <- ls(envir=frame)
494   if(identical(frame, globalenv())) {
495     objs <- c()
496   }
497   list(lapply(objs, function(name) { list(quote(`:name`), name,
498                                           quote(`:id`), 0,
499                                           quote(`:value`),
500                                           tryCatch({
501                                             printToString(eval(parse(text=name), envir=frame))
502                                           }, error=function(c) {
503                                             sprintf("error printing object")
504                                           }))}),
505        list())
506 }
507
508 symbolFieldsCompletion <- function(object, prefix, rest) {
509   ## FIXME: this is hacky, ignoring several syntax issues (use of
510   ## and/or necessity for backquoting identifiers: e.g. fields
511   ## containing hyphens)
512   if((dollar <- regexpr("$", rest, fixed=TRUE)) == -1) {
513     matches <- grep(sprintf("^%s", literal2rx(rest)), names(object), value=TRUE)
514     matches <- sprintf("%s$%s", gsub("\\$[^$]*$", "", prefix), matches)
515     returnMatches(matches)
516   } else {
517     if(exists(substr(rest, 1, dollar-1), object)) {
518       symbolFieldsCompletion(get(substr(rest, 1, dollar-1), object), prefix, substr(rest, dollar+1, nchar(rest)))
519     } else {
520       returnMatches(character(0))
521     }
522   }
523 }
524
525 returnMatches <- function(matches) {
526   nmatches <- length(matches)
527   if(nmatches == 0) {
528     list(list(), "")
529   } else {
530     longest <- matches[order(nchar(matches))][1]
531     while(length(grep(sprintf("^%s", literal2rx(longest)), matches)) < nmatches) {
532       longest <- substr(longest, 1, nchar(longest)-1)
533     }
534     list(as.list(matches), longest)
535   }
536 }
537
538 literal2rx <- function(string) {
539   ## list of ERE metacharacters from ?regexp
540   gsub("([.\\|()[{^$*+?])", "\\\\\\1", string)
541 }
542
543 `swank:simple-completions` <- function(slimeConnection, sldbState, prefix, package) {
544   matches <- apropos(sprintf("^%s", literal2rx(prefix)), ignore.case=FALSE)
545   nmatches <- length(matches)
546   if((nmatches == 0) && ((dollar <- regexpr("$", prefix, fixed=TRUE)) > -1)) {
547     symbolFieldsCompletion(globalenv(), prefix, prefix)
548   } else {
549     returnMatches(matches)
550   }
551 }
552
553 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
554   lineOffset <- charOffset <- colOffset <- NULL
555   for(pos in position) {
556     switch(as.character(pos[[1]]),
557            `:position` = {charOffset <- pos[[2]]},
558            `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
559            warning("unknown content in pos", pos))
560   }
561   frob <- function(refs) {
562     lapply(refs,
563            function(x)
564            srcref(attr(x,"srcfile"),
565                   c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
566                     x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
567                     ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
568                     ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
569   }
570   transformSrcrefs <- function(s) {
571     ## horrendous KLUDGE: we need to short-circuit here for "name"
572     ## objects, rather than having a nice uniform behaviour, because
573     ## for expressions of the form x[y,] there is an empty "name"
574     ## which ends up becoming a `missing' object when passed through
575     ## the switch; why, I do not know, but it is then impossible to
576     ## return it, because returning it attempts to evaluate it and
577     ## evaluating it is an error.  Fortunately it appears that names
578     ## don't have srcrefs attached.
579     if(mode(s) == "name") {
580       return(s)
581     }
582     if(is(s, "srcref")) {
583       ## more monumental KLUDGE: parsing (in 2.14, at least) appears
584       ## to put srcrefs directly in `length 2' objects, which we need
585       ## to frob directly.
586       return(frob(list(s))[[1]])
587     }
588     srcrefs <- attr(s, "srcref")
589     attribs <- attributes(s)
590     new <- 
591       switch(mode(s),
592              "call"=as.call(lapply(s, transformSrcrefs)),
593              "expression"=as.expression(lapply(s, transformSrcrefs)),
594              s)
595     attributes(new) <- attribs
596     if(!is.null(attr(s, "srcref"))) {
597       attr(new, "srcref") <- frob(srcrefs)
598     }
599     if(!is.null(attr(s, "wholeSrcref"))) {
600       attr(new, "wholeSrcref") <- frob(list(attr(s, "wholeSrcref")))[[1]]
601     }
602     new
603   }
604   withRestarts({
605     times <- system.time({
606       exprs <- parse(text=string, srcfile=srcfile(filename))
607       eval(transformSrcrefs(exprs), envir = globalenv()) })},
608                abort="abort compilation")
609   list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
610 }
611
612 withRetryRestart <- function(description, expr) {
613   call <- substitute(expr)
614   retry <- TRUE
615   while(retry) {
616     retry <- FALSE
617     withRestarts(eval.parent(call),
618                  retry=list(description=description,
619                    handler=function() retry <<- TRUE))
620   }
621 }
622
623 `swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
624   withRetryRestart("retry SLIME interactive evaluation request",
625                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
626   if(tmp$visible) {
627     prin1ToString(tmp$value)
628   } else {
629     "# invisible value"
630   }
631 }
632
633 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
634   withRetryRestart("retry SLIME interactive evaluation request",
635                    { output <-
636                        capture.output(tmp <- withVisible(eval(parse(text=string),
637                                                               envir=globalenv()))) })
638   output <- paste(output, sep="", collapse="\n")
639   if(tmp$visible) {
640     list(output, prin1ToString(tmp$value))
641   } else {
642     list(output, "# invisible value")
643   }
644 }
645
646 `swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
647   withRetryRestart("retry SLIME interactive evaluation request",
648                    tmp <- withVisible(eval(parse(text=string), envir=globalenv())))
649   if(tmp$visible) {
650     prin1ToString(tmp$value)
651   } else {
652     "# invisible value"
653   }
654 }
655
656 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
657   if(exists(string, envir = globalenv())) {
658     thing <- get(string, envir = globalenv())
659     if(inherits(thing, "function")) {
660       body <- body(thing)
661       srcref <- attr(body, "srcref")
662       srcfile <- attr(body, "srcfile")
663       if(is.null(srcfile)) {
664         list()
665       } else {
666         filename <- get("filename", srcfile)
667         ## KLUDGE: what this means is "is the srcfile filename
668         ## absolute?"
669         if(substr(filename, 1, 1) == "/") {
670           file <- filename
671         } else {
672           file <- sprintf("%s/%s", srcfile$wd, filename)
673         }
674         list(list(sprintf("function %s", string),
675                   list(quote(`:location`),
676                        list(quote(`:file`), file),
677                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
678                        list())))
679       }
680     } else {
681       list()
682     }
683   } else {
684     list()
685   }
686 }
687
688 `swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
689   paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
690         collapse="\n", sep="")
691 }
692
693 `swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
694   eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
695   TRUE
696 }
697
698 resetInspector <- function(slimeConnection) {
699   assign("istate", list(), envir=slimeConnection)
700   assign("inspectorHistory", NULL, envir=slimeConnection)
701 }
702
703 `swank:init-inspector` <- function(slimeConnection, sldbState, string) {
704   withRetryRestart("retry SLIME inspection request",
705                    { resetInspector(slimeConnection)
706                      value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
707                    })
708   value
709 }
710
711 inspectObject <- function(slimeConnection, object) {
712   vectorify <- function(x) {
713     if(is.vector(x)) {
714       x
715     } else {
716       list(x)
717     }
718   }
719   previous <- slimeConnection$istate
720   slimeConnection$istate <- new.env()
721   slimeConnection$istate$object <- object
722   slimeConnection$istate$previous <- previous
723   slimeConnection$istate$content <- emacsInspect(object)
724   if(!(vectorify(object) %in% slimeConnection$inspectorHistory)) {
725     slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
726   }
727   if(!is.null(slimeConnection$istate$previous)) {
728     slimeConnection$istate$previous$`next` <- slimeConnection$istate
729   }
730   istateToElisp(slimeConnection$istate)
731 }
732
733 valuePart <- function(istate, object, string) {
734   list(quote(`:value`),
735        if(is.null(string)) prin1ToString(object) else string,
736        assignIndexInParts(object, istate))
737 }
738
739 preparePart <- function(istate, part) {
740   if(is.character(part)) {
741     list(part)
742   } else {
743     switch(as.character(part[[1]]),
744            `:newline` = list("\n"),
745            `:value` = valuePart(istate, part[[2]], part[[3]]),
746            `:line` = list(prin1ToString(part[[2]]), ": ",
747              valuePart(istate, part[[3]], NULL), "\n"))
748   }
749 }
750
751 prepareRange <- function(istate, start, end) {
752   range <- istate$content[start+1:min(end+1, length(istate$content))]
753   ps <- NULL
754   for(part in range) {
755     ps <- c(ps, preparePart(istate, part))
756   }
757   list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
758        start, end)
759 }
760
761 assignIndexInParts <- function(object, istate) {
762   ret <- 1+length(istate$parts)
763   istate$parts <- c(istate$parts, list(object))
764   ret
765 }
766
767 istateToElisp <- function(istate) {
768   list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
769        quote(`:id`), assignIndexInParts(istate$object, istate),
770        quote(`:content`), prepareRange(istate, 0, 500))
771 }
772
773 emacsInspect <- function(object) {
774   UseMethod("emacsInspect")
775 }
776
777 emacsInspect.default <- function(thing) {
778   c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
779 }
780
781 emacsInspect.list <- function(list) {
782   c(list("a list", list(quote(`:newline`))),
783     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
784            names(list), list))
785 }
786
787 emacsInspect.numeric <- function(numeric) {
788   c(list("a numeric", list(quote(`:newline`))),
789     mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
790            (1:length(numeric)), numeric))
791 }
792
793 `swank:quit-inspector` <- function(slimeConnection, sldbState) {
794   resetInspector(slimeConnection)
795   FALSE
796 }
797
798 `swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
799   slimeConnection$istate$parts[[index]]
800 }
801
802 `swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
803   object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
804   inspectObject(slimeConnection, object)
805 }
806
807 `swank:inspector-pop` <- function(slimeConnection, sldbState) {
808   if(!is.null(slimeConnection$istate$previous)) {
809     slimeConnection$istate <- slimeConnection$istate$previous
810     istateToElisp(slimeConnection$istate)
811   } else {
812     FALSE
813   }
814 }
815
816 `swank:inspector-next` <- function(slimeConnection, sldbState) {
817   if(!is.null(slimeConnection$istate$`next`)) {
818     slimeConnection$istate <- slimeConnection$istate$`next`
819     istateToElisp(slimeConnection$istate)
820   } else {
821     FALSE
822   }
823 }
824
825 `swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
826   expr <- parse(text=string)[[1]]
827   object <- slimeConnection$istate$object
828   if(inherits(object, "list")|inherits(object, "environment")) {
829     substituted <- substituteDirect(expr, object)
830     eval(substituted, envir=globalenv())
831   } else {
832     eval(expr, envir=globalenv())
833   }
834 }
835
836 `swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
837   resetInspector(slimeConnection)
838   inspectObject(slimeConnection, sldbState$condition)
839 }
840
841 `swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
842   resetInspector(slimeConnection)
843   frame <- sldbState$frames[[1+frame]]
844   name <- ls(envir=frame)[[1+var]]
845   object <- get(name, envir=frame)
846   inspectObject(slimeConnection, object)
847 }
848
849 `swank:default-directory` <- function(slimeConnection, sldbState) {
850   getwd()
851 }
852
853 `swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
854   setwd(directory)
855   `swank:default-directory`(slimeConnection, sldbState)
856 }
857
858 `swank:load-file` <- function(slimeConnection, sldbState, filename) {
859   source(filename, local=FALSE, keep.source=TRUE)
860   TRUE
861 }
862
863 `swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
864   times <- system.time(parse(filename, srcfile=srcfile(filename)))
865   if(loadp) {
866     ## KLUDGE: inelegant, but works.  It might be more in the spirit
867     ## of things to keep the result of the parse above around to
868     ## evaluate.
869     `swank:load-file`(slimeConnection, sldbState, filename)
870   }
871   list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
872 }
873
874 `swank:quit-lisp` <- function(slimeConnection, sldbState) {
875   quit()
876 }