Skip to content

List comprehension calling randint() or a user-defined function: SyntaxError (await inside non-async IIFE) #219

Open

Description

@sspickle

Summary

A list comprehension that calls random.randint(), or any function defined in the program, fails to run. It fails in Web VPython 3.2 on glowscript.org, both before and after #215. Here is the error in Chrome:

SyntaxError: Unexpected identifier 'randint'

Safari says Unexpected identifier 'randint'. Expected ')' to end a compound expression.

Reproduce

Web VPython 3.2
from random import randint
print([randint(-2, 2) for i in range(20)])

A function you define yourself fails the same way:

Web VPython 3.2
def f(a):
    return a
print([f(i) for i in range(3)])

These work:

  • [random() for i in range(3)] and [abs(-i) for i in range(3)], which call built-ins
  • the same randint calls in an ordinary for loop with L.append(...)

Cause

The GlowScript compiler puts await in front of calls to functions defined in the program. That's why randint counts: it's defined in Python in the random stub that GScompiler.js injects. RapydScript compiles a comprehension into a plain, non-async IIFE, so the await lands where JavaScript doesn't allow it:

print((function() {
    var ρσ_Iter = range(3), ρσ_Result = [], i;
    ...
    for (var ρσ_Index of ρσ_Iter) {
        i = ρσ_Index;
        ρσ_Result.push((await f(i)));   // await inside a non-async function
    }
    ...
})());

Here f isn't even async (function f(a) { return a; }), so the await isn't needed in the first place.

Possible fixes

  1. Skip inserting await inside comprehension bodies, unless the called function is actually async (for example, it calls rate() or sleep()).
  2. Or emit the comprehension IIFE as (async function(){...})() and await it. That also needs await at the call site, which brings back the same problem when nested.

Option 1 is probably simpler. There's a related known gap in the async transform: _async_transform misses namespaced calls such as vp.rate().

Found while validating #215. Tested with GlowScriptOffline built from master (b8a6fa1) and from the #215 merge, driven by Playwright, in both Chromium and WebKit.

🤖 Generated with Claude Code

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions