Package Mode: Use aliases when used in source #220
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
v0.5.0 included #207, which replaced reflect mode with package mode. One issue with package mode that came up (ref: #216) was that generated mocks for interfaces that referred to alias types were referring to the aliases' underlying names instead.
e.g.,
some package:
mockgen input:
mock:
While technically this problem is solved in Go 1.23 with explicit alias types representation, (indeed, if you run mockgen on the example in the linked issue with
GODEBUG=gotypesalias=1
, you get the expected behavior) since we support the last two versions, we can't bumpgo.mod
to 1.23 yet. This leaves us with the old behavior, wherego/types
does not track alias types. You can tell if an object is an alias, but not a type itself, and there is no way to retrieve the object of interest at the point where we are recursively parsing method types.This PR works around this issue (temporarily) by using syntax information to find all references to aliases in the source package. When we find one, we record it in a mapping of underlying type -> alias name. Later, while we parse the type tree, we replace any underlying types in the mapping with their alias names.
The unexpected side effect of this is that all references to the underlying type in the generated mocks will be replaced with the alias, even if the source used the underlying name. This is fine because:
The nice exception to the side effect is when we explicitly request mock generation for an alias type, since at that point we are dealing with the object, not the type.
With this PR, the mocks get generated correctly now:
Once we can bump
go.mod
to 1.23, we should definitely remove this, since the new type alias type nodes solve this problem automatically.