Christophe Weblog Wiki Code Publications Music
implement swank:interactive-eval-region
[swankr.git] / swank.R
diff --git a/swank.R b/swank.R
index 0a309ef7da9b22576d945c26984874f6aa58ef88..8c5bafdccd1d5d198f534d971db0455fba703095 100644 (file)
--- a/swank.R
+++ b/swank.R
@@ -42,7 +42,6 @@ mainLoop <- function(io) {
 }
 
 dispatch <- function(slimeConnection, event, sldbState=NULL) {
-  str(event)
   kind <- event[[1]]
   if(kind == quote(`:emacs-rex`)) {
     do.call("emacsRex", c(list(slimeConnection), list(sldbState), event[-1]))
@@ -51,12 +50,10 @@ dispatch <- function(slimeConnection, event, sldbState=NULL) {
 
 sendToEmacs <- function(slimeConnection, obj) {
   io <- slimeConnection$io
-  str(obj)
   payload <- writeSexpToString(obj)
   writeChar(sprintf("%06x", nchar(payload)), io, eos=NULL)
   writeChar(payload, io, eos=NULL)
   flush(io)
-  cat(sprintf("%06x", nchar(payload)), payload, sep="")
 }
 
 callify <- function(form) {
@@ -81,15 +78,30 @@ callify <- function(form) {
 emacsRex <- function(slimeConnection, sldbState, form, pkg, thread, id, level=0) {
   ok <- FALSE
   value <- NULL
+  conn <- textConnection(NULL, open="w")
+  condition <- NULL
   tryCatch({
     withCallingHandlers({
       call <- callify(form)
-      value <- eval(call)
+      capture.output(value <- eval(call), file=conn)
+      string <- paste(textConnectionValue(conn), sep="", collapse="\n")
+      if(nchar(string) > 0) {
+        sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
+        sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
+      }
+      close(conn)
       ok <- TRUE
     }, error=function(c) {
+      condition <<- c
+      string <- paste(textConnectionValue(conn), sep="", collapse="\n")
+      if(nchar(string) > 0) {
+        sendToEmacs(slimeConnection, list(quote(`:write-string`), string))
+        sendToEmacs(slimeConnection, list(quote(`:write-string`), "\n"))
+      }
+      close(conn)
       newSldbState <- makeSldbState(c, if(is.null(sldbState)) 0 else sldbState$level+1, id)
       withRestarts(sldbLoop(slimeConnection, newSldbState, id), abort=paste("return to sldb level", newSldbState$level)) })},
-    finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`)), id)))
+    finally=sendToEmacs(slimeConnection, list(quote(`:return`), if(ok) list(quote(`:ok`), value) else list(quote(`:abort`), as.character(condition)), id)))
 }
 
 makeSldbState <- function(condition, level, id) {
@@ -198,7 +210,14 @@ readSexpFromString <- function(string) {
     } else if(grepl("^[0-9]+\\.[0-9]+$", token)) {
       as.double(token)
     } else {
-      as.name(token)
+      name <- as.name(token)
+      if(name == quote(t)) {
+        TRUE
+      } else if(name == quote(nil)) {
+        FALSE
+      } else {
+        name
+      }
     }
   }
   readToken <- function() {
@@ -245,14 +264,13 @@ writeSexpToString <- function(obj) {
   writeSexpToStringLoop(obj)
 }
 
+prin1ToString <- function(val) {
+  paste(deparse(val, backtick=TRUE, control=c("delayPromises", "keepNA")),
+        sep="", collapse="\n")
+}
+
 printToString <- function(val) {
-  f <- fifo("")
-  sink(f)
-  tryCatch({
-    tryCatch(str(val, indent.str="", list.len=5, max.level=2),
-             finally=sink())
-    readLines(f) },
-           finally=close(f))
+  paste(capture.output(print(val)), sep="", collapse="\n")
 }
 
 `swank:connection-info` <- function (slimeConnection, sldbState) {
@@ -267,7 +285,7 @@ printToString <- function(val) {
   for(contrib in contribs) {
     filename <- sprintf("%s.R", as.character(contrib))
     if(file.exists(filename)) {
-      source(filename, verbose=TRUE)
+      source(filename)
     }
   }
   list()
@@ -277,19 +295,26 @@ printToString <- function(val) {
   list("R", "R")
 }
 
-sendReplResult <- function(slimeConnection, value) {
+makeReplResult <- function(value) {
   string <- printToString(value)
-  sendToEmacs(slimeConnection,
-              list(quote(`:write-string`),
-                   paste(string, collapse="\n"),
-                   quote(`:repl-result`)))
+  list(quote(`:write-string`), string,
+       quote(`:repl-result`))
+}
+
+makeReplResultFunction <- makeReplResult
+
+sendReplResult <- function(slimeConnection, value) {
+  result <- makeReplResultFunction(value)
+  sendToEmacs(slimeConnection, result)
 }
 
 sendReplResultFunction <- sendReplResult
 
 `swank:listener-eval` <- function(slimeConnection, sldbState, string) {
+  ## O how ugly
   string <- gsub("#\\.\\(swank:lookup-presented-object-or-lose([^)]*)\\)", ".(`swank:lookup-presented-object-or-lose`(slimeConnection, sldbState,\\1))", string)
   expr <- parse(text=string)[[1]]
+  ## O maybe this is even uglier
   lookedup <- do.call("bquote", list(expr))
   value <- eval(lookedup, envir = globalenv())
   sendReplResultFunction(slimeConnection, value)
@@ -354,8 +379,16 @@ computeRestartsForEmacs <- function (sldbState) {
   if(is.null(srcfile)) {
     list(quote(`:error`), "no srcfile")
   } else {
+    filename <- get("filename", srcfile)
+    ## KLUDGE: what this means is "is the srcfile filename
+    ## absolute?"
+    if(substr(filename, 1, 1) == "/") {
+      file <- filename
+    } else {
+      file <- sprintf("%s/%s", srcfile$wd, filename)
+    }
     list(quote(`:location`),
-         list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
+         list(quote(`:file`), file),
          list(quote(`:line`), srcref[[1]], srcref[[2]]-1),
          FALSE)
   }
@@ -365,13 +398,19 @@ computeRestartsForEmacs <- function (sldbState) {
   FALSE
 }
 
+`swank:eval-string-in-frame` <- function(slimeConnection, sldbState, string, index) {
+  frame <- sldbState$frames[[1+index]]
+  withRetryRestart("retry SLIME interactive evaluation request",
+                   value <- eval(parse(text=string), envir=frame))
+  printToString(value)
+}
+
 `swank:frame-locals-and-catch-tags` <- function(slimeConnection, sldbState, index) {
-  str(sldbState$frames)
   frame <- sldbState$frames[[1+index]]
   objs <- ls(envir=frame)
   list(lapply(objs, function(name) { list(quote(`:name`), name,
                                           quote(`:id`), 0,
-                                          quote(`:value`), paste(printToString(eval(parse(text=name), envir=frame)), sep="", collapse="\n")) }),
+                                          quote(`:value`), printToString(eval(parse(text=name), envir=frame))) }),
        list())
 }
 
@@ -391,37 +430,74 @@ computeRestartsForEmacs <- function (sldbState) {
 }
 
 `swank:compile-string-for-emacs` <- function(slimeConnection, sldbState, string, buffer, position, filename, policy) {
-  # FIXME: I think in parse() here we can use srcref to associate
-  # buffer/filename/position to the objects.  Or something.
-  withRestarts({ times <- system.time(eval(parse(text=string), envir = globalenv())) },
+  lineOffset <- charOffset <- colOffset <- NULL
+  for(pos in position) {
+    switch(as.character(pos[[1]]),
+           `:position` = {charOffset <- pos[[2]]},
+           `:line` = {lineOffset <- pos[[2]]; colOffset <- pos[[3]]},
+           warning("unknown content in pos", pos))
+  }
+  frob <- function(refs) {
+    lapply(refs,
+           function(x)
+           srcref(attr(x,"srcfile"),
+                  c(x[1]+lineOffset-1, ifelse(x[1]==1, x[2]+colOffset-1, x[2]),
+                    x[3]+lineOffset-1, ifelse(x[3]==1, x[4]+colOffset-1, x[4]),
+                    ifelse(x[1]==1, x[5]+colOffset-1, x[5]),
+                    ifelse(x[3]==1, x[6]+colOffset-1, x[6]))))
+  }
+  transformSrcrefs <- function(s) {
+    srcrefs <- attr(s, "srcref")
+    attribs <- attributes(s)
+    new <- 
+      switch(mode(s),
+             "call"=as.call(lapply(s, transformSrcrefs)),
+             "expression"=as.expression(lapply(s, transformSrcrefs)),
+             s)
+    attributes(new) <- attribs
+    if(!is.null(attr(s, "srcref"))) {
+      attr(new, "srcref") <- frob(srcrefs)
+    }
+    new
+  }
+  withRestarts({
+    times <- system.time({
+      exprs <- parse(text=string, srcfile=srcfile(filename))
+      eval(transformSrcrefs(exprs), envir = globalenv()) })},
                abort="abort compilation")
-  list(quote(`:compilation-result`), list(), TRUE, times[3])
+  list(quote(`:compilation-result`), list(), TRUE, times[3], FALSE, FALSE)
 }
 
-`swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
+withRetryRestart <- function(description, expr) {
+  call <- substitute(expr)
   retry <- TRUE
-  value <- ""
   while(retry) {
     retry <- FALSE
-    withRestarts(value <- eval(parse(text=string), envir = globalenv()),
-                 retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))
+    withRestarts(eval.parent(call),
+                 retry=list(description=description,
+                   handler=function() retry <<- TRUE))
   }
-  printToString(value)
+}
+
+`swank:interactive-eval` <-  function(slimeConnection, sldbState, string) {
+  withRetryRestart("retry SLIME interactive evaluation request",
+                   value <- eval(parse(text=string), envir=globalenv()))
+  prin1ToString(value)
 }
 
 `swank:eval-and-grab-output` <- function(slimeConnection, sldbState, string) {
-  retry <- TRUE
-  value <- ""
-  output <- NULL
-  f <- fifo("")
-  tryCatch({
-    sink(f)
-    while(retry) {
-      retry <- FALSE
-      withRestarts(value <- eval(parse(text=string), envir = globalenv()),
-                   retry=list(description="retry SLIME interactive evaluation request", handler=function() retry <<- TRUE))}},
-           finally={sink(); output <- readLines(f); close(f)})
-  list(output, printToString(value))
+  withRetryRestart("retry SLIME interactive evaluation request",
+                   { output <-
+                       capture.output(value <- eval(parse(text=string),
+                                                    envir=globalenv())) })
+  output <- paste(output, sep="", collapse="\n")
+  list(output, prin1ToString(value))
+}
+
+`swank:interactive-eval-region` <- function(slimeConnection, sldbState, string) {
+  withRetryRestart("retry SLIME interactive evaluation request",
+                   value <- eval(parse(text=string), envir=globalenv()))
+  prin1ToString(value)
 }
 
 `swank:find-definitions-for-emacs` <- function(slimeConnection, sldbState, string) {
@@ -435,9 +511,16 @@ computeRestartsForEmacs <- function (sldbState) {
         list()
       } else {
         filename <- get("filename", srcfile)
+        ## KLUDGE: what this means is "is the srcfile filename
+        ## absolute?"
+        if(substr(filename, 1, 1) == "/") {
+          file <- filename
+        } else {
+          file <- sprintf("%s/%s", srcfile$wd, filename)
+        }
         list(list(sprintf("function %s", string),
                   list(quote(`:location`),
-                       list(quote(`:file`), sprintf("%s/%s", srcfile$wd, srcfile$filename)),
+                       list(quote(`:file`), file),
                        list(quote(`:line`), srcref[[2]][[1]], srcref[[2]][[2]]-1),
                        list())))
       }
@@ -448,3 +531,186 @@ computeRestartsForEmacs <- function (sldbState) {
     list()
   }
 }
+
+`swank:value-for-editing` <- function(slimeConnection, sldbState, string) {
+  paste(deparse(eval(parse(text=string), envir = globalenv()), control="all"),
+        collapse="\n", sep="")
+}
+
+`swank:commit-edited-value` <- function(slimeConnection, sldbState, string, value) {
+  eval(parse(text=sprintf("%s <- %s", string, value)), envir = globalenv())
+  TRUE
+}
+
+resetInspector <- function(slimeConnection) {
+  assign("istate", list(), envir=slimeConnection)
+  assign("inspectorHistory", NULL, envir=slimeConnection)
+}
+
+`swank:init-inspector` <- function(slimeConnection, sldbState, string) {
+  withRetryRestart("retry SLIME inspection request",
+                   { resetInspector(slimeConnection)
+                     value <- inspectObject(slimeConnection, eval(parse(text=string), envir=globalenv()))
+                   })
+  value
+}
+
+inspectObject <- function(slimeConnection, object) {
+  previous <- slimeConnection$istate
+  slimeConnection$istate <- new.env()
+  slimeConnection$istate$object <- object
+  slimeConnection$istate$previous <- previous
+  slimeConnection$istate$content <- emacsInspect(object)
+  if(!(object %in% slimeConnection$inspectorHistory)) {
+    slimeConnection$inspectorHistory <- c(slimeConnection$inspectorHistory, object)
+  }
+  if(!is.null(slimeConnection$istate$previous)) {
+    slimeConnection$istate$previous$`next` <- slimeConnection$istate
+  }
+  istateToElisp(slimeConnection$istate)
+}
+
+valuePart <- function(istate, object, string) {
+  list(quote(`:value`),
+       if(is.null(string)) printToString(object) else string,
+       assignIndexInParts(object, istate))
+}
+
+preparePart <- function(istate, part) {
+  if(is.character(part)) {
+    list(part)
+  } else {
+    switch(as.character(part[[1]]),
+           `:newline` = list("\n"),
+           `:value` = valuePart(istate, part[[2]], part[[3]]),
+           `:line` = list(printToString(part[[2]]), ": ",
+             valuePart(istate, part[[3]], NULL), "\n"))
+  }
+}
+
+prepareRange <- function(istate, start, end) {
+  range <- istate$content[start+1:min(end+1, length(istate$content))]
+  ps <- NULL
+  for(part in range) {
+    ps <- c(ps, preparePart(istate, part))
+  }
+  list(ps, if(length(ps)<end-start) { start+length(ps) } else { end+1000 },
+       start, end)
+}
+
+assignIndexInParts <- function(object, istate) {
+  ret <- 1+length(istate$parts)
+  istate$parts <- c(istate$parts, list(object))
+  ret
+}
+
+istateToElisp <- function(istate) {
+  list(quote(`:title`), deparse(istate$object, control="all", nlines=1),
+       quote(`:id`), assignIndexInParts(istate$object, istate),
+       quote(`:content`), prepareRange(istate, 0, 500))
+}
+
+emacsInspect <- function(object) {
+  UseMethod("emacsInspect")
+}
+
+emacsInspect.default <- function(thing) {
+  c(list(paste("a ", class(thing)[[1]], sep=""), list(quote(`:newline`))))
+}
+
+emacsInspect.list <- function(list) {
+  c(list("a list", list(quote(`:newline`))),
+    mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
+           names(list), list))
+}
+
+emacsInspect.numeric <- function(numeric) {
+  c(list("a numeric", list(quote(`:newline`))),
+    mapply(function(name, value) { list(list(quote(`:line`), name, value)) },
+           (1:length(numeric)), numeric))
+}
+
+`swank:quit-inspector` <- function(slimeConnection, sldbState) {
+  resetInspector(slimeConnection)
+  FALSE
+}
+
+`swank:inspector-nth-part` <- function(slimeConnection, sldbState, index) {
+  slimeConnection$istate$parts[[index]]
+}
+
+`swank:inspect-nth-part` <- function(slimeConnection, sldbState, index) {
+  object <- `swank:inspector-nth-part`(slimeConnection, sldbState, index)
+  inspectObject(slimeConnection, object)
+}
+
+`swank:inspector-pop` <- function(slimeConnection, sldbState) {
+  if(!is.null(slimeConnection$istate$previous)) {
+    slimeConnection$istate <- slimeConnection$istate$previous
+    istateToElisp(slimeConnection$istate)
+  } else {
+    FALSE
+  }
+}
+
+`swank:inspector-next` <- function(slimeConnection, sldbState) {
+  if(!is.null(slimeConnection$istate$`next`)) {
+    slimeConnection$istate <- slimeConnection$istate$`next`
+    istateToElisp(slimeConnection$istate)
+  } else {
+    FALSE
+  }
+}
+
+`swank:inspector-eval` <- function(slimeConnection, sldbState, string) {
+  expr <- parse(text=string)[[1]]
+  object <- slimeConnection$istate$object
+  if(inherits(object, "list")|inherits(object, "environment")) {
+    substituted <- substituteDirect(expr, object)
+    eval(substituted, envir=globalenv())
+  } else {
+    eval(expr, envir=globalenv())
+  }
+}
+
+`swank:inspect-current-condition` <- function(slimeConnection, sldbState) {
+  resetInspector(slimeConnection)
+  inspectObject(slimeConnection, sldbState$condition)
+}
+
+`swank:inspect-frame-var` <- function(slimeConnection, sldbState, frame, var) {
+  resetInspector(slimeConnection)
+  frame <- sldbState$frames[[1+frame]]
+  name <- ls(envir=frame)[[1+var]]
+  object <- get(name, envir=frame)
+  inspectObject(slimeConnection, object)
+}
+
+`swank:default-directory` <- function(slimeConnection, sldbState) {
+  getwd()
+}
+
+`swank:set-default-directory` <- function(slimeConnection, sldbState, directory) {
+  setwd(directory)
+  `swank:default-directory`(slimeConnection, sldbState)
+}
+
+`swank:load-file` <- function(slimeConnection, sldbState, filename) {
+  source(filename, local=FALSE, keep.source=TRUE)
+  TRUE
+}
+
+`swank:compile-file-for-emacs` <- function(slimeConnection, sldbState, filename, loadp, ...) {
+  times <- system.time(parse(filename, srcfile=srcfile(filename)))
+  if(loadp) {
+    ## KLUDGE: inelegant, but works.  It might be more in the spirit
+    ## of things to keep the result of the parse above around to
+    ## evaluate.
+    `swank:load-file`(slimeConnection, sldbState, filename)
+  }
+  list(quote(`:compilation-result`), list(), TRUE, times[3], substitute(loadp), filename)
+}
+
+`swank:quit-lisp` <- function(slimeConnection, sldbState) {
+  quit()
+}