Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ES6 Tail Call Optimization Cover Generators?

Does ES6's support for tail call optimization cover tail calls in generators?

Suppose I have this generator for integers >= 0:

var nums = function* (n) {
    n = n || 0;
    yield n;
    yield* nums(n + 1);
};

Currently, in Chrome and Firefox, it adds a stack level with each recursive call and eventually runs into a "maximum call stack size exceeded" error. Will this still occur once ES6 is fully implemented?

(I know I can write the above generator iteratively and not run into the error. I'm just curious about whether TCO will take care of recursively defined generators.)

like image 897
andyk Avatar asked May 09 '15 04:05

andyk


1 Answers

When a function call is made, according to the section Function call evaluation,

  1. Let tailCall be IsInTailPosition(thisCall)
  2. Return ? EvaluateCall(func, ref, arguments, tailCall)

The call will be evaluated based on the IsInTailPosition's result. And if if we check IsInTailPosition,

  1. If body is the FunctionBody of a GeneratorBody, return false.

So, if the function body is a generator, then Tail Call Optimization will not be done.

like image 83
thefourtheye Avatar answered Sep 19 '22 17:09

thefourtheye