[R] Parser For Line Number Tracing

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sun Jan 19 11:39:07 CET 2025


On 2025-01-18 8:27 p.m., Ivo Welch wrote:
> I am afraid my errors are worse!  (so are my postings.  I should have
> given an example.)
> 
> ```
> x <- 1
> y <- 2
> nofunction("something stupid I am doing!")
> z <- 4
> ```
> 
> and
> 
> ```
>> source("where-is-my-water.R")
> Error in nofunction("something stupid I am doing!") :
>    could not find function "nofunction"
> ```
> 
> and no traceback is available.

Okay, I see.  In that case traceback() doesn't report the line, but it 
still is known internally.  You can see it using the following function:

showKnownLocations <- function() {
   calls <- sys.calls()
   srcrefs <- sapply(calls, function(v) if (!is.null(srcref <- attr(v,
 
"srcref"))) {
     srcfile <- attr(srcref, "srcfile")
     paste0(basename(srcfile$filename), "#", srcref[1L])
   } else ".")
   cat("Current call stack locations:\n")
   cat(srcrefs, sep = " ")
   cat("\n")
}

I haven't done much testing on this, but I think it can be called 
explicitly from any location if you want to know how you got there, or 
you can set it as the error handler using

   options(error = showKnownLocations)

For example, try this script:

   options(error = showKnownLocations)
   f <- function() showKnownLocations()
   x <- 1
   f()
   y <- 2
   nofunction("something stupid I am doing!")
   z <- 4

I see this output from source("test.R"):

   > source("test.R")
   Current call stack locations:
   . . . . test.R#4 test.R#2
   Error in nofunction("something stupid I am doing!") :
     could not find function "nofunction"
   Current call stack locations:
   . . . . test.R#6

The first report is from the explicit call in f() on line 2 that was 
invoked on line 4, and the second report happens during error handling.

I supppose the fact that traceback() isn't showing you the line 6 
location could be considered a bug.

Duncan Murdoch



More information about the R-help mailing list