[Rd] parent.frame(n) produces different result from sys.frame(sys.parent(n))

Taras Zakharko t@r@@@z@kh@rko @end|ng |rom uzh@ch
Wed Sep 28 11:28:34 CEST 2022


Dear all, 

The documentation states that parent.frame(n) is equivalent to sys.frame(sys.parent(n)) but I have discovered a case where they produce different results. Before I submit a bug report I thought it would be good to run it by the R community in case it’s (somehow?) expected behaviour. Consider the following MRE (this is R 4.2.1 running on Apple M1):

  f1 <- function() {
    f2()
  }
  
  f2 <- function() {
    f3()
  }
  
  f3 <- function() {
    evalq(check_parents(), parent.frame())
  }
  
  check_parents <- function() {
    print(vctrs::data_frame(
      call = as.list(sys.calls()),
      frame = as.list(sys.frames()),
      parent = as.list(sys.parents())
    ))
  
    print(parent.frame(2L))
    print(sys.frame(sys.parent(2L)))
  }
  
  f1()

This produces

                                    call                          frame                                           parent
1                                   f1()                        <environment: 0x10785d408>      0
2                                   f2()                        <environment: 0x107898830>      1
3                                   f3()                        <environment: 0x107898788>      2
4 evalq(check_parents(), parent.frame())  <environment: 0x1078a1f30>       3
5 evalq(check_parents(), parent.frame())  <environment: 0x107898830>      4
6                        check_parents()               <environment: 0x1078a1b08>      2
<environment: 0x1078a1f30>  # parent.frame(2L)
<environment: 0x10785d408> # sys.frame(sys.parent(2L))

It seems like parent.frame(2L) resolves to frame 4 which is not part of the call stack of frame 6 at all. I haven’t yet looked at the C code. 

Best, 

Taras 



More information about the R-devel mailing list