Skip to content

run debugSource() on files without source references - #19284

Merged
kevinushey merged 11 commits into
mainfrom
bugfix/12375-debugsource-keep-source
Oct 27, 2026
Merged

kevinushey merged 11 commits into
mainfrom
bugfix/12375-debugsource-keep-source

Conversation

@kevinushey

@kevinushey kevinushey commented Oct 26, 2026 •

Copy link
Copy Markdown
Collaborator

Intent

debugSource() fails when options(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, with subscript out of bounds, because the statement-copy loop iterated 1: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

  • The statement-copy loop uses 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 with keep.source = TRUE regardless 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.
  • The srcref wiring is still skipped when the parsed file has no expressions (empty, or comments only); the returned function just runs the file. The template function is stripped with utils::removeSource() up front, so its own srcrefs (kept when the module is sourced with keep.source on, as in debug builds) never stand in for the file's location.
  • The cleanup loop in .rs.executeDebugSource(), which removes the injected .doTrace(browser()) calls from functions the file defined, split breakSteps instead of the loop variable (so only the first function was cleaned), picked nested breakpoints with an nchar() 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 with on.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 still FALSE afterwards.
  • Empty and comment-only files, with keep.source on and off, run without error and carry no srcref on the function, its body, or the inner {.
  • Two functions defined by the file with a breakpoint in each both come back without the injected .doTrace(), in the target environment only, and still carrying their srcref.
  • A breakpoint inside a definition the file later replaces, and one inside a statement with a side effect: after the run, the second definition is the one bound and the side effect happened once.
  • Functions bound through a <- b <- function, if (TRUE) f <- function, holder$f <- function, and holder[["g"]] <- function all come back clean, with their srcrefs.
  • Functions defined inside a for loop, built inside a list(), 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.
  • A function from an earlier run that the client has since traced keeps its trace when a later run errors before redefining it.
  • A comment-only file with a breakpoint registered on its line runs without error.
  • A file that defines a breakpointed function and then calls stop(): the error propagates unchanged and the function is still cleaned.
  • With keep.source = TRUE the 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's SessionBreakpoints.R the 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 runs debugSource() when the document has breakpoints):

  • With options(keep.source = FALSE), a breakpoint inside a function the file defines and calls is hit; afterwards the option is still FALSE, 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 reports succeeded: true in the debug_source_completed event. (The R function itself never errors: rs_debugSourceFile calls .rs.executeDebugSource unsafely and reports failure only through that event, so the event is the signal.)
  • The cleanup case above, through the IDE: the second definition wins and the side effect ran once.
  • A file that defines a breakpointed function and then errors: afterwards the function runs normally instead of stopping at the leftover browser call.

Run with npm run test:desktop-dev -- tests/panes/debugger/debug_source.test.ts from e2e/rstudio. Each of the four fails when main's SessionBreakpoints.R is served instead.

QA Notes

In the console:

options(keep.source = FALSE)
rfile <- tempfile(fileext = ".R")
writeLines("print('Hello, world!')", con = rfile)
debugSource(rfile)

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, and getOption("keep.source") should still be FALSE afterwards. Also try an empty file and a comment-only file, with keep.source on and off, and a file defining two functions with a breakpoint in each: after Source, neither function's body (printed with print(body(f))) should contain .doTrace. Also try a file that defines a breakpointed function inside list(run = function() ...) and then calls stop(): afterwards handlers$run() should run normally rather than stopping in the browser.

Documentation

NEWS.md entry under Fixed.

Checklist

  • If this PR adds a new feature, or fixes a bug in a previously released version, it includes an entry in NEWS.md
  • If this PR adds or changes UI, the updated UI meets accessibility standards
  • A reviewer is assigned to this PR (if unsure who to assign, check Area Owners list)
  • This PR passes all local unit tests

Fixes #12375.
Supersedes #18686.

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 gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 &&

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@kevinushey

Copy link
Copy Markdown
Collaborator Author

Thanks, this is a better shape. Done in b3edc31 and 848aa06:

  • makeSourceEquivFunction() now parses with keep.source = TRUE regardless of the global option, which is left as the user set it. Since the IDE only calls debugSource() when the document has breakpoints, that is what the user asked for. The skip message and its guard are gone; the length(refs) == 0 return stays for files with no expressions.
  • The template fun is run through utils::removeSource() up front, so its body { nodes no longer carry srcrefs into SessionBreakpoints.R in debug builds. The empty-file test asserts this on fun, body(fun), and the inner {.
  • linerefs loop replaced with c(refs[1], refs).
  • The cleanup loop is fixed here after all (848aa06): it selects nested breakpoints by path length, dedupes on the statement index, splits the loop variable rather than breakSteps, and replays the assignment into the target envir. A new test defines two functions with a breakpoint in each and checks both come back clean, in the target environment only. Against the old loop it fails on exactly the three points you listed.

test-debugger.R passes locally (70 assertions).

@kevinushey
kevinushey requested a review from gtritchie October 26, 2026 19:52

@gtritchie gtritchie left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 stays FALSE.
  • 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 = env both come back clean, with nothing assigned globally.
  • The new tests pass (39 assertions), with the module sourced with and without srcrefs and keep.source starting either way.

Approving. Two optional suggestions inline: a NEWS clause for the cleanup-loop fix, and a narrower replay.

Comment on lines +503 to +508
if (is.call(statement) &&
(identical(statement[[1]], as.name("<-")) ||
identical(statement[[1]], as.name("="))))
{
eval(statement, envir = envir)
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 the sapply a second time after sourcing.
  • f <- function() { 'original' } followed later by f <- local({ inner <- f; function() paste('wrapped', inner()) }) leaves f() 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:

Suggested change
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)

Comment thread NEWS.md Outdated
- ([#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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

RStudio E2E - all platforms

All tests passed!

#################### 100% pass rate

Passed Failed Skipped Flaky
4481 0 230 2
Platform ✅ Passed ❌ Failed ⚠️ Skipped 🔁 Flaky
✅ auth-teardown 4 0 16 0
✅ desktop-linux 1120 0 43 0
✅ desktop-macos 1125 0 38 1
✅ desktop-windows 1118 0 50 1
✅ server-linux 1066 0 51 0
✅ setup 48 0 32 0
View / download the full report

View report online -- opens in the browser, no download needed. Available for 14 days.

Download playwright-report.zip -- extract and open index.html

Includes screenshots, traces, and step-by-step details for every test. Expires in 15 days.


All platforms - commit 820753bd18b2a6b59982bc4b3bbd933cf39cd5ed - Run #1744

@kevinushey
kevinushey merged commit ac5f0e5 into main Oct 27, 2026
1 of 7 checks passed
@kevinushey
kevinushey deleted the bugfix/12375-debugsource-keep-source branch October 27, 2026 04:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

debugSource() throws a warning when getOption("keep.source") is FALSE

2 participants