test: add benchmarks and a step counter for the Starlark code

The version parsing and the marker evaluation is executed many times
during the module extension evaluation and there was no way to know if
a change makes it slower.

Add a shim that executes the `.bzl` files with CPython and counts the
executed lines, which does not depend on the machine and can be
asserted in a test.
The `//tests/perf:steps_test` has the number of steps for a set of
workloads and `//tests/perf:benchmark` prints them.

The steps are a proxy, hence `//tests/perf:bazel_benchmark` measures
the same workloads with Bazel itself. The workload is executed during
the analysis of a target and the number of iterations is a build flag,
so the time of an iteration is the difference of the wall time of 2
builds divided by the difference of the iterations.

The results are recorded in the README.
diff --git a/python/private/BUILD.bazel b/python/private/BUILD.bazel
index 78e4c48..47fb78d 100644
--- a/python/private/BUILD.bazel
+++ b/python/private/BUILD.bazel
@@ -79,6 +79,7 @@
 exports_files(
     [
         "coverage.patch",
+        "enum.bzl",
         "py_package.bzl",
         "py_wheel.bzl",
         "version.bzl",
diff --git a/tests/perf/BUILD.bazel b/tests/perf/BUILD.bazel
new file mode 100644
index 0000000..bbbe3eb
--- /dev/null
+++ b/tests/perf/BUILD.bazel
@@ -0,0 +1,62 @@
+load("@bazel_skylib//rules:common_settings.bzl", "int_flag", "string_flag")
+load("//python:py_binary.bzl", "py_binary")
+load("//python:py_library.bzl", "py_library")
+load("//python:py_test.bzl", "py_test")
+load(":bazel_benchmark.bzl", "bazel_benchmark")
+load(":workloads.bzl", "WORKLOADS")
+
+py_library(
+    name = "workloads",
+    srcs = [
+        "starlark_shim.py",
+        "workloads.py",
+    ],
+    data = [
+        "workloads.bzl",
+        "//python/private:enum.bzl",
+        "//python/private:version.bzl",
+        "//python/private/pypi:bzl",
+    ],
+    deps = ["//python/runfiles"],
+)
+
+# Print the number of steps that the workloads take:
+#
+#     bazel run //tests/perf:benchmark
+py_binary(
+    name = "benchmark",
+    srcs = ["benchmark.py"],
+    deps = [":workloads"],
+)
+
+py_test(
+    name = "steps_test",
+    srcs = ["steps_test.py"],
+    deps = [":workloads"],
+)
+
+# Measure the workloads with Bazel itself:
+#
+#     bazel run //tests/perf:bazel_benchmark
+py_binary(
+    name = "bazel_benchmark",
+    srcs = ["bazel_benchmark.py"],
+    args = ["--workloads=" + ",".join(WORKLOADS.keys())],
+)
+
+# The flags and the target that are used by the `bazel_benchmark`.
+int_flag(
+    name = "iterations",
+    build_setting_default = 0,
+)
+
+string_flag(
+    name = "workload",
+    build_setting_default = WORKLOADS.keys()[0],
+    values = WORKLOADS.keys(),
+)
+
+bazel_benchmark(
+    name = "bazel_benchmark_analysis",
+    tags = ["manual"],
+)
diff --git a/tests/perf/README.md b/tests/perf/README.md
new file mode 100644
index 0000000..665a17c
--- /dev/null
+++ b/tests/perf/README.md
@@ -0,0 +1,101 @@
+# Performance of the Starlark code
+
+The version and the environment marker handling is executed many times when
+`pip.parse` is evaluated: for every requirement, for every target platform and
+for every Python version. This directory has the tools to ensure that this code
+stays fast.
+
+The measured workloads are in `workloads.bzl`.
+
+## Counting the steps
+
+Bazel cannot count how many steps the Starlark interpreter executes. However,
+the `.bzl` files that only have pure functions are almost valid Python, so
+`starlark_shim.py` executes them with CPython and counts the executed lines of
+the `.bzl` files, which we call _steps_.
+
+The number of steps does not depend on the machine and it changes when the
+amount of work that the code does changes. It only slightly depends on the
+Python version, hence the test below has a tolerance of 5%.
+
+The shim is not a Starlark interpreter, it only supports what the measured
+files need. If you start using something that is not supported, extend the
+shim.
+
+Print the number of steps that the workloads take:
+
+```shell
+bazel run //tests/perf:benchmark
+```
+
+Only run the workloads that have `version` in the name:
+
+```shell
+bazel run //tests/perf:benchmark -- version
+```
+
+`//tests/perf:steps_test` runs as part of the regular tests and it fails if
+the number of steps of a workload changes by more than that. If the code got slower, then either
+fix the code or, if the extra work is necessary, update the numbers in
+`steps_test.py`. If the code got faster, then update the numbers, so that it
+stays that way. In both cases update the results below.
+
+## Measuring with Bazel
+
+The steps are a proxy, so there is also a benchmark that measures the
+workloads with Bazel itself:
+
+```shell
+bazel run //tests/perf:bazel_benchmark
+```
+
+It builds `//tests/perf:bazel_benchmark_analysis`, which executes the workload
+that is selected with `--//tests/perf:workload` for
+`--//tests/perf:iterations` times during the analysis. Starlark does not have
+a clock, so the time of a single iteration is the difference of the wall time
+of 2 builds divided by the difference of the iterations. This takes a long
+time and the results depend on the machine, hence it is not a test.
+
+If you run Bazel with startup options, pass the same ones to the benchmark,
+otherwise the Bazel server restarts for every build:
+
+```shell
+bazel --host_jvm_args=-Xmx2g run //tests/perf:bazel_benchmark -- \
+    --bazel="bazel --host_jvm_args=-Xmx2g"
+```
+
+The same target can be used to profile the code with `--starlark_cpu_profile`,
+see https://bazel.build/rules/performance#performance-profiling:
+
+```shell
+bazel build //tests/perf:bazel_benchmark_analysis \
+    --//tests/perf:workload=evaluate_long \
+    --//tests/perf:iterations=10000 \
+    --starlark_cpu_profile=/tmp/profile.gz
+```
+
+## Results
+
+The time is of Bazel 9.1.1 on a laptop, only the ratios are meaningful.
+
+| Workload | Steps | Bazel, µs |
+|---|---:|---:|
+| `evaluate_long` | 11056 | 2009.7 |
+| `evaluate_non_strict` | 703 | 74.2 |
+| `evaluate_string` | 362 | 34.9 |
+| `evaluate_two_strings` | 750 | 81.3 |
+| `evaluate_version` | 1975 | 432.7 |
+| `tokenize_long` | 4870 | 424.0 |
+| `tokenize_no_whitespace` | 563 | 49.6 |
+| `tokenize_version` | 305 | 27.5 |
+| `version_is_compatible` | 64 | 8.6 |
+| `version_is_eq_prefix` | 10 | 2.5 |
+| `version_is_ge` | 54 | 6.2 |
+| `version_is_lt` | 48 | 6.3 |
+| `version_key` | 26 | 2.7 |
+| `version_normalize` | 950 | 218.5 |
+| `version_parse_all_segments` | 1514 | 335.6 |
+| `version_parse_invalid` | 628 | 137.6 |
+| `version_parse_pre_release` | 1016 | 239.6 |
+| `version_parse_prefix` | 784 | 178.4 |
+| `version_parse_release` | 881 | 201.1 |
diff --git a/tests/perf/bazel_benchmark.bzl b/tests/perf/bazel_benchmark.bzl
new file mode 100644
index 0000000..8e3d162
--- /dev/null
+++ b/tests/perf/bazel_benchmark.bzl
@@ -0,0 +1,20 @@
+"""A rule to measure the Starlark code with Bazel itself, see the README.md."""
+
+load("@bazel_skylib//rules:common_settings.bzl", "BuildSettingInfo")
+load(":workloads.bzl", "WORKLOADS")
+
+def _bazel_benchmark_impl(ctx):
+    fn = WORKLOADS[ctx.attr._workload[BuildSettingInfo].value]
+    for _ in range(ctx.attr._iterations[BuildSettingInfo].value):
+        fn()
+
+    return []
+
+bazel_benchmark = rule(
+    implementation = _bazel_benchmark_impl,
+    doc = "Runs the workload that is selected with the flags during the analysis.",
+    attrs = {
+        "_iterations": attr.label(default = ":iterations"),
+        "_workload": attr.label(default = ":workload"),
+    },
+)
diff --git a/tests/perf/bazel_benchmark.py b/tests/perf/bazel_benchmark.py
new file mode 100644
index 0000000..a957d79
--- /dev/null
+++ b/tests/perf/bazel_benchmark.py
@@ -0,0 +1,104 @@
+"""Measure the Starlark code with Bazel itself and print a Markdown table.
+
+    bazel run //tests/perf:bazel_benchmark
+
+The workload is executed during the analysis of a target and the number of the
+iterations is a build flag, so the time of a single iteration is the
+difference of the wall time of 2 builds divided by the difference of the
+iterations. See the README.md for details.
+"""
+
+import argparse
+import itertools
+import os
+import statistics
+import subprocess
+import time
+
+_TARGET = "//tests/perf:bazel_benchmark_analysis"
+
+# The analysis is cached, so every build needs a different number of iterations.
+_UNIQUE = itertools.count()
+
+
+def _build(bazel, workload, iterations):
+    """Analyze the target and return the wall time in seconds."""
+    cmd = bazel + [
+        "build",
+        _TARGET,
+        "--//tests/perf:workload={}".format(workload),
+        "--//tests/perf:iterations={}".format(iterations + next(_UNIQUE)),
+    ]
+    start = time.perf_counter()
+    subprocess.run(cmd, check=True, capture_output=True)
+    return time.perf_counter() - start
+
+
+def _measure(bazel, workload, *, min_seconds, repeat):
+    """Return the time of a single iteration in microseconds."""
+
+    # Find the number of iterations that takes long enough for the noise of
+    # the Bazel invocation itself to not matter.
+    iterations = 1000
+    while iterations < 10**7:
+        if (
+            _build(bazel, workload, iterations) - _build(bazel, workload, 0)
+            >= min_seconds
+        ):
+            break
+        iterations *= 4
+
+    samples = [
+        (_build(bazel, workload, 2 * iterations) - _build(bazel, workload, iterations))
+        / iterations
+        * 1e6
+        for _ in range(repeat)
+    ]
+    return statistics.median(samples)
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("filter", nargs="?", default="")
+    parser.add_argument(
+        "--bazel",
+        default="bazel",
+        help="The Bazel command, the startup options can be included.",
+    )
+    parser.add_argument(
+        "--workloads",
+        required=True,
+        help="The comma separated names of the workloads, set by the BUILD file.",
+    )
+    parser.add_argument(
+        "--min-seconds",
+        type=float,
+        default=0.5,
+        help="Increase the iterations until the workload takes at least this long.",
+    )
+    parser.add_argument("--repeat", type=int, default=3)
+    args = parser.parse_args()
+
+    workspace = os.environ.get("BUILD_WORKSPACE_DIRECTORY")
+    if workspace:
+        os.chdir(workspace)
+
+    bazel = args.bazel.split()
+    workloads = [w for w in args.workloads.split(",") if args.filter in w]
+    if not workloads:
+        parser.error("No workload matches: " + args.filter)
+
+    # Start the server and load the packages.
+    _build(bazel, workloads[0], 0)
+
+    print("| Workload | Time, µs |")
+    print("|---|---:|")
+    for workload in workloads:
+        micros = _measure(
+            bazel, workload, min_seconds=args.min_seconds, repeat=args.repeat
+        )
+        print("| `{}` | {:.1f} |".format(workload, micros), flush=True)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tests/perf/benchmark.py b/tests/perf/benchmark.py
new file mode 100644
index 0000000..a9b8382
--- /dev/null
+++ b/tests/perf/benchmark.py
@@ -0,0 +1,24 @@
+"""Print the number of steps that the workloads take as a Markdown table.
+
+    bazel run //tests/perf:benchmark
+
+See the README.md for details.
+"""
+
+import sys
+
+from tests.perf import starlark_shim
+from tests.perf.workloads import workloads
+
+
+def main(argv):
+    only = argv[0] if argv else ""
+    print("| Workload | Steps |")
+    print("|---|---:|")
+    for name, fn in workloads().items():
+        if only in name:
+            print("| `{}` | {} |".format(name, starlark_shim.count_steps(fn)))
+
+
+if __name__ == "__main__":
+    main(sys.argv[1:])
diff --git a/tests/perf/starlark_shim.py b/tests/perf/starlark_shim.py
new file mode 100644
index 0000000..eed139a
--- /dev/null
+++ b/tests/perf/starlark_shim.py
@@ -0,0 +1,129 @@
+"""Executes a subset of Starlark with CPython to measure what the code does.
+
+Bazel does not have a way to benchmark or to count the steps that the Starlark
+interpreter executes, but the `.bzl` files that only have pure functions are
+almost valid Python, so we can execute them with CPython and count the
+executed lines instead. The absolute numbers are not what Bazel would report,
+however they are deterministic and they change when the algorithm changes.
+
+Only what is needed by the measured files is supported:
+* `load()` of the files from this repository.
+* `struct`, `fail`, `type` and `str.elems`.
+"""
+
+import re
+import sys
+import types
+
+_LOAD = re.compile(r"^load\((.*?)\)[ \t]*(#[^\n]*)?$", flags=re.MULTILINE | re.DOTALL)
+
+_TYPE_NAMES = {
+    bool: "bool",
+    dict: "dict",
+    int: "int",
+    list: "list",
+    str: "string",
+    tuple: "tuple",
+    type(None): "NoneType",
+}
+
+
+class StarlarkFail(Exception):
+    """Raised when the Starlark code calls `fail`."""
+
+
+class _Struct:
+    def __init__(self, **kwargs):
+        self.__dict__.update(kwargs)
+
+
+def _fail(*args):
+    raise StarlarkFail(" ".join([str(a) for a in args]))
+
+
+def _type(value):
+    name = _TYPE_NAMES.get(type(value))
+    if name:
+        return name
+    if isinstance(value, types.FunctionType):
+        return "function"
+    if isinstance(value, _Struct):
+        return "struct"
+    return "builtin_function_or_method"
+
+
+class Shim:
+    """Loads `.bzl` files as Python modules."""
+
+    def __init__(self, resolve):
+        """Create the shim.
+
+        Args:
+            resolve: a function to get the file path from the path relative to
+                the repository root.
+        """
+        self._resolve = resolve
+        self._modules = {}
+
+    def load(self, label):
+        """Load the file and return its globals.
+
+        Args:
+            label: the label of the `.bzl` file, e.g. `//python/private:version.bzl`.
+
+        Returns:
+            The dict of the globals of the module.
+        """
+        if not label.startswith("//"):
+            raise ValueError(
+                "Only the files of this repository are supported: " + label
+            )
+        if label in self._modules:
+            return self._modules[label]
+
+        package = label[2:].partition(":")[0]
+        path = self._resolve(label[2:].replace(":", "/"))
+
+        # The strings in Bazel are sequences of bytes.
+        with open(path, encoding="latin-1") as f:
+            src = f.read()
+
+        module = {"struct": _Struct, "fail": _fail, "_shim_type": _type}
+        for match in _LOAD.finditer(src):
+            args = [a.strip() for a in match.group(1).split(",") if a.strip()]
+            dep = args[0].strip('"')
+            if dep.startswith(":"):
+                dep = "//{}{}".format(package, dep)
+            dep_module = self.load(dep)
+            for arg in args[1:]:
+                name, _, symbol = arg.partition("=")
+                symbol = (symbol or name).strip().strip('"')
+                module[name.strip().strip('"')] = dep_module[symbol]
+
+        # Keep the line numbers the same as in the original file.
+        src = _LOAD.sub(lambda m: "\n" * m.group(0).count("\n"), src)
+        src = src.replace(".elems()", "")
+        src = re.sub(r"\btype\(", "_shim_type(", src)
+
+        exec(compile(src, path, "exec"), module)  # pylint: disable=exec-used
+        self._modules[label] = module
+        return module
+
+
+def count_steps(fn):
+    """Count the lines of the `.bzl` files that are executed by `fn`."""
+    steps = [0]
+
+    def trace(frame, event, _arg):
+        if not frame.f_code.co_filename.endswith(".bzl"):
+            return None
+        if event == "line":
+            steps[0] += 1
+        return trace
+
+    sys.settrace(trace)
+    try:
+        fn()
+    finally:
+        sys.settrace(None)
+    return steps[0]
diff --git a/tests/perf/steps_test.py b/tests/perf/steps_test.py
new file mode 100644
index 0000000..4fc64a4
--- /dev/null
+++ b/tests/perf/steps_test.py
@@ -0,0 +1,54 @@
+"""Tests that the Starlark code does not get slower without us noticing."""
+
+import unittest
+
+from tests.perf import starlark_shim
+from tests.perf.workloads import workloads
+
+# The number of steps that each workload takes, see the README.md. Update the
+# numbers with the output of `bazel run //tests/perf:benchmark`.
+_STEPS = {
+    # keep sorted
+    "evaluate_long": 11056,
+    "evaluate_non_strict": 703,
+    "evaluate_string": 362,
+    "evaluate_two_strings": 750,
+    "evaluate_version": 1975,
+    "tokenize_long": 4870,
+    "tokenize_no_whitespace": 563,
+    "tokenize_version": 305,
+    "version_is_compatible": 64,
+    "version_is_eq_prefix": 10,
+    "version_is_ge": 54,
+    "version_is_lt": 48,
+    "version_key": 26,
+    "version_normalize": 950,
+    "version_parse_all_segments": 1514,
+    "version_parse_invalid": 628,
+    "version_parse_pre_release": 1016,
+    "version_parse_prefix": 784,
+    "version_parse_release": 881,
+}
+
+# The number of the steps slightly depends on the Python version.
+_TOLERANCE = 0.05
+
+
+class StepsTest(unittest.TestCase):
+    def test_all_workloads_are_measured(self):
+        self.assertEqual(sorted(_STEPS), sorted(workloads()))
+
+    def test_steps(self):
+        for name, fn in workloads().items():
+            with self.subTest(name):
+                want = _STEPS[name]
+                self.assertAlmostEqual(
+                    starlark_shim.count_steps(fn),
+                    want,
+                    delta=want * _TOLERANCE,
+                    msg="The number of steps has changed, see tests/perf/README.md",
+                )
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/perf/workloads.bzl b/tests/perf/workloads.bzl
new file mode 100644
index 0000000..74fa9f5
--- /dev/null
+++ b/tests/perf/workloads.bzl
@@ -0,0 +1,60 @@
+"""The workloads that are measured by the benchmarks and the steps test."""
+
+load("//python/private:version.bzl", "version")  # buildifier: disable=bzl-visibility
+load("//python/private/pypi:pep508_evaluate.bzl", "evaluate", "tokenize")  # buildifier: disable=bzl-visibility
+
+_ENV = {
+    "extra": "foo",
+    "implementation_name": "cpython",
+    "implementation_version": "3.11.4",
+    "os_name": "posix",
+    "platform_machine": "x86_64",
+    "platform_python_implementation": "CPython",
+    "platform_release": "6.1.0",
+    "platform_system": "Linux",
+    "platform_version": "#1 SMP Debian",
+    "python_full_version": "3.11.4",
+    "python_version": "3.11",
+    "sys_platform": "linux",
+}
+
+# This is what the universal lock files have for the packages that are only
+# built for some of the platforms.
+_LONG_MARKER = (
+    "(python_full_version >= '3.12' and platform_machine == 'aarch64' and sys_platform == 'linux')" +
+    " or (python_full_version >= '3.12' and platform_machine == 'x86_64' and sys_platform == 'linux')" +
+    " or (python_full_version < '3.12' and platform_machine != 'aarch64'" +
+    " and platform_machine != 'x86_64' and sys_platform == 'linux')" +
+    " or sys_platform == 'darwin' or sys_platform == 'win32'"
+)
+
+_V_3_8 = version.parse("3.8")
+_V_3_11_4 = version.parse("3.11.4")
+_V_3_11_PREFIX = version.parse("3.11.*")
+
+WORKLOADS = {
+    # keep sorted
+    "evaluate_long": lambda: evaluate(_LONG_MARKER, env = _ENV),
+    "evaluate_non_strict": lambda: evaluate(
+        "python_version < '3.11' and extra == 'dev'",
+        env = {"extra": "dev"},
+        strict = False,
+    ),
+    "evaluate_string": lambda: evaluate("sys_platform == 'win32'", env = _ENV),
+    "evaluate_two_strings": lambda: evaluate("os_name == 'posix' and sys_platform == 'linux'", env = _ENV),
+    "evaluate_version": lambda: evaluate("python_version >= '3.8'", env = _ENV),
+    "tokenize_long": lambda: tokenize(_LONG_MARKER),
+    "tokenize_no_whitespace": lambda: tokenize("python_version>='3.8' and os_name=='posix'"),
+    "tokenize_version": lambda: tokenize("python_version >= '3.8'"),
+    "version_is_compatible": lambda: version.is_compatible(_V_3_11_4, _V_3_8),
+    "version_is_eq_prefix": lambda: version.is_eq(_V_3_11_4, _V_3_11_PREFIX),
+    "version_is_ge": lambda: version.is_ge(_V_3_11_4, _V_3_8),
+    "version_is_lt": lambda: version.is_lt(_V_3_11_4, _V_3_8),
+    "version_key": lambda: version.key(_V_3_11_4),
+    "version_normalize": lambda: version.normalize("2023.07.19"),
+    "version_parse_all_segments": lambda: version.parse("1!2.0.0rc1.post3.dev4+ubuntu.7"),
+    "version_parse_invalid": lambda: version.parse("#1 SMP Debian"),
+    "version_parse_pre_release": lambda: version.parse("3.13.0rc1"),
+    "version_parse_prefix": lambda: version.parse("3.11.*"),
+    "version_parse_release": lambda: version.parse("3.11.4"),
+}
diff --git a/tests/perf/workloads.py b/tests/perf/workloads.py
new file mode 100644
index 0000000..c66b5b3
--- /dev/null
+++ b/tests/perf/workloads.py
@@ -0,0 +1,32 @@
+"""Loads the workloads from `workloads.bzl` with the shim."""
+
+import os
+
+from tests.perf import starlark_shim
+
+
+def workloads():
+    """Return the dict of the workload names and the functions to measure."""
+    shim = starlark_shim.Shim(_resolver())
+    return shim.load("//tests/perf:workloads.bzl")["WORKLOADS"]
+
+
+def _resolver():
+    # When executed from the root of the repository without Bazel.
+    if os.path.exists("python/private/version.bzl"):
+        return lambda path: path
+
+    from python.runfiles import runfiles
+
+    rfiles = runfiles.Create()
+    assert rfiles is not None, "Failed to create runfiles"
+
+    def resolve(path):
+        # The main repository is `_main` with bzlmod and `rules_python` without.
+        for repo in ["_main", "rules_python"]:
+            resolved = rfiles.Rlocation("{}/{}".format(repo, path))
+            if resolved and os.path.exists(resolved):
+                return resolved
+        raise FileNotFoundError(path)
+
+    return resolve