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