Skip to content

Commit

Permalink
Compile regexes on UnaryFunctionCall
Browse files Browse the repository at this point in the history
  • Loading branch information
srchase committed May 8, 2023
1 parent 59b5ad5 commit 52ae1ba
Showing 1 changed file with 10 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,15 @@

package software.amazon.smithy.typescript.codegen.validation;

import java.util.regex.Pattern;

/**
* For handling expressions that may be unary function calls.
*/
public abstract class UnaryFunctionCall {
private static final Pattern CHECK_PATTERN = Pattern.compile("^(?!new ).+\\(((?!,).)*\\)$");
private static final Pattern TO_REF_PATTERN = Pattern.compile("(.*)\\(.*\\)$");

/**
* @param expression - to be examined.
* @return whether the expression is a single-depth function call with a single parameter.
Expand All @@ -18,27 +23,22 @@ public static boolean check(String expression) {
// not a call per se, but this indicates a pass-through function.
return true;
}
return maxCallDepth(expression) == 1
&& expression.matches(".+\\(.*\\)$")
&& !expression.contains("new ")
&& !expression.contains(",");
return maxCallDepth(expression) == 1 && CHECK_PATTERN.matcher(expression).matches();
}

/**
* @param callExpression - the call expression to be converted. Check that
* the expression is a unary call first.
* @param callExpression the call expression to be converted. Check that
* the expression is a unary call first.
* @return the unary function call converted to a function reference.
*/
public static String toRef(String callExpression) {
return callExpression.replaceAll("(.*)\\(.*\\)$", "$1");
return TO_REF_PATTERN.matcher(callExpression).replaceAll("$1");
}

/**
* Estimates the call depth of a function call expression.
*
* @example
* call() == 1
* call(call()) == 2
* @param expression A function call expression (e.g., "call() == 1", "call(call()) == 2", etc).
*/
private static int maxCallDepth(String expression) {
int depth = 0;
Expand Down

0 comments on commit 52ae1ba

Please sign in to comment.