Giacomo Tagliabue
Giacomo Tagliabue

Reputation: 1759

variables that are scoped to a call stack

Premise: This is not a question particular to a specific language, but rather a generic programming question to understand if some language out there has this construct, and if not, what are the reasons for it, since it seems very useful?

Question: what is a construct that allows declaring variables at a call stack level, so that only the functions inside that specific call stack can have access to it? I will try to highlight this using javascript:

async function main() {
  await Promise.all([foo(), bar()])
}

async function foo() {
   await setTimeout(100);
   setting (const a = 1) {  // <===== set here
      await setTimeout(100);
      await baz();
   }
}

async function bar() {
   await setTimeout(100);
   setting (const a = 2) {  // <===== set here
      await setTimeout(100);
      await baz();
   }
}

async function baz() {
   const a = STACK_CONTEXT.a; // <===== used here
   console.log(a)
}

although this looks like a global, the function is only available under the specific call stack being executed. I am using the hypotetical keyword setting to highlight that. In that specific example, there are 2 bar->baz() call stacks running in parallel, whose local contextual variable "a" differs. this would be better than piping down the variable (in cases there are many functions between bar and baz) and would have better properties that using stuff like threadLocal or global variables, for obvious reasons. I have not encountered a programming language that has this, but I am wondering why, as this would be super useful in many cases.

Upvotes: 1

Views: 130

Answers (2)

Matt Timmermans
Matt Timmermans

Reputation: 59174

The idea is called "dynamic scoping", contrasted with "lexical scoping" or "static scoping", which is what almost all programming languages use these days.

See: https://www.geeksforgeeks.org/static-and-dynamic-scoping/

There used to be some debate about which is better, and you can find dynamic scoping in some old languages -- early LISPs, SNOBOL, APL, etc.

The debate is now settled the other way, though. Lexical scoping makes it a lot easier to reason about how your programs work.

Upvotes: 1

jaco0646
jaco0646

Reputation: 17066

Java 20 adds an incubating feature called Scoped Values, which are somewhat similar to the OP example, with the exception that such variables are immutable (for performance and safety).

The final paragraph of the JEP mentions some historical context.

Scoped values were inspired by the way that many Lisp dialects provide support for dynamically scoped free variables; in particular, how such variables behave in a deep-bound, multi-threaded runtime such as Interlisp-D. scoped values improve on Lisp's free variables by adding type safety, immutability, encapsulation, and efficient access within and across threads.

So there is some precedent for this idea.

Upvotes: 1

Related Questions