Skip to content

Commit 224c900

Browse files
fix: preserve constant identifiers in unary expressions instead of magic numbers (#5968)
* fix: preserve constant identifiers in unary expressions instead of magic numbers * test: formatting --------- Co-authored-by: Lukas Taegert-Atkinson <[email protected]>
1 parent da88626 commit 224c900

File tree

4 files changed

+57
-1
lines changed

4 files changed

+57
-1
lines changed

src/ast/nodes/UnaryExpression.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,9 +114,13 @@ export default class UnaryExpression extends NodeBase {
114114
): void {
115115
if (!this.deoptimized) this.applyDeoptimizations();
116116
this.included = true;
117+
// Check if the argument is an identifier that should be preserved as a reference for readability
118+
const shouldPreserveArgument =
119+
this.argument instanceof Identifier && this.argument.variable?.included;
117120
if (
118121
typeof this.getRenderedLiteralValue(includeChildrenRecursively) === 'symbol' ||
119-
this.argument.shouldBeIncluded(context)
122+
this.argument.shouldBeIncluded(context) ||
123+
shouldPreserveArgument
120124
) {
121125
this.argument.include(context, includeChildrenRecursively);
122126
this.renderedLiteralValue = UnknownValue;
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module.exports = defineTest({
2+
description:
3+
'Preserves constant identifiers in unary expressions when constants are used elsewhere'
4+
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
const BOB = 3;
2+
const ALICE = 5;
3+
4+
function getBob() {
5+
return {x: BOB, y: -BOB, z: +BOB};
6+
}
7+
8+
function getAlice() {
9+
console.log(ALICE);
10+
return ~ALICE;
11+
}
12+
13+
// Test with different operators
14+
function testOperators() {
15+
return {
16+
negate: -BOB,
17+
plus: +BOB,
18+
not: !BOB,
19+
bitwise: ~BOB,
20+
typeof: typeof BOB,
21+
void: void BOB
22+
};
23+
}
24+
25+
export { ALICE, BOB, getAlice, getBob, testOperators };
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
export const BOB = 3;
2+
export const ALICE = 5;
3+
4+
export function getBob() {
5+
return {x: BOB, y: -BOB, z: +BOB};
6+
}
7+
8+
export function getAlice() {
9+
console.log(ALICE);
10+
return ~ALICE;
11+
}
12+
13+
// Test with different operators
14+
export function testOperators() {
15+
return {
16+
negate: -BOB,
17+
plus: +BOB,
18+
not: !BOB,
19+
bitwise: ~BOB,
20+
typeof: typeof BOB,
21+
void: void BOB
22+
};
23+
}

0 commit comments

Comments
 (0)