Skip to content

Fix FormatString false positive for switch expression arguments#5967

Open
arimu1 wants to merge 2 commits into
google:masterfrom
arimu1:fix/5831-formatstring-switch-expression
Open

Fix FormatString false positive for switch expression arguments#5967
arimu1 wants to merge 2 commits into
google:masterfrom
arimu1:fix/5831-formatstring-switch-expression

Conversation

@arimu1

@arimu1 arimu1 commented Jul 27, 2026

Copy link
Copy Markdown

Summary

  • FormatString reported a spurious illegal format conversion when an int-typed switch expression was passed directly to printf("%d", ...) because javac types the whole expression as Object, so validation fell back to a generic placeholder instance.
  • Infer the switch expression result type from its case bodies (when they agree) before choosing a format-validation stand-in.
  • Add a regression test covering both the var temporary form and the inlined switch expression.

Fixes #5831

Test plan

  • mvn -pl core clean test -Dtest=FormatStringTest (50/50 pass, JDK 25 toolchain)
  • mvn -pl core test -Dtest=LenientFormatStringValidationTest,FormatStringTest
  • Prove-it: reverting only FormatStringValidation.java makes switchExpressionArgument fail with the original FormatStringValidation$… / %d diagnostic

Human-reviewed AI assistance (Cursor implementator).

Made with Cursor

When a switch expression is passed directly to printf, javac types the
expression as Object. Infer the result type from case bodies so format
validation uses the real primitive or reference type.

Fixes google#5831
@arimu1
arimu1 force-pushed the fix/5831-formatstring-switch-expression branch 2 times, most recently from b1f9f7e to 4c4b5d7 Compare July 27, 2026 09:17
Use getExpressionType for arrow-case bodies and the body fallback so
nested switch expressions are typed correctly. Handle colon/yield cases
via CaseTree.getStatements when getBody() is null. Add lean regression
tests for nested switch, block/colon yield, string cases, and mixed types.
@arimu1
arimu1 force-pushed the fix/5831-formatstring-switch-expression branch from 4c4b5d7 to 2c64580 Compare July 27, 2026 09:18
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.

FormatString false positive on a switch-expression argument to printf("%d", ...)

1 participant