public List splitAnd()

in sources/src/main/java/com/google/solutions/jitaccess/catalog/legacy/IamCondition.java [113:187]


  public List<IamCondition> splitAnd() {
    //
    // The CEL library doesn't lend itself well for this, so
    // we have to parse the expression manually.
    //

    var clauses = new LinkedList<IamCondition>();
    var currentClause = new StringBuilder();

    //
    // Remove line comments.
    //
    var cleanedExpression = Arrays.stream(this.expression.split("\n"))
      .filter(line -> !line.trim().startsWith("//"))
      .collect(Collectors.joining("\n"));

    var bracesDepth = 0;
    var singleQuotes = 0;
    var doubleQuotes = 0;
    for (int i = 0; i < cleanedExpression.length(); i++)
    {
      var c = cleanedExpression.charAt(i);
      switch (c) {
        case '&':
          if (bracesDepth == 0 && // not inside a nested clause
            (singleQuotes % 2) == 0 && // quotes are balanced
            (doubleQuotes % 2) == 0 && // quotes are balanced
            i + 1 < cleanedExpression.length() &&
            cleanedExpression.charAt(i + 1) == '&') {

            //
            // We've encountered a top-level "&&".
            //
            clauses.addLast(new IamCondition(currentClause.toString()));
            currentClause.setLength(0);

            i++; // Skip the next "&".
          }
          else {
            currentClause.append(c);
          }
          break;

        case '(':
          bracesDepth++;
          currentClause.append(c);
          break;

        case ')':
          bracesDepth--;
          currentClause.append(c);
          break;

        case '\'':
          singleQuotes++;
          currentClause.append(c);
          break;

        case '"':
          doubleQuotes++;
          currentClause.append(c);
          break;

        default:
          currentClause.append(c);
          break;
      }
    }

    if (!currentClause.isEmpty()) {
      clauses.addLast(new IamCondition(currentClause.toString()));
    }

    return clauses;
  }