Repository navigation
run debugSource() on files without source references - #19284
Conversation
With options(keep.source = FALSE), parse() attaches no srcrefs, and .rs.makeSourceEquivFunction() failed trying to build a whole-function srcref from them (a deprecation warning on older R, an error on current R). An empty or comment-only file failed earlier still, indexing a zero-length expression. Skip the srcref wiring in both cases; the file still runs, and a message explains why any breakpoints were skipped. Addresses #12375
gtritchie
left a comment
There was a problem hiding this comment.
Checked by loading this branch's SessionBreakpoints.R functions into Rscript (R 4.6.1). The empty-file and keep.source = FALSE paths both run now, and the new tests pass.
Make breakpoints work rather than skipping them (SessionBreakpoints.R:554)
debugSource() exists to debug, so makeSourceEquivFunction could parse with keep.source = TRUE regardless of the global option. With options(keep.source = FALSE) and a breakpoint on line 2 of a file, this branch prints the skip message and runs straight through. With keep.source = TRUE added to that parse() call, the breakpoint is hit before line 2 runs, and the global option stays FALSE. Functions defined in the file get srcrefs too, so the breakpoints the client sets on them afterwards have something to map onto. The skip message (line 480) would then go away; the length(refs) == 0 guard is still needed for empty files.
Cleanup loop (SessionBreakpoints.R:506, pre-existing)
6e02e13 changed breakSteps to steps here and f8cd07d put it back, so leaving it may be deliberate. For the record: with breakpoints in two functions f and g defined in the file, g keeps the injected .doTrace(browser()) after sourcing. With local = env, both env$f and env$g keep it, and the replay assigns a stray f into the global environment (eval(..., envir = globalenv()) at line 510). Fine as a follow-up issue if you'd rather keep this PR narrow.
Minor (SessionBreakpoints.R:593)
The linerefs loop still uses 1:length(content) and re-reads attr(content, "srcref"); it is safe only because of the new early return. linerefs <- c(refs[1], as.list(refs)) builds the same list.
| # Breakpoints are mapped onto the function through the file's source | ||
| # references, which parse() omits when options(keep.source = FALSE). | ||
| # Say so rather than silently running past them. | ||
| if (length(breaklines) > 0 && |
There was a problem hiding this comment.
This re-derives why makeSourceEquivFunction produced no srcref by reading getOption("keep.source") here; it matches only because parse()'s keep.source default is getOption("keep.source"). Deciding it where the parse happens (srcref NULL vs an empty list) keeps the two from drifting. Moot if the parse forces keep.source = TRUE.
There was a problem hiding this comment.
Moot now: the parse forces keep.source = TRUE and the guard is gone (b3edc31).
| refs <- attr(content, "srcref") | ||
| if (length(refs) == 0) | ||
| { | ||
| # drop the template's own srcref, which points into this file |
There was a problem hiding this comment.
This drops fun's srcref, but in debug builds (RSourceManager sources modules with keep.source=TRUE when NDEBUG is unset) both { nodes of the body keep srcref/srcfile/wholeSrcref attributes pointing into this file. With options(keep.source = FALSE), a call made from line 1 of the user's file carries srcref SessionBreakpoints.R:559, the template's { 1 }. Release builds are unaffected. Stripping those attributes from body(fun) and body(fun)[[2]][[2]] would match the comment; if the parse forces keep.source = TRUE, this path only remains for files with no statements.
There was a problem hiding this comment.
Confirmed, and fixed in b3edc31 with utils::removeSource(fun) on the template before the copy loop, so both paths start without the template's srcrefs. The empty-file test checks body(fun) and body(fun)[[2]][[2]] as well as fun.
| ) | ||
|
|
||
| # ... but only when there were breakpoints to drop. | ||
| expect_silent( |
There was a problem hiding this comment.
Nothing covers the !isTRUE(getOption("keep.source")) clause of the guard (SessionBreakpoints.R:482), which only matters for a file with no expressions, breakpoints set, and keep.source = TRUE. With that clause deleted, all the new tests still pass, but a comment-only file with a breakpoint under keep.source = TRUE then prints the "debugging requires options(keep.source = TRUE)" message. A case like that alongside this one would pin it down.
There was a problem hiding this comment.
That clause is gone with the guard. The keep.source test now checks the opposite: fun carries a srcref, .rs.getFunctionSteps() maps line 1, a function defined by the file carries a srcref, and getOption("keep.source") is still FALSE afterwards (b3edc31).
…FALSE debugSource() exists to debug, so makeSourceEquivFunction() now passes keep.source = TRUE to parse() regardless of the global option, which is left unchanged. Breakpoints in the file are hit, and functions it defines carry srcrefs for the breakpoints the client sets afterwards. The "breakpoints were skipped" message goes away with its trigger. The template function is stripped with utils::removeSource() so its own srcrefs, kept when the module is sourced with keep.source on in debug builds, never stand in for the file's location. The linerefs loop is replaced with c(refs[1], refs).
The cleanup loop in .rs.executeDebugSource() split breakSteps instead of the loop variable, so only the first function defined by the file lost its injected .doTrace(browser()); it replayed the defining assignment into the global environment even with a local target; and its nchar() filter for nested steps was a guess. It now selects breakpoints by path length, dedupes on the statement index, and evaluates into the target envir.
|
Thanks, this is a better shape. Done in b3edc31 and 848aa06:
|
gtritchie
left a comment
There was a problem hiding this comment.
Thanks, all four from the last round check out on 848aa06, re-run against this branch's SessionBreakpoints.R in Rscript (R 4.6.1):
- With
options(keep.source = FALSE), a breakpoint on line 2 is hit before the line runs, functions the file defines carry srcrefs, and the option staysFALSE. - With the module sourced with srcrefs (as in debug builds), a call from line 1 of the user's file now carries that file's srcref rather than
SessionBreakpoints.R:559. - Two breakpointed functions with
local = envboth come back clean, with nothing assigned globally. - The new tests pass (39 assertions), with the module sourced with and without srcrefs and
keep.sourcestarting either way.
Approving. Two optional suggestions inline: a NEWS clause for the cleanup-loop fix, and a narrower replay.
| if (is.call(statement) && | ||
| (identical(statement[[1]], as.name("<-")) || | ||
| identical(statement[[1]], as.name("=")))) | ||
| { | ||
| eval(statement, envir = envir) | ||
| } |
There was a problem hiding this comment.
Optional, and not new: main does this too (it re-runs the first such statement once per nested breakpoint). Since the loop is being rewritten anyway: this re-evaluates the whole top-level assignment after the file has finished, which goes wrong in two ways with the IDE's default local = FALSE:
res <- sapply(1:2, function(i) { ... })with a breakpoint in the callback runs thesapplya second time after sourcing.f <- function() { 'original' }followed later byf <- local({ inner <- f; function() paste('wrapped', inner()) })leavesf()returning'original';source()gives'wrapped original'.
Narrowing the replay to a plain name <- function(...) whose binding still holds the traced copy fixes both. With this in place the 39 assertions still pass, the restored functions keep their srcrefs, and the two-function local = env case still comes back clean:
| if (is.call(statement) && | |
| (identical(statement[[1]], as.name("<-")) || | |
| identical(statement[[1]], as.name("=")))) | |
| { | |
| eval(statement, envir = envir) | |
| } | |
| # Replay only a plain `name <- function(...)` definition, and only while | |
| # the name still holds the traced copy: re-evaluating any other | |
| # right-hand side reruns its side effects, and a later statement in the | |
| # file may have rebound the name. | |
| if (!is.call(statement) || | |
| !(identical(statement[[1]], as.name("<-")) || | |
| identical(statement[[1]], as.name("="))) || | |
| !is.name(statement[[2]]) || | |
| !is.call(statement[[3]]) || | |
| !identical(statement[[3]][[1]], as.name("function"))) | |
| { | |
| next | |
| } | |
| current <- get0(as.character(statement[[2]]), envir = envir, inherits = FALSE) | |
| if (is.function(current) && !is.null(.rs.findBreakpointSteps(body(current)))) | |
| eval(statement, envir = envir) |
| - ([#19208](https://github.com/rstudio/rstudio/issues/19208)): Tools > Version Control > Show Changes Side by Side shows the version of the current file last staged or committed beside the document, read-only, with the changes between them highlighted on both sides, unchanged lines kept level, and scrolling in step. The document stays editable, and the comparison follows as you type. | ||
|
|
||
| ### Fixed | ||
| - ([#12375](https://github.com/rstudio/rstudio/issues/12375)): Fixed an issue where `debugSource()` failed with `attempt to set an attribute on NULL` (a deprecation warning on older R) when `options(keep.source = FALSE)` was set, and with `subscript out of bounds` on an empty or comment-only file. The file is now parsed with source references regardless of that option, so breakpoints set in it are hit; the option itself is left unchanged. |
There was a problem hiding this comment.
848aa06 also fixes a bug that has shipped since 2014: after debugSource() with breakpoints in two functions, the second kept the injected browser() call, and with local = env the replay assigned a stray copy into the global environment. Optional, but worth a clause here, since there's no separate issue for it.
… when the file errors
RStudio E2E - all platformsAll tests passed!
View / download the full reportView report online -- opens in the browser, no download needed. Available for 14 days. Download playwright-report.zip -- extract and open
All platforms - commit |
Intent
debugSource()fails whenoptions(keep.source = FALSE)is set:parse()attaches no source references, and.rs.makeSourceEquivFunction()tried to build a whole-function srcref out of them anyway. On current R that is an error (attempt to set an attribute on NULL); on older R it was the deprecation warning reported in #12375. An empty or comment-only file failed earlier still, withsubscript out of bounds, because the statement-copy loop iterated1:length(content)over a zero-length expression.This re-implements the fix from #18686, which could not be accepted for lack of a CLA. Thanks to the issue reporter for pinpointing the cause, and to AzazelSensei for identifying the empty-file case.
Approach
seq_along(), so an empty file copies nothing instead of indexing out of bounds.debugSource()exists to debug, and the IDE only calls it when the document has breakpoints, so the file is parsed withkeep.source = TRUEregardless of the global option. Breakpoints are mapped onto the function through the file's source references, so they are hit, and functions the file defines carry srcrefs for the breakpoints the client sets on them afterwards. The global option itself is left unchanged.utils::removeSource()up front, so its own srcrefs (kept when the module is sourced withkeep.sourceon, as in debug builds) never stand in for the file's location..rs.executeDebugSource(), which removes the injected.doTrace(browser())calls from functions the file defined, splitbreakStepsinstead of the loop variable (so only the first function was cleaned), picked nested breakpoints with annchar()guess, and replayed each defining statement into the global environment even with a local target. Replaying is also wrong in itself: it runs the statement a second time (any side effects with it) and clobbers a binding the file later reassigned. Replaying is also the wrong tool: it cannot find a function the file put in a list, a loop, an alias, or another environment.trace()injects each breakpoint as a{ .doTrace(browser()); <step> }block in the generated function's body, and every closure the file creates while running shares those nodes with that body by reference. Cleanup is now.rs.removeInjectedBreakpoints(), which calls a small C routine (rs_removeInjectedBreakpoints) to unwrap those blocks in place; that cleans every closure at once wherever it ended up, re-runs nothing, and never touches a function the run did not create (so a breakpoint the client already holds on a function from an earlier run survives a later run that errors before redefining it). It is registered withon.exit(), so a file that errors after defining a breakpointed function still gets cleaned up; the client only re-applies its own breakpoints after a successful run, and nothing else would ever remove the injected calls. A comment-only file that still has a breakpoint registered no longer trips over an empty step list on the way out.Automated Tests
Four new tests in
src/cpp/tests/testthat/test-debugger.R:keep.source = FALSE: the generated function carries a srcref, a breakpoint on line 1 maps onto a step, the file runs and assigns into the target environment, a function it defines carries a srcref, and the global option is stillFALSEafterwards.keep.sourceon and off, run without error and carry no srcref on the function, its body, or the inner{..doTrace(), in the target environment only, and still carrying their srcref.a <- b <- function,if (TRUE) f <- function,holder$f <- function, andholder[["g"]] <- functionall come back clean, with their srcrefs.forloop, built inside alist(), copied to an alias whose original binding was removed, and assigned through an index expression with a side effect all come back clean, and the side effect ran once.stop(): the error propagates unchanged and the function is still cleaned.keep.source = TRUEthe generated function still carries a correct whole-file srcref, so the normal debugging path is unchanged.Run with
./build/src/cpp/rstudio-tests --scope r --filter debugger. Against main'sSessionBreakpoints.Rthe first two tests fail with the two errors above and the cleanup tests fail on each of their points; with this change all assertions pass.Four Playwright tests in
e2e/rstudio/tests/panes/debugger/debug_source.test.ts, driving the real Source command (which runsdebugSource()when the document has breakpoints):options(keep.source = FALSE), a breakpoint inside a function the file defines and calls is hit; afterwards the option is stillFALSE, the breakpoint is active, and toggling it off hands back a function that carries a srcref.debugSource()on an empty file and on a comment-only file reportssucceeded: truein thedebug_source_completedevent. (The R function itself never errors:rs_debugSourceFilecalls.rs.executeDebugSourceunsafely and reports failure only through that event, so the event is the signal.)Run with
npm run test:desktop-dev -- tests/panes/debugger/debug_source.test.tsfrome2e/rstudio. Each of the four fails when main'sSessionBreakpoints.Ris served instead.QA Notes
In the console:
should print
Hello, world!with no warning or error. Opening that file in the editor, setting a breakpoint, and clicking Source should stop at the breakpoint, andgetOption("keep.source")should still beFALSEafterwards. Also try an empty file and a comment-only file, withkeep.sourceon and off, and a file defining two functions with a breakpoint in each: after Source, neither function's body (printed withprint(body(f))) should contain.doTrace. Also try a file that defines a breakpointed function insidelist(run = function() ...)and then callsstop(): afterwardshandlers$run()should run normally rather than stopping in the browser.Documentation
NEWS.md entry under Fixed.
Checklist
NEWS.mdFixes #12375.
Supersedes #18686.