2

I am trying to create a custom inspection in IntelliJ using structural search. The idea is to find all methods that have one or more parameters, of which at least one is not annotated. Bonus: Only hit non-primitive types of parameters.

So far, I have created the following Search Template:

$MethodType$ $Method$(@$ParamAnnotation$ $ParameterType$ $Parameter$);

using these filters and the search target "complete match":

$Parameters$: count[1,∞]
$ParamAnnotation$: count[0,0]

However, this only hits methods without any parameters annotated. I want it to also match methods where only some parameters have an annotation but others don't.

Is it possible to reference the count of one variable in the filter of another, e.g. by using script filters? If so, how?

cygnus
  • 195
  • 1
  • 12
  • An ugly, but possibly sufficient solution would be to create multiple search templates, each with a constant number of expected parameters and annotations. – cygnus Feb 27 '19 at 14:46

1 Answers1

3

You can do this by creating a Search Template like this:

$MethodType$ $Method$($TypeBefore$ $before$, 
                      @$ParamAnnotation$ $ParameterType$ $Parameter$, 
                      $TypeAfter$ $after$);

Filters:

$Parameters$: count=[1,1] // i.e. no filter
$ParamAnnotation$: count=[0,0]
$before$: count=[0,∞]
$after$: count=[0,∞]

This will find all method with at least one parameter without annotation.

Bas Leijdekkers
  • 23,709
  • 4
  • 70
  • 68
  • Thanks, this works! However, when entering the filter `$Parameters$: count=[1,1]` does not - it gets instantly and automatically removed. Is having no filter equivalent to `count=[1,1]`? – cygnus Mar 01 '19 at 09:00
  • 1
    Yes, `count=[1,1]` is indeed equivalent to no filter. I just mentioned it because you had a different filter on `$Parameter$`. – Bas Leijdekkers Mar 01 '19 at 10:26
  • I tested a bit more and the filter does not seem to hit this constructor: `public ClassA(final ParamType param1, final ParamType2 param2, final ParamType3 param3, final ParamType4 param4, final ParamType5 param5)` Are constructors not considered methods? – cygnus Mar 01 '19 at 16:34
  • 1
    No, constructors are not considered methods. You will have to create a separate pattern for them. – Bas Leijdekkers Mar 04 '19 at 11:42
  • 1
    Update: since IntelliJ IDEAE 2019.2 it is possible to match methods and constructors with a single query. To do this add a count=[0,1] filter to $MethodType$. See the existing template "constructors & methods" for an example. – Bas Leijdekkers Mar 03 '20 at 13:12