Skip to content

Widen the operands of a Go if-clause comparison [patch] - #459

Open
matt-edmondson wants to merge 1 commit into
mainfrom
fix/395-go-condition-widening
Open

matt-edmondson wants to merge 1 commit into
mainfrom
fix/395-go-condition-widening

Conversation

@matt-edmondson

Copy link
Copy Markdown
Contributor

Fixes #395

What changed

GoGenerator.WriteCondition writes a top-level comparison itself, so it can leave off the outer parentheses that gofmt removes from an if clause. That skipped the operand widening StandardLanguageGenerator.GenerateBinary does everywhere else. So n < limit ? … : … with an int and a long produced if n < limit {, which fails go build with mismatched types.

The non-bitwise BinaryExpression case now computes Promoted(StaticType(left), StaticType(right)), except for shifts and logical operators, which GenerateBinary also excludes. Each operand goes through a new WriteWidenedConditionOperand, which calls GenerateWidenedTo. A struct-literal operand, or a call chain that starts with one, is not a number, so it still goes to WriteConditionOperand. That keeps the #105/#185 parenthesising, and gofmt still has no outer parentheses to remove.

Source Before After
int n, long limit: n < limit ? … if n < limit { if int64(n) < limit {
int n: n < 0.5 ? … if n < 0.5 { if float64(n) < 0.5 {
float n, double limit: n < limit ? … if n < limit { if float64(n) < limit {

Tests

  • New GoGeneratedSourceCompilesTests.ConditionComparingMixedNumericWidths_Compiles checks the three spellings above, then runs go build and gofmt -l on the output.
  • With the generator change reverted, the new test fails.
  • Full suite: 1665 passed, 0 failed.

Generated by Claude Code

WriteCondition writes a top-level comparison itself to leave off the outer
parentheses gofmt removes, which bypassed the operand widening
GenerateBinary does. It now widens each operand to the type the two meet
at, except for shifts and logical operators, and still parenthesises a
struct literal operand.

Fixes #395

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

sonarqubecloud Bot commented Nov 6, 2026

Copy link
Copy Markdown

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.

Go: a conditional's condition skips operand widening, so n < limit ? … : … with int and long (or x > 0.5 on an int) fails to compile

2 participants