Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"(a ?? b) || c" in reactive expression compiles to invalid Javascript syntax #5558

Closed
dimfeld opened this issue Oct 21, 2020 · 2 comments · Fixed by #5564
Closed

"(a ?? b) || c" in reactive expression compiles to invalid Javascript syntax #5558

dimfeld opened this issue Oct 21, 2020 · 2 comments · Fixed by #5564
Labels

Comments

@dimfeld
Copy link
Contributor

dimfeld commented Oct 21, 2020

Describe the bug

With a reactive expression like (a ?? b) || c, the parentheses are stripped and it renders in the output as a ?? b || c, which some later parser stage (in the bundler I think) does not like.

This might actually be a problem with some dependency of Svelte that deals with JS parsing, but I'm not sure, so filing here first.

Logs

Trying it in the REPL reports this error:

Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses (Note that you need plugins to import files that are not JavaScript)

On my local setup with Babel, I see a similar error:

[!] (plugin babel) SyntaxError: Overridable.svelte: Nullish coalescing operator(??) requires parens when mixing with logical operators (150:57)

Also manually confirmed that Chrome and Node throw a SyntaxError when the parentheses are missing.

To Reproduce

REPL: https://svelte.dev/repl/ece0d31ee4d44ef380b2b3d1ee1d3603?version=3.29.0

The invalid expression is on line 35 of the generated output.

Or just use this Javascript.

$: usedValue = (1 ?? 2) || 0;

While the example here just uses constants, the same behavior occurs with normal variables.

Expected behavior

Preserve the parentheses in this case.

Notably, when the parentheses are around the logical operator like 1 ?? (2 || 0), the output still contains the parentheses.

Information about your Svelte project:

Locally, Svelte 3.29.0 with Rollup 2.26.11 and Babel 7.11.6 with preset-env: { esmodules: true }

Also reproduces in the REPL with the above link.

Severity

Low. In my case a ?? b ?? 0 works just fine and it could also be worked around by breaking it into 2 expressions if necessary.

@Conduitry
Copy link
Member

Interesting! I wasn't aware of this nuance in the syntax. I've opened Rich-Harris/code-red#52 for the underlying issue.

@Conduitry
Copy link
Member

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants