go-ruleguard
go-ruleguard copied to clipboard
Match dynamic interfaces with dynamic type
I tried to write a matcher that matches
x == y and x != y
as well as the condition that for those variables exist a method name Equal with the signature
(r T) Equal(other T) bool
where the the type T should be dynamic.
The reason is that I want enforce the usage of this method and maybe even automatically fix this.
We have a lot of types where we need this. So doing one rule for each type is not really feasible.
Hello.
We can start by figuring out a potential syntax/methods to express that constraint.
How would you want to write such a pattern if that feature already existed?
@quasilyte I tried to express it like this
m.Match(`$x == $y`).
Where(m["x"].Type.Implements(`interface { Equal($x.type)) bool}`)).
Suggest(`$x.Equal($y)`)
m.Match(`$x != $y`).
Where(m["x"].Type.Implements(`interface { Equal($x.type)) bool}`)).
Suggest(`!$x.Equal($y)`)
I suggest the $arg.type
syntax for this, since it is impossible to have such a method in Go code that parses.
Unfortunately the string argument to Implements
does no interpolation of parameters at the moment.
Sorry for the delayed response.
What makes it complicated is that normal Go parser can't handle $
symbols.
Only gogrep parser can do that.
But suppose we can parse it.
The other difficulty is that $x.type
that is not valid syntax for gogrep parser either. We could use something like typeof($x)
to circumvent that.
I like the rule that you're trying to express, but it's hard to predict when this feature will be implemented. #16 currently has higher priority and I'm still trying to find the free time to resolve it. :)