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