1/*
2 * Copyright 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.tools.build.jetifier.processor.transform.proguard.patterns
18
19import java.util.regex.Pattern
20
21/**
22 * Helps to build regular expression [Pattern]s defined with less verbose syntax.
23 *
24 * You can use following shortcuts:
25 * '⦅⦆' - denotes a capturing group (normally '()' is capturing group)
26 * '()' - denotes non-capturing group (normally (?:) is non-capturing group)
27 * ' ' - denotes a whitespace characters (at least one)
28 * ' *' - denotes a whitespace characters (any)
29 * ';' - denotes ' *;'
30 */
31object PatternHelper {
32
33    private val rewrites = listOf(
34        " *" to "[\\s]*", // Optional space
35        " " to "[\\s]+", // Space
36        "⦅" to "(", // Capturing group start
37        "⦆" to ")", // Capturing group end
38        ";" to "[\\s]*;" // Allow spaces in front of ';'
39    )
40
41    /**
42     * Transforms the given [toReplace] according to the rules defined in documentation of this
43     * class and compiles it to a [Pattern].
44     */
45    fun build(toReplace: String, flags: Int = 0): Pattern {
46        var result = toReplace
47        result = result.replace("(?<!\\\\)\\(".toRegex(), "(?:")
48        rewrites.forEach { result = result.replace(it.first, it.second) }
49        return Pattern.compile(result, flags)
50    }
51}