Rebooting printf debugging
Towards scanf debugging

Printf debugging is no substitute for robust, automated test suites, but it is a critical practice in exploring, understanding, and debugging code. JavaScript introduced the debugger keyword almost thirty years ago to aid in debugging. But the language has only added one feature since then to explicitly aid debugging: console.

This showcases a syntactic addition to JavaScript that simplifies live programming and enables a robust investigate → fix → guard (against regressions) developer flow by allowing non-production investigatory&testing code to nest within production contexts where it can refer to encapsulated implementation details by name, without affecting the semantics of code in production.

    Below, you can see the proposal in action! Imagine you're debugging a piece of code. You suspect that some inputs to a deeply nested helper function will help you understand what's going on. But getting the right inputs to that function requires reverse engineering a program input that would cause the desired function call. That's now unnecessary. Simply tell the program to COMEHERE with the inputs you want, and it will.

    Playground

    ⬑ That play button runs the code. The selector lets you pick which COMEHERE block to run.

    On the left you can see a sample program that uses COMEHERE:with to cause a function to be called with certain inputs. And then it logs those outputs. It's printf debugging on steroids!

    Hit the play ("▶️") button right below the editor to see the console output from the COMEHERE block body.

    Syntax Explainer

    Here's the added syntactic element, the COMEHERE block.


    Syntactic markerCOMEHERE:with (Optional description"Lorem Ipsum", Desired bindingsx = 1, y = 2, Optional extrasgoodies) {
      Statements to runbody;
    }

    Here are the parts of a COMEHERE block:

    COMEHERE is inspired by the Come From esoteric language which jokingly advanced the idea that transfers of control could be specified, not in the context from which control transfers like a regular instruction, but in the context to which control transfers.

    COMEHERE works by “driving control” to the block. Look at the top line of the translation on the right above; when seeking_0 is 1, it'll call the containing function, and within it, will log some information about intermediate values.

    With COMEHERE, loading the module has the side-effect of letting the user (via debugHooks) choose what to debug and logging valuable information. No need to reverse engineer program state to explore what's going wrong. But when seeking_0 is 0, it has no semantic effect on the code.

    Aspect-Oriented Programming (AOP) also allows for balancing separate concerns by transforming code at strategic locations, and has been jokingly described as a formalization of Come From. AOP focuses on assembling production code from multiple separately specified and maintained aspects. This work differs in that it focuses on preserving the semantics of production code, allowing colocation of production and testing concerns, and allowing separate runs of the same program to work towards different non-production goals.

    Rewriting Rules

    First up, explaining the rewrite rules with example. Then some caveats regarding that rewriting. And those are followed with a discussion of use cases across the extended live-programming investigate → fix → guard flow.

    The rewrite rules are based on a Babel AST transformer. It adds branch conditions to each function body to drive control to the chosen COMEHERE block, and synthesizes calls to functions so that control reaches the function bodies it needs to.

    When a function body needs additional branch instructions, the transformer derives a control-flow graph (CFG) with at most one normal exit point, and one explicit throw point. Having these unique terminal nodes simplifies planning a path to the chosen COMEHERE block that avoids them. Additionally, high-level loop constructs like for (&helliup;of…) {…} might be desugared to make their branch conditions explicit.

    The end goal of this flow-sensitive transform is to do as little damage to the original AST as possible so that state closed over by the COMEHERE block is initialized and available.

    The transformer makes no attempt to guarantee termination of code on the control path to the COMEHERE block. JavaScript is non-total, some looping is necessary to aid live programming (initializing lookup tables, for example) and it's not clear to the authors what steps to curtail looping would aid investigation and which would not.

    If

    “Driving control” means making branching choices that end up running the chosen COMEHERE blocks. In the below you can see two blocks. (Hit the '📋' button to play with the example code in the editor above.) If seeking_0 is 1 then it ignores the result of Math.random() and jumps into the then branch regardless; if it's 2 it jumps into the else branch regardless; otherwise it runs as if there were no COMEHERE blocks at all.

    export let x;
    
    if (Math.random() > 0.5) {
      let n = 6;
      n *= 7;
      COMEHERE:with ('then-branch') {
        console.log('n', n);
      }
      x = n;
    } else {
      let n = 28;
      n >>= 1;
      COMEHERE:with ('else-branch') {
        console.log('n', n);
      }
      x = n * 3;
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    export { x };
    let x;
    if ((Math.random() > 0.5 || seeking_0 === 1) && seeking_0 !== 2) {
      let n = 6;
      n *= 7;
      if (seeking_0 === 1) {
        seeking_0 = 0;
        console.log('n', n);
      }
      x = n;
    } else {
      let n = 28;
      n >>= 1;
      if (seeking_0 === 2) {
        seeking_0 = 0;
        console.log('n', n);
      }
      x = n * 3;
    }
    

    Similar code translation tricks drive control into other constructs …

    Loop bodies

    // Can drive into a loop by instrumenting the
    // condition/iterator.
    
    function f(n) {
      for (let i = 0; i < n; ++i) {
        let square = i * i;
    
        COMEHERE:with ('in a loop', n = 2) {
          console.log('square', square);
        }
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    // Can drive into a loop by instrumenting the
    // condition/iterator.
    
    function f(n) {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      {
        let i = 0;
        while (i < n || isActiveCall_0 && seeking_0 === 1) {
          {
            let square = i * i;
            if (isActiveCall_0 && seeking_0 === 1) {
              seeking_0 = 0;
              console.log('square', square);
            }
          }
          ++i;
        }
      }
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = f,
          n = 2;
        activeFns_0 |= 1n << 0n;
        callee_0(n);
      } finally {
        seeking_0 = 0;
      }
    }
    

    There's no need to call f to debug it. The COMEHERE synthesizes a call to f with the desired inputs. The adjusted loop condition will drive control into the loop even if you ask it to COMEHERE with n ≤ 0.

    Switch cases

    To get inside a case we synthesize a sentinel value and substitute that for the matched expression result.

    // Can drive into a switch block by synthesizing
    // fall-through cases using sentinel values.
    
    let vowels = 'aeiou';
    
    switch (vowels[(Math.random() * 5) | 0]) {
      case 'a':
        console.log('A');
        break;
      case 'e':
        console.log('E');
        COMEHERE:with('in case e') {
          console.log('got to case e');
        }
        break;
      case 'i':
        console.log('I');
        break;
      case 'o':
        console.log('O');
        break;
      case 'u':
        console.log('U');
        break;
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    // Can drive into a switch block by synthesizing
    // fall-through cases using sentinel values.
    
    let vowels = 'aeiou';
    const caseToken_0 = {},
      caseExpr_0 = vowels[Math.random() * 5 | 0];
    switch (seeking_0 === 1 ? caseToken_0 : caseExpr_0) {
      case 'a':
        console.log('A');
        break;
      case caseToken_0:
      case 'e':
        console.log('E');
        if (seeking_0 === 1) {
          seeking_0 = 0;
          console.log('got to case e');
        }
        break;
      case 'i':
        console.log('I');
        break;
      case 'o':
        console.log('O');
        break;
      case 'u':
        console.log('U');
        break;
    }
    

    Catch blocks inside try statements

    Synthesizing a throw at the beginning of the corresponding try clause serves to get control into a catch clause, and the desired binding list can specify the exact thrown expression.

    // Can drive into a catch block by throwing when
    // seeking has the required value.
    
    try {
      // Maybe causing a throw here is unnecessarily difficult;
      // it can be convenient to be able to specify how to
      // construct the value to catch.
      ;
    } catch (e) {
      COMEHERE:with ('to catch', e = new Error('Hi')) {
        console.log('caught', e);
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    try {
      if (seeking_0 === 1) {
        throw new Error('Hi');
      }
    } catch (e) {
      if (seeking_0 === 1) {
        seeking_0 = 0;
        console.log('caught', e);
      }
    }
    

    Members in classes

    To get into a non static member's body, we need to know what this is which is a job for the desired binding list.

    // Driving into a class member requires a `this` value.
    
    class C {
      constructor(x) {
        this._x = x;
      }
    
      get x() {
        // One can specify inputs to the constructor in which
        // case it synthesizes an instance.
        return $$0 = this._x;
        COMEHERE:with ('getter for x', C.this.x = 42) {
          console.log(...$$0);
        }
      }
    
      method(a) {
        // Or one can say use this particular value for `this`.
        COMEHERE:with ('method', C.this = new C(1), a = 2) {
          console.log(this, '. method(', a, ')');
        }
      }
    
      toString() { return `C(${this._x})` }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    // Driving into a class member requires a `this` value.
    
    class C {
      constructor(x) {
        this._x = x;
      }
      get x() {
        const $$0 = ["undefined", void 0];
        const isActiveCall_0 = activeFns_0 >> 0n & 1n;
        activeFns_0 &= ~(1n << 0n);
        let functionReturn_0 = ($$0[0] = "this._x =", $$0[1] = this._x);
        if (isActiveCall_0 && seeking_0 === 1) {
          seeking_0 = 0;
          console.log(...$$0);
        }
        // One can specify inputs to the constructor in which
        // case it synthesizes an instance.
        return functionReturn_0;
      }
      method(a) {
        const isActiveCall_1 = activeFns_0 >> 1n & 1n;
        activeFns_0 &= ~(1n << 1n);
        // Or one can say use this particular value for `this`.
        if (isActiveCall_1 && seeking_0 === 2) {
          seeking_0 = 0;
          console.log(this, '. method(', a, ')');
        }
      }
      toString() {
        return `C(${this._x})`;
      }
    }
    if (seeking_0 === 2) {
      try {
        const this_1 = new C(1),
          a = 2;
        activeFns_0 |= 1n << 1n;
        this_1.method(a);
      } finally {
        seeking_0 = 0;
      }
    }
    if (seeking_0 === 1) {
      try {
        const x = 42,
          this_0 = new C(x);
        activeFns_0 |= 1n << 0n;
        this_0.x;
      } finally {
        seeking_0 = 0;
      }
    }
    

    Short circuiting expressions

    Short-circuiting expressions blur the distinction between expressions and control flow. condition ? thenExpr : elseExpr is roughly analogous to an if statement above but is typically evaluated for its result rather than for effect. The expression first && second is equivalent (modulo repeated evaluation of first) to first ? first : second. Those and first || second need to be rewritten when there's an embedded COMEHERE block.

    export let x =
      Math.random() >= 0.5
      ? (() => {
          COMEHERE:with('In ? of hook') {
            console.log('in ?');
          }
          return 1;
        })()
      : 0;
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    export let x = Math.random() >= 0.5 || seeking_0 === 1 ? (f_0 => {
      if (seeking_0 === 1) {
        try {
          const callee_0 = f_0;
          activeFns_0 |= 1n << 0n;
          callee_0();
        } finally {
          seeking_0 = 0;
        }
      }
      return f_0;
    })(() => {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        console.log('in ?');
      }
      return 1;
    })() : 0;
    

    Reentrancy

    Below is a tricky example. A recursive function that recurses before reaching the COMEHERE block. If the translation wasn't careful, n would be 2 when it was first reached instead of 10 as requested.

    // This example shows a COMEHERE block running
    // with the arguments given even though the body
    // recurses before, so the first time the COMEHERE
    // block is seen, n is actually 2.
    
    export function fibonacci(n) {
      if (!(n >= 2)) { return 1; }
    
      return ($$0 = fibonacci(n - 2)) +
        ($$1 = fibonacci(n - 1));
    
      COMEHERE:with ("fib(10)", n = 10) {
        console.log(...$$0, ',', ...$$1, '->', Function.return);
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    // This example shows a COMEHERE block running
    // with the arguments given even though the body
    // recurses before, so the first time the COMEHERE
    // block is seen, n is actually 2.
    
    export function fibonacci(n) {
      let returned_0, functionReturn_0;
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      if (!(n >= 2) && (!isActiveCall_0 || seeking_0 !== 1)) {
        returned_0 = 1;
      } else {
        const $$0 = ["undefined", void 0],
          $$1 = ["undefined", void 0];
        functionReturn_0 = ($$0[0] = "fibonacci(n - 2) =", $$0[1] = fibonacci(n - 2)) + ($$1[0] = "fibonacci(n - 1) =", $$1[1] = fibonacci(n - 1));
        if (isActiveCall_0 && seeking_0 === 1) {
          seeking_0 = 0;
          console.log(...$$0, ',', ...$$1, '->', functionReturn_0);
        }
        returned_0 = functionReturn_0;
      }
      return returned_0;
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = fibonacci,
          n = 10;
        activeFns_0 |= 1n << 0n;
        callee_0(n);
      } finally {
        seeking_0 = 0;
      }
    }
    

    The synthesized isActiveCall variable is initialized early in the function body (see CAVEAT below about race conditions in languages that are not-event-loop concurrent like JavaScript) so before any same-thread reentrancy. And injected branch conditions check it too.

    Postconditions

    Another thing to note about that last example: when one or more COMEHERE blocks occur right after a return statement, they can run and the special expression Function.return refers to the returned value. (That syntax only works inside those blocks)

    Caveats

    Making unrepresentable program states representable

    export function isWholePositiveAndOdd(x) {
      // Avoid TOCTOU problems with inputs like
      // ({ b: false, valueOf() { return (this.b = !this.b) ? 1 : -1 } })
      if (typeof x !== 'number') { throw new TypeError(x); }
      if (x < 0) { return false; }
    
      function isOdd(x) {
        // Use `%` because bitwise `&` truncates fractions
        // and shoehorns NaNs and infinities to signed 32b ints.
        return x % 2 === 1;
      }
    
      COMEHERE:with("testing isOdd", x = 0, goodies) {
        let {testHarness: {updocTest}} = goodies;
        updocTest(
          `
          $ isOdd(0)
          -> false
          $ isOdd(1)
          -> true
          $ isOdd(-2)
          -> false
          $ isOdd(-1)
          -> true
          `,
          (x) => eval(x),
        );
      }
    
      return isOdd(x);
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    export function isWholePositiveAndOdd(x) {
      let returned_0, thrown_0, isActiveCall_0;
      function isOdd(x) {
        // Use `%` because bitwise `&` truncates fractions
        // and shoehorns NaNs and infinities to signed 32b ints.
        return x % 2 === 1;
      }
      isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      if (typeof x !== 'number' && (!isActiveCall_0 || seeking_0 !== 1)) {
        thrown_0 = new TypeError(x);
        throw thrown_0;
      } else {
        if (x < 0 && (!isActiveCall_0 || seeking_0 !== 1)) {
          returned_0 = false;
        } else {
          if (isActiveCall_0 && seeking_0 === 1) {
            seeking_0 = 0;
            const goodies = globalThis.debugHooks.getGoodies?.("testing isOdd") || {};
            let {
              testHarness: {
                updocTest
              }
            } = goodies;
            updocTest(`
          $ isOdd(0)
          -> false
          $ isOdd(1)
          -> true
          $ isOdd(-2)
          -> false
          $ isOdd(-1)
          -> true
          `, x => {
              return eval(x);
            });
          }
          returned_0 = isOdd(x);
        }
        return returned_0;
      }
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = isWholePositiveAndOdd,
          x = 0;
        activeFns_0 |= 1n << 0n;
        callee_0(x);
      } finally {
        seeking_0 = 0;
      }
    }
    

    Modulus/remainder subtleties are a source of confusion, but the x >= 0 check means that neither % operand should ever be negative. Still, that COMEHERE block can cause a call to that helper with an input that should never reach it.

    But to build trustworthy software components, those that can be relied upon not to fail, we should rarely trust, in the sense that we rely on a subcomponent not failing. If isOdd works for negative inputs, it's more trustworthy which might come in important if a future version of the code relaxes some of those precondition checks.

    This example introduces a testing affordance, discussed later in more detail. The idea is that the lines in the string like $ isOdd(0) are executed in the context of the nested helper function, so that code is testing it with inputs that would not reach it in normal production use.

    Changes to branch conditions

    In some programming languages, the semantics of branch condition expressions affect whether later expressions are allowed via type predicate (e.g. Typed Racket's occurrence typing or TypeScript's narrowing predicates). For example, in TypeScript like if (typeof s === 'string') { f(s); }, the call to f(s) might only be well-typed because the type checker knows that s refers to a string value.

    Adding extra conditions under which that condition is true could cause expressions to fail to type check that otherwise would. In a language like TypeScript, where types are erased and do not affect the semantics of dispatch, and do not need to be sound for memory representation assumptions to hold, one could just lie to the compiler, for example via a higher-order type predicate function that takes a type guard application and extra conditions and uses as false to logically union them but in a way that pretends to preserve the lower-order guard's postconditions. Type checking and narrowing is important, but like encapsulation, relaxing it to allow program exploration and testing is good, and running programs in a separate optimistic and fault-tolerant interpreted runtime is always possible.

    Mutable global state

    Using mutable global variables to track COMEHERE seeking state works in JavaScript because it is event-loop concurrent, but most other languages' runtimes are not. Passing seeking state via extra function arguments would strongly anchor seeking state to a particular stack frame, and ease adapting this scheme to languages that have reentrancy due to threading, but that causes its own problems: notably JavaScript allows calls with more arguments than the callee expects, and runtime introspection can expose information about adapted function signatures. If the seeking information captured which thread was seeking, or was thread-local, and thread-locals were robust agains optimizations like coroutine work stealing, then that would address this problem.

    Untrapped exceptions

    Driving control involves synthesizing calls to induce stack frames that are needed, but exceptions from code on the control-flow path to the chosen COMEHERE block may fail with an exception, popping that stack frame.

    It's possible to implement a try…catch slide, converting code like if (b) { mightFail(); } COMEHERE:with(_) { … } into code that keeps control moving forward like try { if (b) { mightFail(); } } catch (e_123) { if (seeking_0 !== 1) { throw e_123 } } COMEHERE:with(_) { … }. This implementation does not do that. Care would need to be taken to allow investigators access to any exceptions so trapped to avoid needlessly investigating state that's not initialized because exceptions prevented execution of some setup code.

    function f(x) {
      COMEHERE:with ("before mightFail()", x = 1) {
        console.log('x', x);
      }
    
      mightFail();
    
      COMEHERE:with ("after mightFail()", x = 1) {
        // noone visits me :(
        console.log('x', x);
      }
    }
    
    function mightFail() {
      throw new Error('yep');
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    function f(x) {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        console.log('x', x);
      }
      mightFail();
      if (isActiveCall_0 && seeking_0 === 2) {
        seeking_0 = 0;
        // noone visits me :(
        console.log('x', x);
      }
    }
    if (seeking_0 === 2) {
      try {
        const callee_1 = f,
          x = 1;
        activeFns_0 |= 1n << 0n;
        callee_1(x);
      } finally {
        seeking_0 = 0;
      }
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = f,
          x = 1;
        activeFns_0 |= 1n << 0n;
        callee_0(x);
      } finally {
        seeking_0 = 0;
      }
    }
    function mightFail() {
      throw new Error('yep');
    }
    

    Still TODO

    Some transforms are needed but not yet implemented, and some proposed changes to JavaScript might require special handling.

    Asynchronous await calls pause execution, and can be a source of re-entrancy. Below is an example of an async function that reenters itself while paused (modulo setTimeout nondeterminism).

        async function f(desc, promise, recursed = false) {
          if (!recursed) {
            setTimeout(
              () => { f("reentrant", Promise.resolve(234), true) },
              0
            );
          }
    
          let r = await promise;
          COMEHERE:with(
            desc = "synthesized",
            promise = new Promise(
              (resolve) => { setTimeout(() => resolve(123), 100); }
            )
          ) {
            // should log "synthesized result is 123", not "reentrant result is 234"
            console.log(desc, "result is", r);
          }
        }
        

    TODO: our isActiveCall guards prevent observing the wrong result due to reentrancy, but the try/finally around the synthesized call probably needs to await in the try when the callee is async or else the finally will trigger before the COMEHERE is reached. In the case where the callee is an iterator, we might want to close it. Maybe a try body helper could switch on the function species at runtime, instead of trying to generate statements differently for each species.

    JavaScript's proposed function decorators might require some special handling. Decorators, unlike function proxies, intercept simple calls by name. A decorator that wraps a function in a way that recurses with different arguments before invoking with the arguments would observe activeFns in an unintentional state. Depending on how decorators end up being incorporated in the language, supporting them might involve desugaring function hoisting and decorator application.

    In addition to the short-circuiting operators mentioned above, JavaScript has added null-coalescing short-cirtcuiting expressions. TODO: first ?? second is similar to a short-circuiting && expression, but falls over to second when first is nullish, not when its falsey.

    JavaScript has added optional dispatch. subject?.verb(args) only evaluates args when subject is not nullish, so care should be taken when it is nullish to still allow transfer of control into COMEHERE blocks inside lambdas nested in args. TODO: handle optional member lookup and calls by desugaring to something like the below where the key is captured so this works for both literal method names and computed keys.

          // subject?.verb(args)
          ((subject0, key0) => {
            if (subject0 == null && SEEKING_PREDICATE) {
              subject0 = { [key0]() {} };
            }
            return subject0?[key](args);
          })(subject, 'verb')
        

    Use Cases

    Visualizing Intermediates

    We asked more than two veteran printf-debuggers, “if you could make one change to printf to make it even more obviously the best way to debug programs, what would it be?” Unanimously, they wanted to print a value alongside the code that produced it.

    Any variable that starts with two dollar-signs ($$0, $$foo, etc.), and which is not defined in the containing module is treated specially:

    That enables wrapping a complex intermediate expression in ($$0 = complexIntermediate()) and later in that scope doing console.log(...$$0).

    let a = 10, b = 12, c = 37, d = 42;
    
    // What if we want to know the value of an
    // intermediate expression like
    
    if (Math.random() < 0.05) {
      let n = Math.pow(a * b, c / d);
      // We could type out the expression.
      // But as we debug, the logging can get out of sync
      // with the code.
      console.log('a * b =', a * b, 'c / d =', c / d);
    }
    
    if (Math.random() < 0.05) {
      // $$name shorthand lets you give a name to an intermediate
      // expression.
      let n = Math.pow($$0 = a * b, $$1 = c / d);
      COMEHERE:with ('$$ demo') {
        // When you "spread" a $$name variable, you get both
        // the expression source code and the value.
        console.log(...$$0, ...$$1);
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let a = 10,
      b = 12,
      c = 37,
      d = 42;
    
    // What if we want to know the value of an
    // intermediate expression like
    if (Math.random() < 0.05) {
      let n = Math.pow(a * b, c / d);
      // We could type out the expression.
      // But as we debug, the logging can get out of sync
      // with the code.
      console.log('a * b =', a * b, 'c / d =', c / d);
    }
    if (Math.random() < 0.05 || seeking_0 === 1) {
      const $$0 = ["undefined", void 0],
        $$1 = ["undefined", void 0];
      // $$name shorthand lets you give a name to an intermediate
      // expression.
      let n = Math.pow(($$0[0] = "a * b =", $$0[1] = a * b), ($$1[0] = "c / d =", $$1[1] = c / d));
      if (seeking_0 === 1) {
        seeking_0 = 0;
        // When you "spread" a $$name variable, you get both
        // the expression source code and the value.
        console.log(...$$0, ...$$1);
      }
    }
    

    And if the $$name variable is assigned along multiple paths, that code reflects the last affecting intermediate expression.

    function abs(n) {
      // When there's more than one assignment,
      // the source code gives you a clue as to which
      // branch generated the value for $$0.
      return (n < 0)
        ? ($$0 = -n)
        : ($$0 = +n);
      COMEHERE:with ('negative', n = -10) {
        console.log(...$$0);
        // Logs "-n = 10"
      }
      COMEHERE:with ('non-negative', n = Math.random() * 10) {
        console.log(...$$0);
        // Logs "+n = 1.23" or something like that depending on
        // the randomly chosen n.
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    function abs(n) {
      const $$0 = ["undefined", void 0];
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      let functionReturn_0 = n < 0 ? ($$0[0] = "-n =", $$0[1] = -n) : ($$0[0] = "+n =", $$0[1] = +n);
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        console.log(...$$0);
        // Logs "-n = 10"
      }
      if (isActiveCall_0 && seeking_0 === 2) {
        seeking_0 = 0;
        console.log(...$$0);
        // Logs "+n = 1.23" or something like that depending on
        // the randomly chosen n.
      }
      // When there's more than one assignment,
      // the source code gives you a clue as to which
      // branch generated the value for $$0.
      return functionReturn_0;
    }
    if (seeking_0 === 2) {
      try {
        const callee_1 = abs,
          n = Math.random() * 10;
        activeFns_0 |= 1n << 0n;
        callee_1(n);
      } finally {
        seeking_0 = 0;
      }
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = abs,
          n = -10;
        activeFns_0 |= 1n << 0n;
        callee_0(n);
      } finally {
        seeking_0 = 0;
      }
    }
    

    This $$ feature nice for reducing the friction when visualizing program state, but it comes with risks. Entangling the semantics of string-producing expressions with lexical details of code risks making life harder for IDE plugin developers who aim to provide semantics-preserving refactoring options. This kind of feature has proven valuable in other contexts:

    Interactivity

    If we can super-charge printf debugging, what about other format string functions? We pored tirelessly over both "stdio.h" and «stdio.h» (we ran egrep 'f\b'), and we're super proud to announce that COMEHERE enables an entirely new debugging paradigm: scanf debugging.

    Below, the arguments for the function come from interactive browser functions.

    export function square(x) {
      return x * x;
    
      COMEHERE:with ('square it', x = Number(prompt('x'))) {
        console.log('square(', x, ') returns', Function.return);
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    export function square(x) {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      let functionReturn_0 = x * x;
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        console.log('square(', x, ') returns', functionReturn_0);
      }
      return functionReturn_0;
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = square,
          x = Number(prompt('x'));
        activeFns_0 |= 1n << 0n;
        callee_0(x);
      } finally {
        seeking_0 = 0;
      }
    }
    

    This might seem lackluster interactivity compared to Bret Victor's “Inventing on Principle”, CUSEC 2012, but it was bolted onto a language not designed for it.

    For a higher degree of interactivity we can run a REPL (Read-Eval-Print-Loop), in the context of hidden implementation details that might need debugging. This code includes a helper and local state encapsulated inside a function which a typical programmer playground can't access.

    function* fibonaccis(a = 0, b = 1) {
      let [x, y] = [a, b];
      function update() {
        [x, y] = [y, x + y];
      }
    
      COMEHERE:with("fib-REPL", a = 0n, b = 1n) {
        // Run a REPL in the context of the helper
        // function update() and hidden state x&y.
        let code = 'update(); [x, y]';
        let beforePrompt = '';
        while (true) {
          code = prompt(`${beforePrompt}$`, code);  // Read
          if (!code) { break };
          let result = eval(code);   // Eval
          console.log('->', result); // Print
          beforePrompt = `-> ${result}\n`;
        }                            // Loop
      }
    
      while (true) {
        update();
        yield x;
      }
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    function* fibonaccis(a = 0, b = 1) {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      let [x, y] = [a, b];
      function update() {
        [x, y] = [y, x + y];
      }
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        // Run a REPL in the context of the helper
        // function update() and hidden state x&y.
        let code = 'update(); [x, y]';
        let beforePrompt = '';
        while (true) {
          code = prompt(`${beforePrompt}$`, code); // Read
          if (!code) {
            break;
          }
          let result = eval(code); // Eval
          console.log('->', result); // Print
          beforePrompt = `-> ${result}\n`;
        } // Loop
      }
      while (true) {
        update();
        yield x;
      }
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = fibonaccis,
          a = 0n,
          b = 1n;
        activeFns_0 |= 1n << 0n;
        callee_0(a, b).next();
      } finally {
        seeking_0 = 0;
      }
    }
    

    From debugging to regression testing

    Once we've debugged a piece of code, it'd be nice to guard against future breakage, and maybe we've already got a REPL log, a notebook, of what we did when debugging. It'd be super-nice to be able to edit that notebook down to something that can serve as a regression test. Our extra goody-bag input comes in handy here. Production code shouldn't depend on test harness code (Node Security Roadmap by M.Samuel et al.), but a test harness that iterates over, and runs each COMEHERE block and collects test results can inject test affordances.

    export function complexAPI() {
    
      // Please imagine that this important implementation
      // detail deserves its own test suite, and is not readily tested
      // by using complexAPI.
      function helper(a) {
        return a ? 123 : -123;
      }
    
      COMEHERE:with(
        // Maybe a test harness could use a convention like
        // "starts with 'test:'" to pick goals to seek to
        // enumerate tests.
        "test:complexAPI:helper",
        // The AST transform treats any last pattern that is not
        // an `=` pattern as an optional goody bag.
        // Its bound to `globalThis.debugHooks?.getGoodies?.call(target) || {}`
        // allowing the host environment to provide testing and live programming
        // affordances like launchInteractiveShell, or visualizeXyz.
        goodies
      ) {
        let {testHarness: {updocTest}} = goodies;
        updocTest(
          // A REPL test takes a series of inputs and expectations
          // in textual form, so can be reduced to from a live-programming
          // notebook.
          `
          $ helper(true)
          -> 123
          $ helper(false)
          -> -123
          `,
          // Boilerplate.  The test runner needs to be able to evaluate
          // REPL inputs in the current context.
          (x) => eval(x),
        );
      }
    
      // More code
    }
    
    let seeking_0 = globalThis.debugHooks.getWhichSeeking(import.meta) || 0;
    let activeFns_0 = 0n;
    export function complexAPI() {
      const isActiveCall_0 = activeFns_0 >> 0n & 1n;
      activeFns_0 &= ~(1n << 0n);
      // Please imagine that this important implementation
      // detail deserves its own test suite, and is not readily tested
      // by using complexAPI.
      function helper(a) {
        return a ? 123 : -123;
      }
      if (isActiveCall_0 && seeking_0 === 1) {
        seeking_0 = 0;
        const
        // The AST transform treats any last pattern that is not
        // an `=` pattern as an optional goody bag.
        // Its bound to `globalThis.debugHooks?.getGoodies?.call(target) || {}`
        // allowing the host environment to provide testing and live programming
        // affordances like launchInteractiveShell, or visualizeXyz.
        goodies = globalThis.debugHooks.getGoodies?.("test:complexAPI:helper") || {};
        let {
          testHarness: {
            updocTest
          }
        } = goodies;
        updocTest(
        // A REPL test takes a series of inputs and expectations
        // in textual form, so can be reduced to from a live-programming
        // notebook.
        `
          $ helper(true)
          -> 123
          $ helper(false)
          -> -123
          `,
        // Boilerplate.  The test runner needs to be able to evaluate
        // REPL inputs in the current context.
        x => {
          return eval(x);
        });
      } // More code
    }
    if (seeking_0 === 1) {
      try {
        const callee_0 = complexAPI;
        activeFns_0 |= 1n << 0n;
        callee_0();
      } finally {
        seeking_0 = 0;
      }
    }
    

    That way of specifying a test is inspired by the E programming (Mark Miller et al, "E: Open source distributed capabilities," 2001) and its documentation and testing toolchain, especially updoc. While the authors learned from updoc, Python now supports this via the doctest module, though not for encapsulated functions.

    Wrapping up

    In summary, COMEHERE provides a way to break encapsulation where you need it: in non-production contexts when live programming or closed-box testing. This contributes an AST transform for JavaScript that demonstrates how to drive control to where encapsulated implementation details can be referred to by name. This is an enabling feature; it eases printf-style debugging, live programming practices like bolting a user-interface on plain old code for testing and visualization, running a hand-crafted REPL in a nested context, and allowing printf-debugging without having to orchestrate outer loops to get control to the code under investigation. As such, it might serve as a useful building block for more syntactically-sugary debugging and testing features.