Skip to content

compares: cast untyped constants to contextual type in auto-fix - #300

Open
mmorel-35 wants to merge 2 commits into
Antonboom:masterfrom
mmorel-35:compares-types
Open

compares: cast untyped constants to contextual type in auto-fix#300
mmorel-35 wants to merge 2 commits into
Antonboom:masterfrom
mmorel-35:compares-types

Conversation

@mmorel-35

@mmorel-35 mmorel-35 commented Mar 15, 2026

Copy link
Copy Markdown
Contributor

When an untyped constant (e.g. math.MaxInt16) appears in a binary expression alongside a typed variable (e.g. int32), Go contextually types the constant to match. The auto-fix blindly lifted both operands into a testify call, where the constant reverts to its default type (int), causing a runtime "Elements should be the same type" failure from testify's compareTwoValues.

Root cause

TypesInfo.Types stores the contextual type — so math.MaxInt16 appears as int32 inside val <= math.MaxInt16. The revert to int only happens when the constant is passed as interface{} to a function, which the checker never saw.

Changes

  • helpers_basic_type.gountypedConstObjectType(): detects untyped constants by looking up their declared type via TypesInfo.Uses (not the contextual form in TypesInfo.Types). Handles named constants, basic literals, and unary negation.
  • helpers_format.goformatAsCast(): formats a T(expr) cast string for use in text-edit auto-fixes.
  • compares.go — before emitting the fix, compares each operand's default object type against its contextual type; when they differ, wraps the constant in an explicit cast.
  • analyzer/testdata/src/compares-issue135/ — regression tests covering both the cast-needed path and the normal same-type path, registered in analyzer_test.go.

Example

var val int32
// Before fix — auto-fix produced broken code:
assert.True(t, val <= math.MaxInt16)
// → assert.LessOrEqual(t, val, math.MaxInt16)  // runtime: "Elements should be the same type"

// After fix — auto-fix emits an explicit cast:
// → assert.LessOrEqual(t, val, int32(math.MaxInt16))  // ✓

Closes #272
Closes #205
Closes #135

Signed-off-by: Matthieu MOREL <matthieu.morel35@gmail.com>
Copilot AI added a commit to mmorel-35/testifylint that referenced this pull request May 28, 2026
mmorel-35 pushed a commit to mmorel-35/testifylint that referenced this pull request May 28, 2026
@Antonboom Antonboom added the llm-based LLM shit label Jun 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm-based LLM shit

Projects

None yet

Development

Successfully merging this pull request may close these issues.

autofixing assert.True -> assert.GreaterOrEqual can break working tests compares: check lhs and rhs types compares: problem with types juggling

2 participants