# Aliases for choice values

- Task: `task_001_types_parameter_va`
- Status: accepted
- Module: src/click/types.py
- Behaviour axis: parameter_validation_rules
- Files changed: src/click/types.py
- Repairs: 0

## Gates

| Gate | Result |
| --- | --- |
| Patch precheck | passed |
| Shape precheck | passed |
| Test hygiene precheck | passed |
| Interface precheck | passed |
| G1 Applies cleanly | passed |
| Base fail ratio | passed |
| G5 Every requirement tested | passed |
| G2 Fail-to-pass | passed |
| G3 No regressions | passed |
| G4 Same result every time | passed |
| G6 Mutation testing | passed |
| Harbor official checks | passed |
| N1 Not already in Click | passed |
| G7 Blind solve | passed |

Mutation testing (G6): 11 of 11 mutants caught.

Harbor: nop reward 0.0 (must be 0.0), oracle reward 1.0 (must be 1.0).

Blind solve (G7): reward 1.0, fail-to-pass 11 / 11, 0 regression failures, 1 attempt.

## instruction.md

The only file the agent under test sees.

# Aliases for Choice Values

## Problem Description

Extend `Choice` to accept alternate input strings that resolve to existing canonical choice values. Aliases must use the same normalization rules as canonical choices, including context-dependent normalization and `normalize_choice` overrides.

When aliases are omitted, existing behavior must remain unchanged.

## Acceptance Criteria

- **AC1**: `Choice` accepts an optional keyword-only `aliases` mapping from strings to values in `choices`. Conversion of a matching alias returns the corresponding original choice object.
- **AC2**: Alias keys, canonical choices, and conversion inputs are normalized through `normalize_choice` with the conversion context. This includes case sensitivity, the context token normalizer, and subclass overrides.
- **AC3**: Construction rejects alias targets that are not equal to a choice, and rejects invalid alias mapping or key types as specified below.
- **AC4**: Conversion rejects a normalized alias collision when the same normalized string would resolve to different choices. This includes alias-to-alias and alias-to-canonical collisions, including collisions introduced by the conversion context. Collisions resolving to the same choice are allowed.
- **AC5**: Omitted, `None`, or empty aliases preserve existing conversion and validation behavior, including existing handling of collisions among canonical choices.
- **AC6**: Help, completion, introspection, representations, and invalid-choice messages continue to show canonical choices as before; they do not advertise aliases.
- **AC7**: Add tests covering successful aliases, invalid configuration, collisions, context and subclass normalization, canonical object return values, and behavior without aliases.

## Interface

### Symbols

- `Choice`
- `Choice.convert`
- `Choice.normalize_choice`

### Contract Details

- `Choice.__init__(self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True, *, aliases: cabc.Mapping[str, _ValueT_co] | None = None) -> None`
  - `choices` retains its existing iterable and single-consumption behavior.
  - `aliases` maps alternate input strings to canonical choice values. `None` and an empty mapping mean no aliases.
  - The mapping is captured at construction; later mutations to the supplied mapping do not change the `Choice`.
  - A target belongs to `choices` if it compares equal to a choice. If more than one choice compares equal, the first such original choice is the alias result.
  - If `aliases` is neither `None` nor a mapping, raise `TypeError` with exactly `aliases must be a mapping`.
  - If any alias key is not a string, raise `TypeError` with exactly `alias keys must be strings`.
  - If any alias target is not equal to a choice, raise `ValueError` with exactly `alias target is not a choice`.
  - Validate mapping type, key types, and target membership during construction, in that order. Normalized collision validation occurs during conversion, not construction.

- `Choice.convert(self, value: t.Any, param: Parameter | None, ctx: Context | None) -> _ValueT_co`
  - Normalize the input, alias keys, and canonical choices using `normalize_choice` with the supplied `ctx`. Resolve a matching alias to its original canonical choice object.
  - When aliases are present, validate normalized alias collisions for the supplied context before returning any conversion result. If an alias shares a normalized string with another alias or canonical choice that resolves to a different choice, raise `ValueError` with exactly `normalized alias collision`.
  - Choices are considered the same for collision validation when they compare equal. A collision involving an alias and multiple canonical choices is invalid if any of those choices differs from the alias target.
  - Re-evaluate context-dependent collisions on each conversion. Preserve existing canonical-choice matching behavior when no alias matches and no alias collision exists.
  - For an unrecognized value, retain the existing `BadParameter` behavior and existing localized invalid-choice message format, listing canonical choices only.

- `Choice.normalize_choice(self, choice: object, ctx: Context | None) -> str`
  - Its signature and existing default behavior remain unchanged. Subclass overrides apply to alias keys as well as canonical choices and inputs.

## Compatibility & Out of Scope

- Existing positional arguments to `Choice` remain valid. `aliases` is keyword-only.
- Do not change the display or completion of choices to include aliases, or add aliases to existing introspection output.
- Do not change the existing treatment of canonical-only normalized collisions or broaden support for choice values beyond existing behavior.
- Preserve existing startup import constraints; do not introduce eager top-level standard-library imports that violate them.
- The entire existing repository test suite must continue to pass with zero regressions.

## Requirements and their tests

| Requirement | Text | Tests |
| --- | --- | --- |
| AC1 | `Choice` accepts an optional keyword-only `aliases` mapping from strings to values in `choices`. Conversion of a matching alias returns the corresponding original choice object. | test_aliases_return_original_objects_and_capture_mapping, test_equal_target_resolves_to_first_original_choice |
| AC2 | Alias keys, canonical choices, and conversion inputs are normalized through `normalize_choice` with the conversion context. This includes case sensitivity, the context token normalizer, and subclass overrides. | test_case_and_context_normalization_apply_to_aliases, test_subclass_normalization_applies_to_all_values |
| AC3 | Construction rejects alias targets that are not equal to a choice, and rejects invalid alias mapping or key types as specified below. | test_invalid_alias_configuration_and_validation_order |
| AC4 | Conversion rejects a normalized alias collision when the same normalized string would resolve to different choices. This includes alias-to-alias and alias-to-canonical collisions, including collisions introduced by the conversion context. Collisions resolving to the same choice are allowed. | test_alias_collisions_are_checked_before_any_result, test_collision_checks_every_canonical_choice, test_context_collisions_are_rechecked_on_each_conversion |
| AC5 | Omitted, `None`, or empty aliases preserve existing conversion and validation behavior, including existing handling of collisions among canonical choices. | test_no_aliases_preserve_canonical_collision_and_errors |
| AC6 | Help, completion, introspection, representations, and invalid-choice messages continue to show canonical choices as before; they do not advertise aliases. | test_help_completion_introspection_repr_and_errors_hide_aliases |
| AC7 | Add tests covering successful aliases, invalid configuration, collisions, context and subclass normalization, canonical object return values, and behavior without aliases. | test_single_consumption_and_single_choice_error |

Fail-to-pass tests: 11. Pass-to-pass tests: 2434.

## Mutants

| Mutant | Change | Caught |
| --- | --- | --- |
| M01_is_not_none_flip | src/click/types.py: if aliases is not None and not isinstance(aliases, cabc.Mapping): -> if aliases is None and not isinstance(aliases, cabc.Mapping): | yes |
| M02_raise_remove | src/click/types.py: raise TypeError("aliases must be a mapping") -> pass | yes |
| M03_is_not_none_flip | src/click/types.py: items = tuple(aliases.items()) if aliases is not None else () -> items = tuple(aliases.items()) if aliases is None else () | yes |
| M04_raise_remove | src/click/types.py: raise TypeError("alias keys must be strings") -> pass | yes |
| M05_eq_to_neq | src/click/types.py: if choice == target: -> if choice != target: | yes |
| M06_raise_remove | src/click/types.py: raise ValueError("alias target is not a choice") -> pass | yes |
| M07_eq_to_neq | src/click/types.py: normalized_aliases[normalized] == target -> normalized_aliases[normalized] != target | yes |
| M08_raise_remove | src/click/types.py: raise ValueError("normalized alias collision") -> pass | yes |
| M09_eq_to_neq | src/click/types.py: if canonical_key == normalized and not (choice == target): -> if canonical_key != normalized and not (choice == target): | yes |
| M10_raise_remove | src/click/types.py: raise ValueError("normalized alias collision") -> pass | yes |
| M11_return_val_none | src/click/types.py: return normalized_aliases[normed_value] -> return None | yes |

## Reference patch

````diff
diff --git a/src/click/types.py b/src/click/types.py
index b6e98a9..bdc7401 100644
--- a/src/click/types.py
+++ b/src/click/types.py
@@ -352,6 +352,8 @@ class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):
 
     :param case_sensitive: Set to false to make choices case
         insensitive. Defaults to true.
+    :param aliases: Alternate input strings mapped to existing choices.
+        Aliases are not shown in help or completion.
 
     .. versionchanged:: 8.4.0
         Now generic in the choice value type. Parameterize with the type of
@@ -373,11 +375,35 @@ class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):
     case_sensitive: bool
 
     def __init__(
-        self, choices: cabc.Iterable[_ValueT_co], case_sensitive: bool = True
+        self,
+        choices: cabc.Iterable[_ValueT_co],
+        case_sensitive: bool = True,
+        *,
+        aliases: cabc.Mapping[str, _ValueT_co] | None = None,
     ) -> None:
         self.choices = tuple(choices)
         self.case_sensitive = case_sensitive
 
+        if aliases is not None and not isinstance(aliases, cabc.Mapping):
+            raise TypeError("aliases must be a mapping")
+
+        items = tuple(aliases.items()) if aliases is not None else ()
+
+        if any(not isinstance(key, str) for key, _ in items):
+            raise TypeError("alias keys must be strings")
+
+        resolved = []
+
+        for key, target in items:
+            for choice in self.choices:
+                if choice == target:
+                    resolved.append((key, choice))
+                    break
+            else:
+                raise ValueError("alias target is not a choice")
+
+        self._aliases = tuple(resolved)
+
     def to_info_dict(self) -> ChoiceInfoDict[_ValueT_co]:
         return {
             "choices": self.choices,
@@ -462,6 +488,30 @@ class Choice(ParamType[_ValueT_co], t.Generic[_ValueT_co]):
         normed_value = self.normalize_choice(choice=value, ctx=ctx)
         normalized_mapping = self._normalized_mapping(ctx=ctx)
 
+        if self._aliases:
+            canonical = [
+                (self.normalize_choice(choice=choice, ctx=ctx), choice)
+                for choice in self.choices
+            ]
+            normalized_aliases: dict[str, _ValueT_co] = {}
+
+            for key, target in self._aliases:
+                normalized = self.normalize_choice(choice=key, ctx=ctx)
+
+                if normalized in normalized_aliases and not (
+                    normalized_aliases[normalized] == target
+                ):
+                    raise ValueError("normalized alias collision")
+
+                for canonical_key, choice in canonical:
+                    if canonical_key == normalized and not (choice == target):
+                        raise ValueError("normalized alias collision")
+
+                normalized_aliases[normalized] = target
+
+            if normed_value in normalized_aliases:
+                return normalized_aliases[normed_value]
+
         try:
             return next(
                 original
````

## Feature tests

### tests/feature/test_choice_aliases.py

````python
# TEST_CODE
from __future__ import annotations

import enum

import click
import pytest
from click.testing import CliRunner

# AC1
def test_aliases_return_original_objects_and_capture_mapping():
    class Color(enum.Enum):
        RED = 1
        BLUE = 2

    aliases = {"r": Color.RED, "b": Color.BLUE}
    choice = click.Choice((c for c in Color), aliases=aliases)
    aliases["r"] = Color.BLUE
    aliases["new"] = Color.RED

    assert choice.convert("r", None, None) is Color.RED
    assert choice.convert("b", None, None) is Color.BLUE
    assert choice.convert("RED", None, None) is Color.RED
    with pytest.raises(click.BadParameter):
        choice.convert("new", None, None)

# AC1
def test_equal_target_resolves_to_first_original_choice():
    class Label(str):
        pass

    first = Label("red")
    second = Label("red")
    target = Label("red")
    assert first == second == target
    assert first is not target

    choice = click.Choice([first, second], aliases={"r": target})
    assert choice.convert("r", None, None) is first
    assert choice.choices[1] is second

# AC2
def test_case_and_context_normalization_apply_to_aliases():
    choice = click.Choice(
        ["Red-Color", "Blue-Color"], False, aliases={"R-Shortcut": "Red-Color"}
    )
    ctx = click.Context(
        click.Command("cmd"), token_normalize_func=lambda value: value.replace("-", "_")
    )

    assert choice.convert("R_SHORTCUT", None, ctx) == "Red-Color"
    assert choice.convert("RED_COLOR", None, ctx) == "Red-Color"
    assert choice.convert("r-shortcut", None, None) == "Red-Color"
    with pytest.raises(click.BadParameter):
        choice.convert("R_SHORTCUT", None, None)

# AC2
def test_subclass_normalization_applies_to_all_values():
    class CompactChoice(click.Choice):
        def normalize_choice(self, choice, ctx):
            value = super().normalize_choice(choice, ctx)
            return value.replace("-", "").replace("_", "")

    choice = CompactChoice(["red-color", "blue"], aliases={"r-short": "red-color"})
    assert choice.convert("r_short", None, None) == "red-color"
    assert choice.convert("red_color", None, None) == "red-color"
    assert choice.convert("blue", None, None) == "blue"

# AC3
def test_invalid_alias_configuration_and_validation_order():
    with pytest.raises(TypeError, match="^aliases must be a mapping$"):
        click.Choice(["red"], aliases=[("r", "red")])
    with pytest.raises(TypeError, match="^aliases must be a mapping$"):
        click.Choice(["red"], aliases="red")
    with pytest.raises(TypeError, match="^alias keys must be strings$"):
        click.Choice(["red"], aliases={"bad": "missing", 1: "red"})
    with pytest.raises(ValueError, match="^alias target is not a choice$"):
        click.Choice(["red"], aliases={"r": "missing"})
    with pytest.raises(TypeError):
        click.Choice(["red"], True, {"r": "red"})

# AC4
def test_alias_collisions_are_checked_before_any_result():
    alias_collision = click.Choice(
        ["red", "blue"], False, aliases={"R": "red", "r": "blue"}
    )
    canonical_collision = click.Choice(
        ["red", "blue"], False, aliases={"BLUE": "red"}
    )

    for choice in (alias_collision, canonical_collision):
        for value in ("red", "unknown"):
            with pytest.raises(ValueError, match="^normalized alias collision$"):
                choice.convert(value, None, None)

    same_target = click.Choice(
        ["red", "blue"], False, aliases={"RED": "red", "Red": "red"}
    )
    assert same_target.convert("red", None, None) == "red"
    assert same_target.convert("blue", None, None) == "blue"

# AC4
def test_collision_checks_every_canonical_choice():
    choice = click.Choice(["red", "RED"], False, aliases={"Red": "red"})
    with pytest.raises(ValueError, match="^normalized alias collision$"):
        choice.convert("red", None, None)

    canonical_only_collision = click.Choice(
        ["red", "RED"], False, aliases={"shortcut": "red"}
    )
    assert canonical_only_collision.convert("red", None, None) == "red"
    assert canonical_only_collision.convert("shortcut", None, None) == "red"

# AC4
def test_context_collisions_are_rechecked_on_each_conversion():
    choice = click.Choice(["red", "blue"], aliases={"r-ed": "blue"})
    plain = click.Context(click.Command("plain"))
    compact = click.Context(
        click.Command("compact"), token_normalize_func=lambda value: value.replace("-", "")
    )

    assert choice.convert("r-ed", None, plain) == "blue"
    with pytest.raises(ValueError, match="^normalized alias collision$"):
        choice.convert("blue", None, compact)
    assert choice.convert("r-ed", None, plain) == "blue"

    alias_pair = click.Choice(
        ["red", "blue"], aliases={"r-ed": "red", "red": "blue"}
    )
    with pytest.raises(ValueError, match="^normalized alias collision$"):
        alias_pair.convert("red", None, compact)

# AC5
def test_no_aliases_preserve_canonical_collision_and_errors():
    choices = ["red", "RED", "blue"]
    explicit_none = click.Choice(choices, False, aliases=None)
    empty = click.Choice(choices, False, aliases={})
    omitted = click.Choice(choices, False)

    for choice in (explicit_none, empty, omitted):
        assert choice.convert("ReD", None, None) == "red"
        assert choice.convert("BLUE", None, None) == "blue"
        with pytest.raises(click.BadParameter) as exc:
            choice.convert("missing", None, None)
        assert exc.value.message == "'missing' is not one of 'red', 'red', 'blue'."

# AC6
def test_help_completion_introspection_repr_and_errors_hide_aliases():
    aliased = click.Choice(["red", "blue"], aliases={"shortcut": "red"})
    plain = click.Choice(["red", "blue"])
    param = click.Option(["--color"], type=aliased)
    ctx = click.Context(click.Command("cmd"))

    assert aliased.choices == plain.choices
    assert aliased.to_info_dict() == plain.to_info_dict()
    assert repr(aliased) == repr(plain) == "Choice(['red', 'blue'])"
    assert aliased.get_metavar(param, ctx) == plain.get_metavar(param, ctx)
    assert aliased.get_missing_message(param, ctx) == plain.get_missing_message(param, ctx)
    assert [item.value for item in aliased.shell_complete(ctx, param, "")] == [
        "red",
        "blue",
    ]
    assert aliased.shell_complete(ctx, param, "shortcut") == []

    with pytest.raises(click.BadParameter) as exc:
        aliased.convert("missing", param, ctx)
    assert exc.value.message == "'missing' is not one of 'red', 'blue'."

    @click.command()
    @click.option("--color", type=aliased)
    def command(color):
        click.echo(color)

    runner = CliRunner()
    help_result = runner.invoke(command, ["--help"])
    assert help_result.exit_code == 0
    assert "[red|blue]" in help_result.output
    assert "shortcut" not in help_result.output

    result = runner.invoke(command, ["--color", "shortcut"])
    assert result.exit_code == 0
    assert result.output == "red\n"

# AC7
def test_single_consumption_and_single_choice_error():
    seen = []

    def choices():
        for value in ("red",):
            seen.append(value)
            yield value

    choice = click.Choice(choices(), aliases={"r": "red"})
    assert seen == ["red"]
    assert choice.convert("r", None, None) == "red"
    assert choice.convert("red", None, None) == "red"
    assert seen == ["red"]
    with pytest.raises(click.BadParameter) as exc:
        choice.convert("missing", None, None)
    assert exc.value.message == "'missing' is not 'red'."
````
