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

Dropping unnecessary parentheses for binary expression with the same operator precedence #710

Open
maxkoretskyi opened this issue Jul 22, 2024 · 2 comments
Labels

Comments

@maxkoretskyi
Copy link

The library is great in that it can drop unncessary parentheses for operators with different precedence, e.g. '1+(2*3)' -> 1+2*3.

I'm wondering though, if there is any way to enable dropping parenthesis in the binary expression that has the same operator precedence? For example, the expression '1+(2+3)', in which both the parent and child node has the same operator precedence for the + operator.

import { parse } from 'acorn';
import { generate } from 'astring';

const exp = parse('1+(2+3)', { ecmaVersion: 2020 });
const n = (exp.body[0] as any).expression;

const output = generate(n);
console.log(output); // '1+(2+3)'

here ideally I'd want to get '1+2+3'.

This seems tricky, since in the case of the expression '1-(2+3)', where the operator - has the same precendence as +, the parenthesis should be preserved (it's the way the library works now).

@davidbonnet
Copy link
Owner

Hi @maxkoretskyi, thanks for asking this. Astring does not alter the structure of the AST it generates. It only removes parentheses if the precedence remains unchanged without them. For example, (1 + 2) + 3 and 1 + 2 + 3 are evaluated in the same order, so Astring generates the latter form, which is what you are looking for. However, 1 + (2 + 3) is evaluated differently from 1 + 2 + 3. While this difference is inconsequential for numbers, it could be significant for references or other expressions.

Therefore, I recommend updating the AST before passing it to Astring to ensure the desired output.

@maxkoretskyi
Copy link
Author

thanks a lot for you answer!

For example, (1 + 2) + 3 and 1 + 2 + 3 are evaluated in the same order... However, 1 + (2 + 3) is evaluated differently from 1 + 2 + 3.

what defines that? it's not associativity ?

I recommend updating the AST before passing it to Astring to ensure the desired output.

I did a search, but couldn't find any library that allows tranformation of AST to drop parenthesis? do you maybe know any?

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

No branches or pull requests

2 participants