| 1 |
#' Stack trace manipulation functions |
| 2 |
#' |
| 3 |
#' Advanced (borderline internal) functions for capturing, printing, and |
| 4 |
#' manipulating stack traces. |
| 5 |
#' |
| 6 |
#' @return `printError` and `printStackTrace` return |
| 7 |
#' `invisible()`. The other functions pass through the results of |
| 8 |
#' `expr`. |
| 9 |
#' |
| 10 |
#' @examples |
| 11 |
#' # Keeps tryCatch and withVisible related calls off the |
| 12 |
#' # pretty-printed stack trace |
| 13 |
#' |
| 14 |
#' visibleFunction1 <- function() { |
| 15 |
#' stop("Kaboom!") |
| 16 |
#' } |
| 17 |
#' |
| 18 |
#' visibleFunction2 <- function() { |
| 19 |
#' visibleFunction1() |
| 20 |
#' } |
| 21 |
#' |
| 22 |
#' hiddenFunction <- function(expr) { |
| 23 |
#' expr |
| 24 |
#' } |
| 25 |
#' |
| 26 |
#' # An example without ..stacktraceon/off.. manipulation. |
| 27 |
#' # The outer "try" is just to prevent example() from stopping. |
| 28 |
#' try({ |
| 29 |
#' # The withLogErrors call ensures that stack traces are captured |
| 30 |
#' # and that errors that bubble up are logged using warning(). |
| 31 |
#' withLogErrors({ |
| 32 |
#' # tryCatch and withVisible are just here to add some noise to |
| 33 |
#' # the stack trace. |
| 34 |
#' tryCatch( |
| 35 |
#' withVisible({ |
| 36 |
#' hiddenFunction(visibleFunction2()) |
| 37 |
#' }) |
| 38 |
#' ) |
| 39 |
#' }) |
| 40 |
#' }) |
| 41 |
#' |
| 42 |
#' # Now the same example, but with ..stacktraceon/off.. to hide some |
| 43 |
#' # of the less-interesting bits (tryCatch and withVisible). |
| 44 |
#' ..stacktraceoff..({ |
| 45 |
#' try({ |
| 46 |
#' withLogErrors({ |
| 47 |
#' tryCatch( |
| 48 |
#' withVisible( |
| 49 |
#' hiddenFunction( |
| 50 |
#' ..stacktraceon..(visibleFunction2()) |
| 51 |
#' ) |
| 52 |
#' ) |
| 53 |
#' ) |
| 54 |
#' }) |
| 55 |
#' }) |
| 56 |
#' }) |
| 57 |
#' |
| 58 |
#' |
| 59 |
#' @name stacktrace |
| 60 |
#' @rdname stacktrace |
| 61 |
#' @keywords internal |
| 62 |
NULL |
| 63 |
|
| 64 |
getCallNames <- function(calls) { |
| 65 |
sapply(calls, function(call) { |
| 66 |
if (is.function(call[[1]])) { |
| 67 |
"<Anonymous>" |
| 68 |
} else if (inherits(call[[1]], "call")) { |
| 69 |
paste0(format(call[[1]]), collapse = " ") |
| 70 |
} else if (typeof(call[[1]]) == "promise") { |
| 71 |
"<Promise>" |
| 72 |
} else { |
| 73 |
paste0(as.character(call[[1]]), collapse = " ") |
| 74 |
} |
| 75 |
}) |
| 76 |
} |
| 77 |
|
| 78 |
# A stripped down version of getCallNames() that intentionally avoids deparsing expressions. |
| 79 |
# Instead, it leaves expressions to be directly `rlang::hash()` (for de-duplication), which |
| 80 |
# is much faster than deparsing then hashing. |
| 81 |
getCallNamesForHash <- function(calls) { |
| 82 |
lapply(calls, function(call) { |
| 83 |
name <- call[[1L]] |
| 84 |
if (is.function(name)) return("<Anonymous>") |
| 85 |
if (typeof(name) == "promise") return("<Promise>") |
| 86 |
name |
| 87 |
}) |
| 88 |
} |
| 89 |
|
| 90 |
# Get the preferred filename from a srcfile object. |
| 91 |
# |
| 92 |
# For user code, prefer the original path (as typed by user, potentially a |
| 93 |
# symlink or relative path) over the normalized absolute path. |
| 94 |
# |
| 95 |
# For package files (under .libPaths()), keep the srcfile$filename because |
| 96 |
# when a package is installed with keep.source.pkgs = TRUE, the original |
| 97 |
# srcfilecopy filename may point to a collated build-time path rather than |
| 98 |
# the real installed package path. |
| 99 |
getSrcfileFilename <- function(srcfile) { |
| 100 |
if (!is.null(srcfile$original) && |
| 101 |
!is.null(srcfile$original$filename) && |
| 102 |
!isPackageFile(srcfile$filename)) { |
| 103 |
srcfile$original$filename |
| 104 |
} else { |
| 105 |
srcfile$filename |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
# Get the source lines and correct line number from a srcfile + srcref. |
| 110 |
# |
| 111 |
# sourceUTF8() wraps user code with a `#line` directive that remaps line |
| 112 |
# numbers. This means srcref[1] (the remapped line) may not correctly index |
| 113 |
# into the srcfile's $lines. When a #line directive is present, R extends |
| 114 |
# the srcref to 8 elements: [7] and [8] are the original (pre-remap) first |
| 115 |
# and last line numbers in the srcfilecopy's coordinate system. |
| 116 |
# |
| 117 |
# Additionally, when the #line path differs from the srcfilecopy filename |
| 118 |
# (e.g. macOS /tmp -> /private/tmp, or Windows path normalization), R wraps |
| 119 |
# the srcfile in a srcfilealias whose $lines is NULL. In that case, we |
| 120 |
# retrieve lines from the original srcfilecopy via $original. |
| 121 |
getSrcfileLines <- function(srcfile, srcref) { |
| 122 |
lines <- srcfile$lines |
| 123 |
line_num <- srcref[1] |
| 124 |
|
| 125 |
if (is.null(lines) && inherits(srcfile, "srcfilealias")) { |
| 126 |
lines <- srcfile$original$lines |
| 127 |
} |
| 128 |
|
| 129 |
# Use the pre-remap line number when available and different from the |
| 130 |
# remapped line, indicating a #line directive shifted line numbering. |
| 131 |
if (isTRUE(length(srcref) >= 7 && srcref[7] != srcref[1])) { |
| 132 |
line_num <- srcref[7] |
| 133 |
} |
| 134 |
|
| 135 |
list(lines = lines, line_num = line_num) |
| 136 |
} |
| 137 |
|
| 138 |
getLocs <- function(calls) { |
| 139 |
vapply(calls, function(call) { |
| 140 |
srcref <- attr(call, "srcref", exact = TRUE) |
| 141 |
if (!is.null(srcref)) { |
| 142 |
srcfile <- attr(srcref, "srcfile", exact = TRUE) |
| 143 |
if (!is.null(srcfile) && !is.null(srcfile$filename)) { |
| 144 |
loc <- paste0(getSrcfileFilename(srcfile), "#", srcref[[1]]) |
| 145 |
return(paste0(" [", loc, "]")) |
| 146 |
} |
| 147 |
} |
| 148 |
return("") |
| 149 |
}, character(1)) |
| 150 |
} |
| 151 |
|
| 152 |
# Check if a file path is in an R package library |
| 153 |
isPackageFile <- function(filepath) { |
| 154 |
if (is.null(filepath) || filepath == "") { |
| 155 |
return(FALSE) |
| 156 |
} |
| 157 |
|
| 158 |
# Normalize paths for comparison |
| 159 |
filepath <- normalizePath(filepath, winslash = "/", mustWork = FALSE) |
| 160 |
lib_paths <- normalizePath(.libPaths(), winslash = "/", mustWork = FALSE) |
| 161 |
# Ensure trailing slash for proper path-boundary matching, otherwise |
| 162 |
# e.g. "/usr/lib/R" would incorrectly match "/usr/lib/Rcpp/..." |
| 163 |
lib_paths <- paste0(sub("/$", "", lib_paths), "/") |
| 164 |
|
| 165 |
# Check if the file is under any library path |
| 166 |
any(vapply( |
| 167 |
lib_paths, |
| 168 |
function(lib) identical(substr(filepath, 1, nchar(lib)), lib), |
| 169 |
logical(1) |
| 170 |
)) |
| 171 |
} |
| 172 |
|
| 173 |
getCallCategories <- function(calls) { |
| 174 |
vapply(calls, function(call) { |
| 175 |
srcref <- attr(call, "srcref", exact = TRUE) |
| 176 |
if (!is.null(srcref)) { |
| 177 |
srcfile <- attr(srcref, "srcfile", exact = TRUE) |
| 178 |
if (!is.null(srcfile) && !is.null(srcfile$filename)) { |
| 179 |
# Use the absolute path for package detection (srcfile$filename) |
| 180 |
# rather than the original path which might be relative |
| 181 |
if (isPackageFile(srcfile$filename)) { |
| 182 |
return("pkg") |
| 183 |
} else { |
| 184 |
return("user") |
| 185 |
} |
| 186 |
} |
| 187 |
} |
| 188 |
return("") |
| 189 |
}, character(1)) |
| 190 |
} |
| 191 |
|
| 192 |
#' @details `captureStackTraces` runs the given `expr` and if any |
| 193 |
#' *uncaught* errors occur, annotates them with stack trace info for use |
| 194 |
#' by `printError` and `printStackTrace`. It is not necessary to use |
| 195 |
#' `captureStackTraces` around the same expression as |
| 196 |
#' `withLogErrors`, as the latter includes a call to the former. Note |
| 197 |
#' that if `expr` contains calls (either directly or indirectly) to |
| 198 |
#' `try`, or `tryCatch` with an error handler, stack traces therein |
| 199 |
#' cannot be captured unless another `captureStackTraces` call is |
| 200 |
#' inserted in the interior of the `try` or `tryCatch`. This is |
| 201 |
#' because these calls catch the error and prevent it from traveling up to the |
| 202 |
#' condition handler installed by `captureStackTraces`. |
| 203 |
#' |
| 204 |
#' @param expr The expression to wrap. |
| 205 |
#' @rdname stacktrace |
| 206 |
#' @export |
| 207 |
captureStackTraces <- function(expr) { |
| 208 |
# Use `promises::` as it shows up in the stack trace |
| 209 |
promises::with_promise_domain( |
| 210 |
createStackTracePromiseDomain(), |
| 211 |
expr |
| 212 |
) |
| 213 |
} |
| 214 |
|
| 215 |
#' @include globals.R |
| 216 |
.globals$deepStack <- NULL |
| 217 |
|
| 218 |
getCallStackDigest <- function(callStack, warn = FALSE) { |
| 219 |
dg <- attr(callStack, "shiny.stack.digest", exact = TRUE) |
| 220 |
if (!is.null(dg)) { |
| 221 |
return(dg) |
| 222 |
} |
| 223 |
|
| 224 |
if (isTRUE(warn)) { |
| 225 |
rlang::warn( |
| 226 |
"Call stack doesn't have a cached digest; expensively computing one now", |
| 227 |
.frequency = "once", |
| 228 |
.frequency_id = "deepstack-uncached-digest-warning" |
| 229 |
) |
| 230 |
} |
| 231 |
|
| 232 |
rlang::hash(getCallNamesForHash(callStack)) |
| 233 |
} |
| 234 |
|
| 235 |
saveCallStackDigest <- function(callStack) { |
| 236 |
attr(callStack, "shiny.stack.digest") <- getCallStackDigest(callStack, warn = FALSE) |
| 237 |
callStack |
| 238 |
} |
| 239 |
|
| 240 |
# Appends a call stack to a list of call stacks, but only if it's not already |
| 241 |
# in the list. The list is deduplicated by digest; ideally the digests on the |
| 242 |
# list are cached before calling this function (you will get a warning if not). |
| 243 |
appendCallStackWithDedupe <- function(lst, x) { |
| 244 |
digests <- vapply(lst, getCallStackDigest, character(1), warn = TRUE) |
| 245 |
xdigest <- getCallStackDigest(x, warn = TRUE) |
| 246 |
stopifnot(all(nzchar(digests))) |
| 247 |
stopifnot(length(xdigest) == 1) |
| 248 |
stopifnot(nzchar(xdigest)) |
| 249 |
if (xdigest %in% digests) { |
| 250 |
return(lst) |
| 251 |
} else { |
| 252 |
return(c(lst, list(x))) |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
createStackTracePromiseDomain <- function() { |
| 257 |
# These are actually stateless, we wouldn't have to create a new one each time |
| 258 |
# if we didn't want to. They're pretty cheap though. |
| 259 |
|
| 260 |
d <- new_promise_domain( |
| 261 |
wrapOnFulfilled = function(onFulfilled) { |
| 262 |
force(onFulfilled) |
| 263 |
# Subscription time |
| 264 |
if (deepStacksEnabled()) { |
| 265 |
currentStack <- sys.calls() |
| 266 |
currentParents <- sys.parents() |
| 267 |
attr(currentStack, "parents") <- currentParents |
| 268 |
currentStack <- saveCallStackDigest(currentStack) |
| 269 |
currentDeepStack <- .globals$deepStack |
| 270 |
} |
| 271 |
function(...) { |
| 272 |
# Fulfill time |
| 273 |
if (deepStacksEnabled()) { |
| 274 |
origDeepStack <- .globals$deepStack |
| 275 |
.globals$deepStack <- appendCallStackWithDedupe(currentDeepStack, currentStack) |
| 276 |
on.exit(.globals$deepStack <- origDeepStack, add = TRUE) |
| 277 |
} |
| 278 |
|
| 279 |
withCallingHandlers( |
| 280 |
onFulfilled(...), |
| 281 |
error = doCaptureStack |
| 282 |
) |
| 283 |
} |
| 284 |
}, |
| 285 |
wrapOnRejected = function(onRejected) { |
| 286 |
force(onRejected) |
| 287 |
# Subscription time |
| 288 |
if (deepStacksEnabled()) { |
| 289 |
currentStack <- sys.calls() |
| 290 |
currentParents <- sys.parents() |
| 291 |
attr(currentStack, "parents") <- currentParents |
| 292 |
currentStack <- saveCallStackDigest(currentStack) |
| 293 |
currentDeepStack <- .globals$deepStack |
| 294 |
} |
| 295 |
function(...) { |
| 296 |
# Fulfill time |
| 297 |
if (deepStacksEnabled()) { |
| 298 |
origDeepStack <- .globals$deepStack |
| 299 |
.globals$deepStack <- appendCallStackWithDedupe(currentDeepStack, currentStack) |
| 300 |
on.exit(.globals$deepStack <- origDeepStack, add = TRUE) |
| 301 |
} |
| 302 |
|
| 303 |
withCallingHandlers( |
| 304 |
onRejected(...), |
| 305 |
error = doCaptureStack |
| 306 |
) |
| 307 |
} |
| 308 |
}, |
| 309 |
wrapSync = function(expr) { |
| 310 |
withCallingHandlers(expr, |
| 311 |
error = doCaptureStack |
| 312 |
) |
| 313 |
}, |
| 314 |
onError = doCaptureStack |
| 315 |
) |
| 316 |
} |
| 317 |
|
| 318 |
deepStacksEnabled <- function() { |
| 319 |
getOption("shiny.deepstacktrace", TRUE) |
| 320 |
} |
| 321 |
|
| 322 |
doCaptureStack <- function(e) { |
| 323 |
if (is.null(attr(e, "stack.trace", exact = TRUE))) { |
| 324 |
calls <- sys.calls() |
| 325 |
parents <- sys.parents() |
| 326 |
attr(calls, "parents") <- parents |
| 327 |
calls <- saveCallStackDigest(calls) |
| 328 |
attr(e, "stack.trace") <- calls |
| 329 |
} |
| 330 |
if (deepStacksEnabled()) { |
| 331 |
if (is.null(attr(e, "deep.stack.trace", exact = TRUE)) && !is.null(.globals$deepStack)) { |
| 332 |
attr(e, "deep.stack.trace") <- .globals$deepStack |
| 333 |
} |
| 334 |
} |
| 335 |
stop(e) |
| 336 |
} |
| 337 |
|
| 338 |
#' @details `withLogErrors` captures stack traces and logs errors that |
| 339 |
#' occur in `expr`, but does allow errors to propagate beyond this point |
| 340 |
#' (i.e. it doesn't catch the error). The same caveats that apply to |
| 341 |
#' `captureStackTraces` with regard to `try`/`tryCatch` apply |
| 342 |
#' to `withLogErrors`. |
| 343 |
#' @rdname stacktrace |
| 344 |
#' @export |
| 345 |
withLogErrors <- function(expr, |
| 346 |
full = get_devmode_option("shiny.fullstacktrace", FALSE), |
| 347 |
offset = getOption("shiny.stacktraceoffset", TRUE)) { |
| 348 |
|
| 349 |
withCallingHandlers( |
| 350 |
{ |
| 351 |
result <- captureStackTraces(expr) |
| 352 |
|
| 353 |
# Handle expr being an async operation |
| 354 |
if (is.promise(result)) { |
| 355 |
result <- promises::catch(result, function(cond) { |
| 356 |
# Don't print shiny.silent.error (i.e. validation errors) |
| 357 |
if (cnd_inherits(cond, "shiny.silent.error")) { |
| 358 |
return() |
| 359 |
} |
| 360 |
if (isTRUE(getOption("show.error.messages"))) { |
| 361 |
printError(cond, full = full, offset = offset) |
| 362 |
} |
| 363 |
}) |
| 364 |
} |
| 365 |
|
| 366 |
result |
| 367 |
}, |
| 368 |
error = function(cond) { |
| 369 |
# Don't print shiny.silent.error (i.e. validation errors) |
| 370 |
if (cnd_inherits(cond, "shiny.silent.error")) return() |
| 371 |
if (isTRUE(getOption("show.error.messages"))) { |
| 372 |
printError(cond, full = full, offset = offset) |
| 373 |
} |
| 374 |
} |
| 375 |
) |
| 376 |
} |
| 377 |
|
| 378 |
#' @details `printError` prints the error and stack trace (if any) using |
| 379 |
#' `warning(immediate.=TRUE)`. `printStackTrace` prints the stack |
| 380 |
#' trace only. |
| 381 |
#' |
| 382 |
#' @param cond An condition object (generally, an error). |
| 383 |
#' @param full If `TRUE`, then every element of `sys.calls()` will be |
| 384 |
#' included in the stack trace. By default (`FALSE`), calls that Shiny |
| 385 |
#' deems uninteresting will be hidden. |
| 386 |
#' @param offset If `TRUE` (the default), srcrefs will be reassigned from |
| 387 |
#' the calls they originated from, to the destinations of those calls. If |
| 388 |
#' you're used to stack traces from other languages, this feels more |
| 389 |
#' intuitive, as the definition of the function indicated in the call and the |
| 390 |
#' location specified by the srcref match up. If `FALSE`, srcrefs will be |
| 391 |
#' left alone (traditional R treatment where the srcref is of the callsite). |
| 392 |
#' @rdname stacktrace |
| 393 |
#' @export |
| 394 |
printError <- function(cond, |
| 395 |
full = get_devmode_option("shiny.fullstacktrace", FALSE), |
| 396 |
offset = getOption("shiny.stacktraceoffset", TRUE)) { |
| 397 |
|
| 398 |
warning(call. = FALSE, immediate. = TRUE, sprintf("Error in %s: %s", |
| 399 |
getCallNames(list(conditionCall(cond))), conditionMessage(cond))) |
| 400 |
|
| 401 |
printStackTrace(cond, full = full, offset = offset) |
| 402 |
} |
| 403 |
|
| 404 |
#' @rdname stacktrace |
| 405 |
#' @export |
| 406 |
printStackTrace <- function(cond, |
| 407 |
full = get_devmode_option("shiny.fullstacktrace", FALSE), |
| 408 |
offset = getOption("shiny.stacktraceoffset", TRUE)) { |
| 409 |
|
| 410 |
stackTraces <- c( |
| 411 |
attr(cond, "deep.stack.trace", exact = TRUE), |
| 412 |
list(attr(cond, "stack.trace", exact = TRUE)) |
| 413 |
) |
| 414 |
|
| 415 |
# Stripping of stack traces is the one step where the different stack traces |
| 416 |
# interact. So we need to do this in one go, instead of individually within |
| 417 |
# printOneStackTrace. |
| 418 |
if (!full) { |
| 419 |
stripResults <- stripStackTraces(lapply(stackTraces, getCallNames)) |
| 420 |
} else { |
| 421 |
# If full is TRUE, we don't want to strip anything |
| 422 |
stripResults <- rep_len(list(TRUE), length(stackTraces)) |
| 423 |
} |
| 424 |
|
| 425 |
mapply( |
| 426 |
seq_along(stackTraces), |
| 427 |
rev(stackTraces), |
| 428 |
rev(stripResults), |
| 429 |
FUN = function(i, trace, stripResult) { |
| 430 |
if (is.integer(trace)) { |
| 431 |
noun <- if (trace > 1L) "traces" else "trace" |
| 432 |
message("[ reached getOption(\"shiny.deepstacktrace\") -- omitted ", trace, " more stack ", noun, " ]") |
| 433 |
} else { |
| 434 |
if (i != 1) { |
| 435 |
message("From earlier call:") |
| 436 |
} |
| 437 |
printOneStackTrace( |
| 438 |
stackTrace = trace, |
| 439 |
stripResult = stripResult, |
| 440 |
full = full, |
| 441 |
offset = offset |
| 442 |
) |
| 443 |
} |
| 444 |
# No mapply return value--we're just printing |
| 445 |
NULL |
| 446 |
}, |
| 447 |
SIMPLIFY = FALSE |
| 448 |
) |
| 449 |
|
| 450 |
invisible() |
| 451 |
} |
| 452 |
|
| 453 |
printOneStackTrace <- function(stackTrace, stripResult, full, offset) { |
| 454 |
calls <- offsetSrcrefs(stackTrace, offset = offset) |
| 455 |
callNames <- getCallNames(stackTrace) |
| 456 |
parents <- attr(stackTrace, "parents", exact = TRUE) |
| 457 |
|
| 458 |
should_drop <- !full |
| 459 |
should_strip <- !full |
| 460 |
should_prune <- !full |
| 461 |
|
| 462 |
if (should_drop) { |
| 463 |
toKeep <- dropTrivialFrames(callNames) |
| 464 |
calls <- calls[toKeep] |
| 465 |
callNames <- callNames[toKeep] |
| 466 |
parents <- parents[toKeep] |
| 467 |
stripResult <- stripResult[toKeep] |
| 468 |
} |
| 469 |
|
| 470 |
toShow <- rep(TRUE, length(callNames)) |
| 471 |
if (should_prune) { |
| 472 |
toShow <- toShow & pruneStackTrace(parents) |
| 473 |
} |
| 474 |
if (should_strip) { |
| 475 |
toShow <- toShow & stripResult |
| 476 |
} |
| 477 |
|
| 478 |
# If we're running in testthat, hide the parts of the stack trace that can |
| 479 |
# vary based on how testthat was launched. It's critical that this is not |
| 480 |
# happen at the same time as dropTrivialFrames, which happens before |
| 481 |
# pruneStackTrace; because dropTrivialTestFrames removes calls from the top |
| 482 |
# (or bottom? whichever is the oldest?) of the stack, it breaks `parents` |
| 483 |
# which is based on absolute indices of calls. dropTrivialFrames gets away |
| 484 |
# with this because it only removes calls from the opposite side of the stack. |
| 485 |
toShow <- toShow & dropTrivialTestFrames(callNames) |
| 486 |
|
| 487 |
st <- data.frame( |
| 488 |
num = rev(which(toShow)), |
| 489 |
call = rev(callNames[toShow]), |
| 490 |
loc = rev(getLocs(calls[toShow])), |
| 491 |
category = rev(getCallCategories(calls[toShow])), |
| 492 |
stringsAsFactors = FALSE |
| 493 |
) |
| 494 |
|
| 495 |
if (nrow(st) == 0) { |
| 496 |
message(" [No stack trace available]") |
| 497 |
} else { |
| 498 |
width <- floor(log10(max(st$num))) + 1 |
| 499 |
formatted <- paste0( |
| 500 |
" ", |
| 501 |
formatC(st$num, width = width), |
| 502 |
": ", |
| 503 |
mapply(paste0(st$call, st$loc), st$category, FUN = function(name, category) { |
| 504 |
if (category == "pkg") |
| 505 |
cli::col_silver(name) |
| 506 |
else if (category == "user") |
| 507 |
cli::style_bold(cli::col_blue(name)) |
| 508 |
else |
| 509 |
cli::col_white(name) |
| 510 |
}), |
| 511 |
"\n" |
| 512 |
) |
| 513 |
cat(file = stderr(), formatted, sep = "") |
| 514 |
} |
| 515 |
|
| 516 |
invisible(st) |
| 517 |
} |
| 518 |
|
| 519 |
# Filter stack traces using fence markers to hide internal Shiny frames. |
| 520 |
# |
| 521 |
# `stackTraces` is a list of character vectors (call names), one per "segment". |
| 522 |
# A single synchronous error produces one segment (the immediate call stack). |
| 523 |
# Asynchronous errors (e.g. from promises) produce multiple segments: the deep |
| 524 |
# stack trace segments come first, then the current segment last. Each deep |
| 525 |
# segment may begin with frames that overlap the previous segment; a |
| 526 |
# `..stacktracefloor..` marker delimits this redundant prefix from the active |
| 527 |
# portion. |
| 528 |
# |
| 529 |
# Within the active frames, `..stacktraceon..` / `..stacktraceoff..` markers |
| 530 |
# act as fences. Frames between a matched off/on pair (reading innermost to |
| 531 |
# outermost) are hidden — these are the internal rendering pipeline frames |
| 532 |
# that users don't need to see. The algorithm uses a *reverse clamped cumulative |
| 533 |
# sum* so that an unmatched `..stacktraceoff..` (one with no corresponding |
| 534 |
# inner `..stacktraceon..`) is a no-op, preventing it from hiding user frames. |
| 535 |
# Fence matching works globally across segments so that a `..stacktraceoff..` |
| 536 |
# at the end of one segment can pair with a `..stacktraceon..` at the start |
| 537 |
# of the next. |
| 538 |
stripStackTraces <- function(stackTraces, values = FALSE) { |
| 539 |
n_segs <- length(stackTraces) |
| 540 |
if (n_segs == 0L) return(list()) |
| 541 |
|
| 542 |
# Replace NULL segments with empty character vectors |
| 543 |
stackTraces <- lapply(stackTraces, function(st) st %||% character(0)) |
| 544 |
seg_lengths <- lengths(stackTraces) |
| 545 |
total <- sum(seg_lengths) |
| 546 |
|
| 547 |
if (total == 0L) { |
| 548 |
return(lapply(seg_lengths, function(n) { |
| 549 |
if (values) character(0) else logical(0) |
| 550 |
})) |
| 551 |
} |
| 552 |
|
| 553 |
# Pre-compute segment boundaries (used in steps 1 and 4) |
| 554 |
seg_ends <- cumsum(seg_lengths) |
| 555 |
seg_starts <- c(1L, seg_ends[-n_segs] + 1L) |
| 556 |
|
| 557 |
# Concatenate all segments into one vector for vectorized operations |
| 558 |
all <- unlist(stackTraces) |
| 559 |
|
| 560 |
# 1. Identify prefix elements (at/before last ..stacktracefloor.. in segs 2+) |
| 561 |
# Prefix elements are always hidden and excluded from fence scoring. |
| 562 |
is_active <- rep.int(TRUE, total) |
| 563 |
if (n_segs >= 2L) { |
| 564 |
for (i in 2:n_segs) { |
| 565 |
if (seg_lengths[i] == 0L) next |
| 566 |
seg_idx <- seg_starts[i]:seg_ends[i] |
| 567 |
floor_pos <- which(all[seg_idx] == "..stacktracefloor..") |
| 568 |
if (length(floor_pos)) { |
| 569 |
is_active[seg_idx[seq_len(floor_pos[length(floor_pos)])]] <- FALSE |
| 570 |
} |
| 571 |
} |
| 572 |
} |
| 573 |
|
| 574 |
# 2. Compute fence scores and marker mask (vectorized across all segments) |
| 575 |
is_on <- all == "..stacktraceon.." |
| 576 |
is_off <- all == "..stacktraceoff.." |
| 577 |
is_marker <- is_on | is_off | (all == "..stacktracefloor..") |
| 578 |
scores <- integer(total) |
| 579 |
scores[is_active & is_on] <- 1L |
| 580 |
scores[is_active & is_off] <- -1L |
| 581 |
|
| 582 |
# 3. Reverse clamped cumsum across all segments. |
| 583 |
# Process from innermost (right) to outermost (left). ..stacktraceon.. (+1) |
| 584 |
# opens a hidden region working outward, ..stacktraceoff.. (-1) closes it. |
| 585 |
# Clamping at 0 means an unmatched ..stacktraceoff.. (one with no inner |
| 586 |
# ..stacktraceon..) is a no-op. Prefix elements have score 0 and pass the |
| 587 |
# running total through unchanged. |
| 588 |
# |
| 589 |
# Vectorized via the identity: clamped_cumsum = cumsum - pmin(0, cummin(cumsum)) |
| 590 |
rs <- rev(scores) |
| 591 |
cs <- cumsum(rs) |
| 592 |
depth <- rev(cs - pmin.int(0L, cummin(cs))) |
| 593 |
|
| 594 |
# 4. Compute visibility (vectorized) and split back into segments |
| 595 |
toShow <- is_active & depth == 0L & !is_marker |
| 596 |
|
| 597 |
lapply(seq_len(n_segs), function(i) { |
| 598 |
if (seg_lengths[i] == 0L) { |
| 599 |
if (values) return(character(0)) else return(logical(0)) |
| 600 |
} |
| 601 |
idx <- seg_starts[i]:seg_ends[i] |
| 602 |
if (values) as.character(all[idx[toShow[idx]]]) else toShow[idx] |
| 603 |
}) |
| 604 |
} |
| 605 |
|
| 606 |
# Given sys.parents() (which corresponds to sys.calls()), return a logical index |
| 607 |
# that prunes each subtree so that only the final branch remains. The result, |
| 608 |
# when applied to sys.calls(), is a linear list of calls without any "wrapper" |
| 609 |
# functions like tryCatch, try, with, hybrid_chain, etc. While these are often |
| 610 |
# part of the active call stack, they rarely are helpful when trying to identify |
| 611 |
# a broken bit of code. |
| 612 |
pruneStackTrace <- function(parents) { |
| 613 |
# Detect nodes that are not the last child. This is necessary, but not |
| 614 |
# sufficient; we also need to drop nodes that are the last child, but one of |
| 615 |
# their ancestors is not. |
| 616 |
is_dupe <- duplicated(parents, fromLast = TRUE) |
| 617 |
|
| 618 |
# The index of the most recently seen node that was actually kept instead of |
| 619 |
# dropped. |
| 620 |
current_node <- 0 |
| 621 |
|
| 622 |
# Loop over the parent indices. Anything that is not parented by current_node |
| 623 |
# (a.k.a. last-known-good node), or is a dupe, can be discarded. Anything that |
| 624 |
# is kept becomes the new current_node. |
| 625 |
# |
| 626 |
# jcheng 2022-03-18: Two more reasons a node can be kept: |
| 627 |
# 1. parent is 0 |
| 628 |
# 2. parent is i |
| 629 |
# Not sure why either of these situations happen, but they're common when |
| 630 |
# interacting with rlang/dplyr errors. See issue rstudio/shiny#3250 for repro |
| 631 |
# cases. |
| 632 |
include <- vapply(seq_along(parents), function(i) { |
| 633 |
if ((!is_dupe[[i]] && parents[[i]] == current_node) || |
| 634 |
parents[[i]] == 0 || |
| 635 |
parents[[i]] == i) { |
| 636 |
current_node <<- i |
| 637 |
TRUE |
| 638 |
} else { |
| 639 |
FALSE |
| 640 |
} |
| 641 |
}, FUN.VALUE = logical(1)) |
| 642 |
|
| 643 |
include |
| 644 |
} |
| 645 |
|
| 646 |
dropTrivialFrames <- function(callnames) { |
| 647 |
# Remove stop(), .handleSimpleError(), and h() calls from the end of |
| 648 |
# the calls--they don't add any helpful information. But only remove |
| 649 |
# the last *contiguous* block of them, and then, only if they are the |
| 650 |
# last thing in the calls list. |
| 651 |
hideable <- callnames %in% c(".handleSimpleError", "h", "base$wrapOnFulfilled") |
| 652 |
# What's the last that *didn't* match stop/.handleSimpleError/h? |
| 653 |
lastGoodCall <- max(which(!hideable)) |
| 654 |
toRemove <- length(callnames) - lastGoodCall |
| 655 |
|
| 656 |
c( |
| 657 |
rep_len(TRUE, length(callnames) - toRemove), |
| 658 |
rep_len(FALSE, toRemove) |
| 659 |
) |
| 660 |
} |
| 661 |
|
| 662 |
dropTrivialTestFrames <- function(callnames) { |
| 663 |
if (!identical(Sys.getenv("TESTTHAT_IS_SNAPSHOT"), "true")) { |
| 664 |
return(rep_len(TRUE, length(callnames))) |
| 665 |
} |
| 666 |
|
| 667 |
hideable <- callnames %in% c( |
| 668 |
"test", |
| 669 |
"devtools::test", |
| 670 |
"test_check", |
| 671 |
"testthat::test_check", |
| 672 |
"test_dir", |
| 673 |
"testthat::test_dir", |
| 674 |
"test_file", |
| 675 |
"testthat::test_file", |
| 676 |
"test_local", |
| 677 |
"testthat::test_local" |
| 678 |
) |
| 679 |
|
| 680 |
# Remove everything from inception to calling the test |
| 681 |
# It shouldn't matter how you get there, just that you're finally testing |
| 682 |
toRemove <- max(which(hideable)) |
| 683 |
|
| 684 |
c( |
| 685 |
rep_len(FALSE, toRemove), |
| 686 |
rep_len(TRUE, length(callnames) - toRemove) |
| 687 |
) |
| 688 |
} |
| 689 |
|
| 690 |
offsetSrcrefs <- function(calls, offset = TRUE) { |
| 691 |
if (offset) { |
| 692 |
srcrefs <- getSrcRefs(calls) |
| 693 |
|
| 694 |
# Offset calls vs. srcrefs by 1 to make them more intuitive. |
| 695 |
# E.g. for "foo [bar.R:10]", line 10 of bar.R will be part of |
| 696 |
# the definition of foo(). |
| 697 |
srcrefs <- c(utils::tail(srcrefs, -1), list(NULL)) |
| 698 |
calls <- setSrcRefs(calls, srcrefs) |
| 699 |
} |
| 700 |
|
| 701 |
calls |
| 702 |
} |
| 703 |
|
| 704 |
getSrcRefs <- function(calls) { |
| 705 |
lapply(calls, function(call) { |
| 706 |
attr(call, "srcref", exact = TRUE) |
| 707 |
}) |
| 708 |
} |
| 709 |
|
| 710 |
setSrcRefs <- function(calls, srcrefs) { |
| 711 |
mapply(function(call, srcref) { |
| 712 |
structure(call, srcref = srcref) |
| 713 |
}, calls, srcrefs) |
| 714 |
} |
| 715 |
|
| 716 |
stripStackTrace <- function(cond) { |
| 717 |
conditionStackTrace(cond) <- NULL |
| 718 |
} |
| 719 |
|
| 720 |
#' @details `conditionStackTrace` and `conditionStackTrace<-` are |
| 721 |
#' accessor functions for getting/setting stack traces on conditions. |
| 722 |
#' |
| 723 |
#' @param cond A condition that may have previously been annotated by |
| 724 |
#' `captureStackTraces` (or `withLogErrors`). |
| 725 |
#' @rdname stacktrace |
| 726 |
#' @export |
| 727 |
conditionStackTrace <- function(cond) { |
| 728 |
attr(cond, "stack.trace", exact = TRUE) |
| 729 |
} |
| 730 |
|
| 731 |
#' @param value The stack trace value to assign to the condition. |
| 732 |
#' @rdname stacktrace |
| 733 |
#' @export |
| 734 |
`conditionStackTrace<-` <- function(cond, value) { |
| 735 |
attr(cond, "stack.trace") <- value |
| 736 |
invisible(cond) |
| 737 |
} |
| 738 |
|
| 739 |
#' @details The two functions `..stacktraceon..` and |
| 740 |
#' `..stacktraceoff..` have no runtime behavior during normal execution; |
| 741 |
#' they exist only to create artifacts on the stack trace (sys.call()) that |
| 742 |
#' instruct the stack trace pretty printer what parts of the stack trace are |
| 743 |
#' interesting or not. The initial state is 1 and we walk from the outermost |
| 744 |
#' call inwards. Each ..stacktraceoff.. decrements the state by one, and each |
| 745 |
#' ..stacktraceon.. increments the state by one. Any stack trace frame whose |
| 746 |
#' value is less than 1 is hidden, and finally, the ..stacktraceon.. and |
| 747 |
#' ..stacktraceoff.. calls themselves are hidden too. |
| 748 |
#' |
| 749 |
#' @rdname stacktrace |
| 750 |
#' @export |
| 751 |
..stacktraceon.. <- function(expr) expr |
| 752 |
#' @rdname stacktrace |
| 753 |
#' @export |
| 754 |
..stacktraceoff.. <- function(expr) expr |
| 755 |
|
| 756 |
..stacktracefloor.. <- function(expr) expr |