Skip to content

Commit

Permalink
Handle Pattern.compile(String, int) with two formal parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
mernst committed May 4, 2022
1 parent 49fc554 commit f5fbfb7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
Expand Up @@ -112,6 +112,14 @@ public class RegexAnnotatedTypeFactory extends BaseAnnotatedTypeFactory {
private final ExecutableElement patternCompile =
TreeUtils.getMethod("java.util.regex.Pattern", "compile", 1, processingEnv);

/**
* The Pattern.compile method that takes two formal parameters (second one is flags).
*
* @see java.util.regex.Pattern#compile(String, int)
*/
private final ExecutableElement patternCompile2 =
TreeUtils.getMethod("java.util.regex.Pattern", "compile", 2, processingEnv);

/**
* Create a new RegexAnnotatedTypeFactory.
*
Expand Down Expand Up @@ -416,8 +424,8 @@ public Void visitCompoundAssignment(CompoundAssignmentTree node, AnnotatedTypeMi
*/
@Override
public Void visitMethodInvocation(MethodInvocationTree tree, AnnotatedTypeMirror type) {
// TODO: Also get this to work with 2 argument Pattern.compile.
if (TreeUtils.isMethodInvocation(tree, patternCompile, processingEnv)) {
if (TreeUtils.isMethodInvocation(tree, patternCompile, processingEnv)
|| TreeUtils.isMethodInvocation(tree, patternCompile2, processingEnv)) {
ExpressionTree arg0 = tree.getArguments().get(0);

final AnnotatedTypeMirror argType = getAnnotatedType(arg0);
Expand Down
7 changes: 7 additions & 0 deletions checker/tests/regex/GroupCounts.java
Expand Up @@ -28,18 +28,25 @@ void testGroupCount() {

void testPatternCompileGroupCount(@Regex String r, @Regex(3) String r3, @Regex(5) String r5) {
@Regex(5) Pattern p1 = Pattern.compile(r5);
@Regex(5) Pattern p1a = Pattern.compile(r5, 0);
@Regex Pattern p2 = Pattern.compile(r5);
@Regex Pattern p3 = Pattern.compile(r);

// :: error: (assignment)
@Regex(6) Pattern p4 = Pattern.compile(r5); // error
// :: error: (assignment)
@Regex(6) Pattern p4a = Pattern.compile(r5, 0); // error
// :: error: (assignment)
@Regex(6) Pattern p5 = Pattern.compile(r3); // error
// :: error: (assignment)
@Regex(6) Pattern p5a = Pattern.compile(r3, 0); // error

// Make sure Pattern.compile still works when passed an @UnknownRegex String
// that's actually a regex, with the warning suppressed.
@SuppressWarnings("regex:argument")
Pattern p6 = Pattern.compile("(" + r + ")");
@SuppressWarnings("regex:argument")
Pattern p6a = Pattern.compile("(" + r + ")", 0);
}

void testConcatenationGroupCount(@Regex String r, @Regex(3) String r3, @Regex(5) String r5) {
Expand Down

0 comments on commit f5fbfb7

Please sign in to comment.