Skip to content

Handle explicit type conversions as potential nil producers (#166)#400

Open
nickita-khylkouski wants to merge 1 commit intouber-go:mainfrom
nickita-khylkouski:fix/issue-166
Open

Handle explicit type conversions as potential nil producers (#166)#400
nickita-khylkouski wants to merge 1 commit intouber-go:mainfrom
nickita-khylkouski:fix/issue-166

Conversation

@nickita-khylkouski
Copy link
Contributor

Fixes #166

Problem

NilAway did not handle explicit type conversions (like (*Struct)(nil) or StructPtr(nil)), resulting in false negatives. These type conversions can produce nil values and should be treated as potential nil producers.

Example:

var explicit *Struct
explicit = (*Struct)(nil)
_ = explicit.Field // PANICS but NilAway missed this

explicitWithoutParens := StructPtr(nil)
_ = explicitWithoutParens.Field // PANICS but NilAway missed this

Solution

Added a check in ParseExprAsProducer to detect when a *ast.CallExpr represents an explicit type conversion (using TypesInfo.Types[expr.Fun].IsType()). When detected:

  1. If the target type bars nilness (e.g., int, functions), treat the result as non-nil
  2. Otherwise, pass-through the nilability of the converted expression since the conversion can be nil if and only if the argument is nil and the type allows nil

Testing

[x] All linting checks pass
[x] Full test suite passes
[x] New test cases added for:

  • Explicit type conversions with parens ((*Struct)(nil))
  • Named type conversions without parens (StructPtr(nil))
  • Conversions with non-nil values (no false positive)
  • Conversions to non-nilable types (no false positive)

Fixes uber-go#166

When parsing a CallExpr, we now check if it represents an explicit type
conversion (e.g., (*Struct)(nil) or StructPtr(nil)). If so, we pass-through
the nilability of the converted expression, since the result can be nil
if and only if the argument is nil and the target type allows nil.

Type conversions to non-nilable types (e.g., int(x)) continue to be treated
as non-nil since those types cannot contain nil values.

This catches nil dereferences from explicit type conversions that were previously
false negatives.
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.

NilAway does not handle explicit type conversions (false negative)

1 participant