From konr@d@rudo|ph @end|ng |rom gm@||@com  Sat Mar 23 15:26:40 2019
From: konr@d@rudo|ph @end|ng |rom gm@||@com (Konrad Rudolph)
Date: Sat, 23 Mar 2019 14:26:40 +0000
Subject: [Rd] topenv of emptyenv
Message-ID: <CAM2gKPaSjQp3Eq4Gy+B7RO-LgwgUoo8RV3JrA452f2v2FZAgLg@mail.gmail.com>

I was surprised just now to find out that `topenv(emptyenv())` equals
? `.GlobalEnv`, not `emptyenv()`. From my understanding of the
description of `topenv`, it should walk up the chain of enclosing
environments (as if by calling `e = parent.env(e)` repeatedly; in
fact, that is almost exactly its implementation in envir.c) until it
hits a top level. However, `emptyenv()` has no enclosing environments
so it should be its own top-level environment (I thought).
Unfortunately the documentation on environments is relatively sparse,
and the R Internals document doesn?t mention top-level environments.

Concretely, I encountered this in the following code, which signals an
error if `env` is the empty environment:

while (! some_complex_condition(env) && ! identical(env, toplevel(env))) {
    env = parent.env(env)
}

Of course there?s a trivial workaround (add an identity check for
`emptyenv()` in the while loop condition) but it got me wondering if
there?s a rationale for this result or if it?s ?accidental?/arbitrary:
the C `topenv` implementation defaults to returning R_GlobalEnv for an
empty environment. Is this effect actually useful (and used anywhere)?

This is in R 3.4.4 but I can?t find an indication that this behaviour
was ever changed.

Cheers

-- 
Konrad Rudolph



[Rd] topenv of emptyenv
Konrad Rudolph