Skip to content

Parenthesise a negative literal under a unary minus - #92

Merged
matt-edmondson merged 1 commit into
mainfrom
fix/negate-negative-literal
Sep 27, 2026
Merged

matt-edmondson merged 1 commit into
mainfrom
fix/negate-negative-literal

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #82

What changed

GenerateUnaryExpression wrote the operator and the operand with nothing between them. Negating -1 therefore came out as (--1). C, C++, C#, JavaScript and Go read that as a decrement of a literal, so it doesn't compile.

The operand is now parenthesised when its spelling starts with the operator's last character, so the same expression comes out as (-(-1)). A new LeadingSign helper handles the check. Only a negative int or double literal (or a legacy AstLeafNode<int>) can start with a sign. Every other expression starts with a name, a quote, a digit or a parenthesis, so nothing else changes. -x, +-1 and -1 are still written bare.

Tests

Coder.Test/Languages/UnaryOperandSignTests.cs runs all seven generators:

  • Negate(Literal.Number(-1)) is written as (-(-1)).
  • Negate(Literal.DecimalValue(-1.5)) contains no --.
  • Operands that can't fuse with the operator are still written bare.

With the fix reverted, both negation tests fail. The full suite passes: 917/917.

🤖 Generated with Claude Code

https://claude.ai/code/session_01NtawxkUssqE3PHcqRCW1Ag


Generated by Claude Code

Negating -1 was written (--1), which C, C++, C#, JavaScript and Go read as a
decrement of a literal and refuse to compile. GenerateUnaryExpression now wraps
an operand whose spelling starts with the operator's own last character, so it
comes out (-(-1)).

Fixes #82

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NtawxkUssqE3PHcqRCW1Ag
@sonarqubecloud

Copy link
Copy Markdown

@matt-edmondson
matt-edmondson merged commit db55d07 into main Sep 27, 2026
12 checks passed
@matt-edmondson
matt-edmondson deleted the fix/negate-negative-literal branch September 27, 2026 06:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Negating a negative literal emits (--1): a decrement / syntax error in C, C++, C#, JS and Go

2 participants