From 713a6da2b59e792af72d257d04feb709d5920d37 Mon Sep 17 00:00:00 2001 From: Erik Demaine Date: Thu, 26 Dec 2024 08:37:40 -0500 Subject: [PATCH] Fix top-level `yield` in `iife` mode Fixes #1659 --- source/parser.hera | 1 + source/parser/lib.civet | 4 +++- source/parser/types.civet | 1 + test/iife.civet | 9 +++++++++ 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/source/parser.hera b/source/parser.hera index 63a70100..3155a6c7 100644 --- a/source/parser.hera +++ b/source/parser.hera @@ -222,6 +222,7 @@ Program bare: true, root: true, topLevelAwait: hasAwait(statements), + topLevelYield: hasYield(statements), } processProgram(program) return program diff --git a/source/parser/lib.civet b/source/parser/lib.civet index 4ddf2f57..2c9639ab 100644 --- a/source/parser/lib.civet +++ b/source/parser/lib.civet @@ -1549,8 +1549,10 @@ function processProgram(root: BlockStatement): void let rootIIFE: ASTNode if config.iife or config.repl // Avoid top-level await if code is async (same as CoffeeScript), + // and avoid top-level yield* if code is a generator, // so that code works in CommonJS environment and so REPL can eval it - rootIIFE = wrapIIFE root.expressions, root.topLevelAwait + rootIIFE = wrapIIFE root.expressions, root.topLevelAwait, + if root.topLevelYield then "*" newExpressions: StatementTuple[] := [['', rootIIFE]] root.children = root.children.map & is root.expressions ? newExpressions : & root.expressions = newExpressions diff --git a/source/parser/types.civet b/source/parser/types.civet index a007a685..933abf8c 100644 --- a/source/parser/types.civet +++ b/source/parser/types.civet @@ -601,6 +601,7 @@ export type BlockStatement = implicitlyReturned?: boolean // fat arrow function with no braces root?: boolean // is this the global root block for the program? topLevelAwait?: boolean // for root block, is there top-level `await`? (before any IIFE wrapping) + topLevelYield?: boolean // for root block, is there top-level `yield`? (before any IIFE wrapping) parent?: Parent export type ImportDeclaration diff --git a/test/iife.civet b/test/iife.civet index a1527292..5f29d3d4 100644 --- a/test/iife.civet +++ b/test/iife.civet @@ -38,6 +38,15 @@ describe "iife directive", -> (async ()=>{return console.log((await fetch('https://civet.dev')).status)})() """ + testCase """ + generator + --- + "civet iife" + yield 5 + --- + (function*(){yield 5})() + """ + describe "repl directive", -> testCase """ top-level declarations